1 /* $NetBSD: ssh-agent.c,v 1.42 2025/04/10 13:27:57 martin Exp $ */
2 /* $OpenBSD: ssh-agent.c,v 1.310 2025/02/18 08:02:48 djm Exp $ */
3
4 /*
5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * All rights reserved
8 * The authentication agent program.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 *
16 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
20 * are met:
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include "includes.h"
40 __RCSID("$NetBSD: ssh-agent.c,v 1.42 2025/04/10 13:27:57 martin Exp $");
41
42 #include <sys/param.h> /* MIN MAX */
43 #include <sys/types.h>
44 #include <sys/time.h>
45 #include <sys/queue.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <sys/stat.h>
49 #include <sys/un.h>
50 #include <sys/wait.h>
51
52 #ifdef WITH_OPENSSL
53 #include <openssl/evp.h>
54 #endif
55
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <paths.h>
59 #include <poll.h>
60 #include <signal.h>
61 #include <stdlib.h>
62 #include <stdio.h>
63 #include <string.h>
64 #include <stdarg.h>
65 #include <limits.h>
66 #include <time.h>
67 #include <unistd.h>
68 #include <util.h>
69
70 #include "xmalloc.h"
71 #include "ssh.h"
72 #include "ssh2.h"
73 #include "sshbuf.h"
74 #include "sshkey.h"
75 #include "authfd.h"
76 #include "log.h"
77 #include "misc.h"
78 #include "getpeereid.h"
79 #include "digest.h"
80 #include "ssherr.h"
81 #include "match.h"
82 #include "msg.h"
83 #include "pathnames.h"
84 #include "ssh-pkcs11.h"
85 #include "sk-api.h"
86 #include "myproposal.h"
87
88 #ifndef DEFAULT_ALLOWED_PROVIDERS
89 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/pkg/lib*/*"
90 #endif
91 #ifndef DEFAULT_WEBSAFE_ALLOWLIST
92 # define DEFAULT_WEBSAFE_ALLOWLIST "ssh:*"
93 #endif
94
95 /* Maximum accepted message length */
96 #define AGENT_MAX_LEN (256*1024)
97 /* Maximum bytes to read from client socket */
98 #define AGENT_RBUF_LEN (4096)
99 /* Maximum number of recorded session IDs/hostkeys per connection */
100 #define AGENT_MAX_SESSION_IDS 16
101 /* Maximum size of session ID */
102 #define AGENT_MAX_SID_LEN 128
103 /* Maximum number of destination constraints to accept on a key */
104 #define AGENT_MAX_DEST_CONSTRAINTS 1024
105 /* Maximum number of associated certificate constraints to accept on a key */
106 #define AGENT_MAX_EXT_CERTS 1024
107
108 /* XXX store hostkey_sid in a refcounted tree */
109
110 typedef enum {
111 AUTH_UNUSED = 0,
112 AUTH_SOCKET = 1,
113 AUTH_CONNECTION = 2,
114 } sock_type;
115
116 struct hostkey_sid {
117 struct sshkey *key;
118 struct sshbuf *sid;
119 int forwarded;
120 };
121
122 typedef struct socket_entry {
123 int fd;
124 sock_type type;
125 struct sshbuf *input;
126 struct sshbuf *output;
127 struct sshbuf *request;
128 size_t nsession_ids;
129 struct hostkey_sid *session_ids;
130 int session_bind_attempted;
131 } SocketEntry;
132
133 u_int sockets_alloc = 0;
134 SocketEntry *sockets = NULL;
135
136 typedef struct identity {
137 TAILQ_ENTRY(identity) next;
138 struct sshkey *key;
139 char *comment;
140 char *provider;
141 time_t death;
142 u_int confirm;
143 char *sk_provider;
144 struct dest_constraint *dest_constraints;
145 size_t ndest_constraints;
146 } Identity;
147
148 struct idtable {
149 int nentries;
150 TAILQ_HEAD(idqueue, identity) idlist;
151 };
152
153 /* private key table */
154 struct idtable *idtab;
155
156 int max_fd = 0;
157
158 /* pid of shell == parent of agent */
159 pid_t parent_pid = -1;
160 time_t parent_alive_interval = 0;
161
162 static sig_atomic_t signalled_exit;
163 static sig_atomic_t signalled_keydrop;
164
165 /* pid of process for which cleanup_socket is applicable */
166 pid_t cleanup_pid = 0;
167
168 /* pathname and directory for AUTH_SOCKET */
169 char socket_name[PATH_MAX];
170 char socket_dir[PATH_MAX];
171
172 /* Pattern-list of allowed PKCS#11/Security key paths */
173 static char *allowed_providers;
174
175 /*
176 * Allows PKCS11 providers or SK keys that use non-internal providers to
177 * be added over a remote connection (identified by session-bind@openssh.com).
178 */
179 static int remote_add_provider;
180
181 /* locking */
182 #define LOCK_SIZE 32
183 #define LOCK_SALT_SIZE 16
184 #define LOCK_ROUNDS 1
185 int locked = 0;
186 u_char lock_pwhash[LOCK_SIZE];
187 u_char lock_salt[LOCK_SALT_SIZE];
188
189 extern char *__progname;
190
191 /* Default lifetime in seconds (0 == forever) */
192 static int lifetime = 0;
193
194 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
195
196 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
197 static int restrict_websafe = 1;
198 static char *websafe_allowlist;
199
200 static void
close_socket(SocketEntry * e)201 close_socket(SocketEntry *e)
202 {
203 size_t i;
204
205 close(e->fd);
206 sshbuf_free(e->input);
207 sshbuf_free(e->output);
208 sshbuf_free(e->request);
209 for (i = 0; i < e->nsession_ids; i++) {
210 sshkey_free(e->session_ids[i].key);
211 sshbuf_free(e->session_ids[i].sid);
212 }
213 free(e->session_ids);
214 memset(e, '\0', sizeof(*e));
215 e->fd = -1;
216 e->type = AUTH_UNUSED;
217 }
218
219 static void
idtab_init(void)220 idtab_init(void)
221 {
222 idtab = xcalloc(1, sizeof(*idtab));
223 TAILQ_INIT(&idtab->idlist);
224 idtab->nentries = 0;
225 }
226
227 static void
free_dest_constraint_hop(struct dest_constraint_hop * dch)228 free_dest_constraint_hop(struct dest_constraint_hop *dch)
229 {
230 u_int i;
231
232 if (dch == NULL)
233 return;
234 free(dch->user);
235 free(dch->hostname);
236 for (i = 0; i < dch->nkeys; i++)
237 sshkey_free(dch->keys[i]);
238 free(dch->keys);
239 free(dch->key_is_ca);
240 }
241
242 static void
free_dest_constraints(struct dest_constraint * dcs,size_t ndcs)243 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
244 {
245 size_t i;
246
247 for (i = 0; i < ndcs; i++) {
248 free_dest_constraint_hop(&dcs[i].from);
249 free_dest_constraint_hop(&dcs[i].to);
250 }
251 free(dcs);
252 }
253
254 #ifdef ENABLE_PKCS11
255 static void
dup_dest_constraint_hop(const struct dest_constraint_hop * dch,struct dest_constraint_hop * out)256 dup_dest_constraint_hop(const struct dest_constraint_hop *dch,
257 struct dest_constraint_hop *out)
258 {
259 u_int i;
260 int r;
261
262 out->user = dch->user == NULL ? NULL : xstrdup(dch->user);
263 out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname);
264 out->is_ca = dch->is_ca;
265 out->nkeys = dch->nkeys;
266 out->keys = out->nkeys == 0 ? NULL :
267 xcalloc(out->nkeys, sizeof(*out->keys));
268 out->key_is_ca = out->nkeys == 0 ? NULL :
269 xcalloc(out->nkeys, sizeof(*out->key_is_ca));
270 for (i = 0; i < dch->nkeys; i++) {
271 if (dch->keys[i] != NULL &&
272 (r = sshkey_from_private(dch->keys[i],
273 &(out->keys[i]))) != 0)
274 fatal_fr(r, "copy key");
275 out->key_is_ca[i] = dch->key_is_ca[i];
276 }
277 }
278
279 static struct dest_constraint *
dup_dest_constraints(const struct dest_constraint * dcs,size_t ndcs)280 dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs)
281 {
282 size_t i;
283 struct dest_constraint *ret;
284
285 if (ndcs == 0)
286 return NULL;
287 ret = xcalloc(ndcs, sizeof(*ret));
288 for (i = 0; i < ndcs; i++) {
289 dup_dest_constraint_hop(&dcs[i].from, &ret[i].from);
290 dup_dest_constraint_hop(&dcs[i].to, &ret[i].to);
291 }
292 return ret;
293 }
294 #endif /* ENABLE_PKCS11 */
295
296 #ifdef DEBUG_CONSTRAINTS
297 static void
dump_dest_constraint_hop(const struct dest_constraint_hop * dch)298 dump_dest_constraint_hop(const struct dest_constraint_hop *dch)
299 {
300 u_int i;
301 char *fp;
302
303 debug_f("user %s hostname %s is_ca %d nkeys %u",
304 dch->user == NULL ? "(null)" : dch->user,
305 dch->hostname == NULL ? "(null)" : dch->hostname,
306 dch->is_ca, dch->nkeys);
307 for (i = 0; i < dch->nkeys; i++) {
308 fp = NULL;
309 if (dch->keys[i] != NULL &&
310 (fp = sshkey_fingerprint(dch->keys[i],
311 SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL)
312 fatal_f("fingerprint failed");
313 debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys,
314 dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]),
315 dch->keys[i] == NULL ? "" : " ",
316 dch->keys[i] == NULL ? "none" : fp,
317 dch->key_is_ca[i]);
318 free(fp);
319 }
320 }
321 #endif /* DEBUG_CONSTRAINTS */
322
323 static void
dump_dest_constraints(const char * context,const struct dest_constraint * dcs,size_t ndcs)324 dump_dest_constraints(const char *context,
325 const struct dest_constraint *dcs, size_t ndcs)
326 {
327 #ifdef DEBUG_CONSTRAINTS
328 size_t i;
329
330 debug_f("%s: %zu constraints", context, ndcs);
331 for (i = 0; i < ndcs; i++) {
332 debug_f("constraint %zu / %zu: from: ", i, ndcs);
333 dump_dest_constraint_hop(&dcs[i].from);
334 debug_f("constraint %zu / %zu: to: ", i, ndcs);
335 dump_dest_constraint_hop(&dcs[i].to);
336 }
337 debug_f("done for %s", context);
338 #endif /* DEBUG_CONSTRAINTS */
339 }
340
341 static void
free_identity(Identity * id)342 free_identity(Identity *id)
343 {
344 sshkey_free(id->key);
345 free(id->provider);
346 free(id->comment);
347 free(id->sk_provider);
348 free_dest_constraints(id->dest_constraints, id->ndest_constraints);
349 free(id);
350 }
351
352 /*
353 * Match 'key' against the key/CA list in a destination constraint hop
354 * Returns 0 on success or -1 otherwise.
355 */
356 static int
match_key_hop(const char * tag,const struct sshkey * key,const struct dest_constraint_hop * dch)357 match_key_hop(const char *tag, const struct sshkey *key,
358 const struct dest_constraint_hop *dch)
359 {
360 const char *reason = NULL;
361 const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
362 u_int i;
363 char *fp;
364
365 if (key == NULL)
366 return -1;
367 /* XXX logspam */
368 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
369 SSH_FP_DEFAULT)) == NULL)
370 fatal_f("fingerprint failed");
371 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
372 tag, hostname, sshkey_type(key), fp, dch->nkeys);
373 free(fp);
374 for (i = 0; i < dch->nkeys; i++) {
375 if (dch->keys[i] == NULL)
376 return -1;
377 /* XXX logspam */
378 if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
379 SSH_FP_DEFAULT)) == NULL)
380 fatal_f("fingerprint failed");
381 debug3_f("%s: key %u: %s%s %s", tag, i,
382 dch->key_is_ca[i] ? "CA " : "",
383 sshkey_type(dch->keys[i]), fp);
384 free(fp);
385 if (!sshkey_is_cert(key)) {
386 /* plain key */
387 if (dch->key_is_ca[i] ||
388 !sshkey_equal(key, dch->keys[i]))
389 continue;
390 return 0;
391 }
392 /* certificate */
393 if (!dch->key_is_ca[i])
394 continue;
395 if (key->cert == NULL || key->cert->signature_key == NULL)
396 return -1; /* shouldn't happen */
397 if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
398 continue;
399 if (sshkey_cert_check_host(key, hostname, 1,
400 SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
401 debug_f("cert %s / hostname %s rejected: %s",
402 key->cert->key_id, hostname, reason);
403 continue;
404 }
405 return 0;
406 }
407 return -1;
408 }
409
410 /* Check destination constraints on an identity against the hostkey/user */
411 static int
permitted_by_dest_constraints(const struct sshkey * fromkey,const struct sshkey * tokey,Identity * id,const char * user,const char ** hostnamep)412 permitted_by_dest_constraints(const struct sshkey *fromkey,
413 const struct sshkey *tokey, Identity *id, const char *user,
414 const char **hostnamep)
415 {
416 size_t i;
417 struct dest_constraint *d;
418
419 if (hostnamep != NULL)
420 *hostnamep = NULL;
421 for (i = 0; i < id->ndest_constraints; i++) {
422 d = id->dest_constraints + i;
423 /* XXX remove logspam */
424 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
425 i, d->from.user ? d->from.user : "",
426 d->from.user ? "@" : "",
427 d->from.hostname ? d->from.hostname : "(ORIGIN)",
428 d->from.nkeys,
429 d->to.user ? d->to.user : "", d->to.user ? "@" : "",
430 d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
431
432 /* Match 'from' key */
433 if (fromkey == NULL) {
434 /* We are matching the first hop */
435 if (d->from.hostname != NULL || d->from.nkeys != 0)
436 continue;
437 } else if (match_key_hop("from", fromkey, &d->from) != 0)
438 continue;
439
440 /* Match 'to' key */
441 if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
442 continue;
443
444 /* Match user if specified */
445 if (d->to.user != NULL && user != NULL &&
446 !match_pattern(user, d->to.user))
447 continue;
448
449 /* successfully matched this constraint */
450 if (hostnamep != NULL)
451 *hostnamep = d->to.hostname;
452 debug2_f("allowed for hostname %s",
453 d->to.hostname == NULL ? "*" : d->to.hostname);
454 return 0;
455 }
456 /* no match */
457 debug2_f("%s identity \"%s\" not permitted for this destination",
458 sshkey_type(id->key), id->comment);
459 return -1;
460 }
461
462 /*
463 * Check whether hostkeys on a SocketEntry and the optionally specified user
464 * are permitted by the destination constraints on the Identity.
465 * Returns 0 on success or -1 otherwise.
466 */
467 static int
identity_permitted(Identity * id,SocketEntry * e,char * user,const char ** forward_hostnamep,const char ** last_hostnamep)468 identity_permitted(Identity *id, SocketEntry *e, char *user,
469 const char **forward_hostnamep, const char **last_hostnamep)
470 {
471 size_t i;
472 const char **hp;
473 struct hostkey_sid *hks;
474 const struct sshkey *fromkey = NULL;
475 const char *test_user;
476 char *fp1, *fp2;
477
478 /* XXX remove logspam */
479 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
480 "%zu constraints", sshkey_type(id->key), id->comment,
481 e->nsession_ids, id->ndest_constraints);
482 if (id->ndest_constraints == 0)
483 return 0; /* unconstrained */
484 if (e->session_bind_attempted && e->nsession_ids == 0) {
485 error_f("previous session bind failed on socket");
486 return -1;
487 }
488 if (e->nsession_ids == 0)
489 return 0; /* local use */
490 /*
491 * Walk through the hops recorded by session_id and try to find a
492 * constraint that satisfies each.
493 */
494 for (i = 0; i < e->nsession_ids; i++) {
495 hks = e->session_ids + i;
496 if (hks->key == NULL)
497 fatal_f("internal error: no bound key");
498 /* XXX remove logspam */
499 fp1 = fp2 = NULL;
500 if (fromkey != NULL &&
501 (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
502 SSH_FP_DEFAULT)) == NULL)
503 fatal_f("fingerprint failed");
504 if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
505 SSH_FP_DEFAULT)) == NULL)
506 fatal_f("fingerprint failed");
507 debug3_f("socketentry fd=%d, entry %zu %s, "
508 "from hostkey %s %s to user %s hostkey %s %s",
509 e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
510 fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
511 fromkey ? fp1 : "", user ? user : "(ANY)",
512 sshkey_type(hks->key), fp2);
513 free(fp1);
514 free(fp2);
515 /*
516 * Record the hostnames for the initial forwarding and
517 * the final destination.
518 */
519 hp = NULL;
520 if (i == e->nsession_ids - 1)
521 hp = last_hostnamep;
522 else if (i == 0)
523 hp = forward_hostnamep;
524 /* Special handling for final recorded binding */
525 test_user = NULL;
526 if (i == e->nsession_ids - 1) {
527 /* Can only check user at final hop */
528 test_user = user;
529 /*
530 * user is only presented for signature requests.
531 * If this is the case, make sure last binding is not
532 * for a forwarding.
533 */
534 if (hks->forwarded && user != NULL) {
535 error_f("tried to sign on forwarding hop");
536 return -1;
537 }
538 } else if (!hks->forwarded) {
539 error_f("tried to forward though signing bind");
540 return -1;
541 }
542 if (permitted_by_dest_constraints(fromkey, hks->key, id,
543 test_user, hp) != 0)
544 return -1;
545 fromkey = hks->key;
546 }
547 /*
548 * Another special case: if the last bound session ID was for a
549 * forwarding, and this function is not being called to check a sign
550 * request (i.e. no 'user' supplied), then only permit the key if
551 * there is a permission that would allow it to be used at another
552 * destination. This hides keys that are allowed to be used to
553 * authenticate *to* a host but not permitted for *use* beyond it.
554 */
555 hks = &e->session_ids[e->nsession_ids - 1];
556 if (hks->forwarded && user == NULL &&
557 permitted_by_dest_constraints(hks->key, NULL, id,
558 NULL, NULL) != 0) {
559 debug3_f("key permitted at host but not after");
560 return -1;
561 }
562
563 /* success */
564 return 0;
565 }
566
567 static int
socket_is_remote(SocketEntry * e)568 socket_is_remote(SocketEntry *e)
569 {
570 return e->session_bind_attempted || (e->nsession_ids != 0);
571 }
572
573 /* return matching private key for given public key */
574 static Identity *
lookup_identity(struct sshkey * key)575 lookup_identity(struct sshkey *key)
576 {
577 Identity *id;
578
579 TAILQ_FOREACH(id, &idtab->idlist, next) {
580 if (sshkey_equal(key, id->key))
581 return (id);
582 }
583 return (NULL);
584 }
585
586 /* Check confirmation of keysign request */
587 static int
confirm_key(Identity * id,const char * extra)588 confirm_key(Identity *id, const char *extra)
589 {
590 char *p;
591 int ret = -1;
592
593 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
594 if (p != NULL &&
595 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
596 id->comment, p,
597 extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
598 ret = 0;
599 free(p);
600
601 return (ret);
602 }
603
604 static void
send_status(SocketEntry * e,int success)605 send_status(SocketEntry *e, int success)
606 {
607 int r;
608
609 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
610 (r = sshbuf_put_u8(e->output, success ?
611 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
612 fatal_fr(r, "compose");
613 }
614
615 /* send list of supported public keys to 'client' */
616 static void
process_request_identities(SocketEntry * e)617 process_request_identities(SocketEntry *e)
618 {
619 Identity *id;
620 struct sshbuf *msg, *keys;
621 int r;
622 u_int i = 0, nentries = 0;
623 char *fp;
624
625 debug2_f("entering");
626
627 if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
628 fatal_f("sshbuf_new failed");
629 TAILQ_FOREACH(id, &idtab->idlist, next) {
630 if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
631 SSH_FP_DEFAULT)) == NULL)
632 fatal_f("fingerprint failed");
633 debug_f("key %u / %u: %s %s", i++, idtab->nentries,
634 sshkey_ssh_name(id->key), fp);
635 dump_dest_constraints(__func__,
636 id->dest_constraints, id->ndest_constraints);
637 free(fp);
638 /* identity not visible, don't include in response */
639 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
640 continue;
641 if ((r = sshkey_puts_opts(id->key, keys,
642 SSHKEY_SERIALIZE_INFO)) != 0 ||
643 (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
644 error_fr(r, "compose key/comment");
645 continue;
646 }
647 nentries++;
648 }
649 debug2_f("replying with %u allowed of %u available keys",
650 nentries, idtab->nentries);
651 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
652 (r = sshbuf_put_u32(msg, nentries)) != 0 ||
653 (r = sshbuf_putb(msg, keys)) != 0)
654 fatal_fr(r, "compose");
655 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
656 fatal_fr(r, "enqueue");
657 sshbuf_free(msg);
658 sshbuf_free(keys);
659 }
660
661
662 static const char *
agent_decode_alg(struct sshkey * key,u_int flags)663 agent_decode_alg(struct sshkey *key, u_int flags)
664 {
665 if (key->type == KEY_RSA) {
666 if (flags & SSH_AGENT_RSA_SHA2_256)
667 return "rsa-sha2-256";
668 else if (flags & SSH_AGENT_RSA_SHA2_512)
669 return "rsa-sha2-512";
670 } else if (key->type == KEY_RSA_CERT) {
671 if (flags & SSH_AGENT_RSA_SHA2_256)
672 return "rsa-sha2-256-cert-v01@openssh.com";
673 else if (flags & SSH_AGENT_RSA_SHA2_512)
674 return "rsa-sha2-512-cert-v01@openssh.com";
675 }
676 return NULL;
677 }
678
679 /*
680 * Attempt to parse the contents of a buffer as a SSH publickey userauth
681 * request, checking its contents for consistency and matching the embedded
682 * key against the one that is being used for signing.
683 * Note: does not modify msg buffer.
684 * Optionally extract the username, session ID and/or hostkey from the request.
685 */
686 static int
parse_userauth_request(struct sshbuf * msg,const struct sshkey * expected_key,char ** userp,struct sshbuf ** sess_idp,struct sshkey ** hostkeyp)687 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
688 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
689 {
690 struct sshbuf *b = NULL, *sess_id = NULL;
691 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
692 int r;
693 u_char t, sig_follows;
694 struct sshkey *mkey = NULL, *hostkey = NULL;
695
696 if (userp != NULL)
697 *userp = NULL;
698 if (sess_idp != NULL)
699 *sess_idp = NULL;
700 if (hostkeyp != NULL)
701 *hostkeyp = NULL;
702 if ((b = sshbuf_fromb(msg)) == NULL)
703 fatal_f("sshbuf_fromb");
704
705 /* SSH userauth request */
706 if ((r = sshbuf_froms(b, &sess_id)) != 0)
707 goto out;
708 if (sshbuf_len(sess_id) == 0) {
709 r = SSH_ERR_INVALID_FORMAT;
710 goto out;
711 }
712 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
713 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
714 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
715 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
716 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
717 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
718 (r = sshkey_froms(b, &mkey)) != 0) /* key */
719 goto out;
720 if (t != SSH2_MSG_USERAUTH_REQUEST ||
721 sig_follows != 1 ||
722 strcmp(service, "ssh-connection") != 0 ||
723 !sshkey_equal(expected_key, mkey) ||
724 sshkey_type_from_name(pkalg) != expected_key->type) {
725 r = SSH_ERR_INVALID_FORMAT;
726 goto out;
727 }
728 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
729 if ((r = sshkey_froms(b, &hostkey)) != 0)
730 goto out;
731 } else if (strcmp(method, "publickey") != 0) {
732 r = SSH_ERR_INVALID_FORMAT;
733 goto out;
734 }
735 if (sshbuf_len(b) != 0) {
736 r = SSH_ERR_INVALID_FORMAT;
737 goto out;
738 }
739 /* success */
740 r = 0;
741 debug3_f("well formed userauth");
742 if (userp != NULL) {
743 *userp = user;
744 user = NULL;
745 }
746 if (sess_idp != NULL) {
747 *sess_idp = sess_id;
748 sess_id = NULL;
749 }
750 if (hostkeyp != NULL) {
751 *hostkeyp = hostkey;
752 hostkey = NULL;
753 }
754 out:
755 sshbuf_free(b);
756 sshbuf_free(sess_id);
757 free(user);
758 free(service);
759 free(method);
760 free(pkalg);
761 sshkey_free(mkey);
762 sshkey_free(hostkey);
763 return r;
764 }
765
766 /*
767 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
768 * Note: does not modify buffer.
769 */
770 static int
parse_sshsig_request(struct sshbuf * msg)771 parse_sshsig_request(struct sshbuf *msg)
772 {
773 int r;
774 struct sshbuf *b;
775
776 if ((b = sshbuf_fromb(msg)) == NULL)
777 fatal_f("sshbuf_fromb");
778
779 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
780 (r = sshbuf_consume(b, 6)) != 0 ||
781 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
782 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
783 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
784 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
785 goto out;
786 if (sshbuf_len(b) != 0) {
787 r = SSH_ERR_INVALID_FORMAT;
788 goto out;
789 }
790 /* success */
791 r = 0;
792 out:
793 sshbuf_free(b);
794 return r;
795 }
796
797 /*
798 * This function inspects a message to be signed by a FIDO key that has a
799 * web-like application string (i.e. one that does not begin with "ssh:".
800 * It checks that the message is one of those expected for SSH operations
801 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
802 * for the web.
803 */
804 static int
check_websafe_message_contents(struct sshkey * key,struct sshbuf * data)805 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
806 {
807 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
808 debug_f("signed data matches public key userauth request");
809 return 1;
810 }
811 if (parse_sshsig_request(data) == 0) {
812 debug_f("signed data matches SSHSIG signature request");
813 return 1;
814 }
815
816 /* XXX check CA signature operation */
817
818 error("web-origin key attempting to sign non-SSH message");
819 return 0;
820 }
821
822 static int
buf_equal(const struct sshbuf * a,const struct sshbuf * b)823 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
824 {
825 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
826 return SSH_ERR_INVALID_ARGUMENT;
827 if (sshbuf_len(a) != sshbuf_len(b))
828 return SSH_ERR_INVALID_FORMAT;
829 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
830 return SSH_ERR_INVALID_FORMAT;
831 return 0;
832 }
833
834 /* ssh2 only */
835 static void
process_sign_request2(SocketEntry * e)836 process_sign_request2(SocketEntry *e)
837 {
838 u_char *signature = NULL;
839 size_t slen = 0;
840 u_int compat = 0, flags;
841 int r, ok = -1, retried = 0;
842 char *fp = NULL, *pin = NULL, *prompt = NULL;
843 char *user = NULL, *sig_dest = NULL;
844 const char *fwd_host = NULL, *dest_host = NULL;
845 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
846 struct sshkey *key = NULL, *hostkey = NULL;
847 struct identity *id;
848 struct notifier_ctx *notifier = NULL;
849
850 debug_f("entering");
851
852 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
853 fatal_f("sshbuf_new failed");
854 if ((r = sshkey_froms(e->request, &key)) != 0 ||
855 (r = sshbuf_get_stringb(e->request, data)) != 0 ||
856 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
857 error_fr(r, "parse");
858 goto send;
859 }
860
861 if ((id = lookup_identity(key)) == NULL) {
862 verbose_f("%s key not found", sshkey_type(key));
863 goto send;
864 }
865 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
866 SSH_FP_DEFAULT)) == NULL)
867 fatal_f("fingerprint failed");
868
869 if (id->ndest_constraints != 0) {
870 if (e->nsession_ids == 0) {
871 logit_f("refusing use of destination-constrained key "
872 "to sign on unbound connection");
873 goto send;
874 }
875 if (parse_userauth_request(data, key, &user, &sid,
876 &hostkey) != 0) {
877 logit_f("refusing use of destination-constrained key "
878 "to sign an unidentified signature");
879 goto send;
880 }
881 /* XXX logspam */
882 debug_f("user=%s", user);
883 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
884 goto send;
885 /* XXX display fwd_host/dest_host in askpass UI */
886 /*
887 * Ensure that the session ID is the most recent one
888 * registered on the socket - it should have been bound by
889 * ssh immediately before userauth.
890 */
891 if (buf_equal(sid,
892 e->session_ids[e->nsession_ids - 1].sid) != 0) {
893 error_f("unexpected session ID (%zu listed) on "
894 "signature request for target user %s with "
895 "key %s %s", e->nsession_ids, user,
896 sshkey_type(id->key), fp);
897 goto send;
898 }
899 /*
900 * Ensure that the hostkey embedded in the signature matches
901 * the one most recently bound to the socket. An exception is
902 * made for the initial forwarding hop.
903 */
904 if (e->nsession_ids > 1 && hostkey == NULL) {
905 error_f("refusing use of destination-constrained key: "
906 "no hostkey recorded in signature for forwarded "
907 "connection");
908 goto send;
909 }
910 if (hostkey != NULL && !sshkey_equal(hostkey,
911 e->session_ids[e->nsession_ids - 1].key)) {
912 error_f("refusing use of destination-constrained key: "
913 "mismatch between hostkey in request and most "
914 "recently bound session");
915 goto send;
916 }
917 xasprintf(&sig_dest, "public key authentication request for "
918 "user \"%s\" to listed host", user);
919 }
920 if (id->confirm && confirm_key(id, sig_dest) != 0) {
921 verbose_f("user refused key");
922 goto send;
923 }
924 if (sshkey_is_sk(id->key)) {
925 if (restrict_websafe &&
926 match_pattern_list(id->key->sk_application,
927 websafe_allowlist, 0) != 1 &&
928 !check_websafe_message_contents(key, data)) {
929 /* error already logged */
930 goto send;
931 }
932 if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
933 notifier = notify_start(0,
934 "Confirm user presence for key %s %s%s%s",
935 sshkey_type(id->key), fp,
936 sig_dest == NULL ? "" : "\n",
937 sig_dest == NULL ? "" : sig_dest);
938 }
939 }
940 retry_pin:
941 if ((r = sshkey_sign(id->key, &signature, &slen,
942 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
943 id->sk_provider, pin, compat)) != 0) {
944 debug_fr(r, "sshkey_sign");
945 if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
946 r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
947 notify_complete(notifier, NULL);
948 notifier = NULL;
949 /* XXX include sig_dest */
950 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
951 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
952 " and confirm user presence " : " ",
953 sshkey_type(id->key), fp);
954 pin = read_passphrase(prompt, RP_USE_ASKPASS);
955 retried = 1;
956 goto retry_pin;
957 }
958 error_fr(r, "sshkey_sign");
959 goto send;
960 }
961 /* Success */
962 ok = 0;
963 debug_f("good signature");
964 send:
965 notify_complete(notifier, "User presence confirmed");
966
967 if (ok == 0) {
968 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
969 (r = sshbuf_put_string(msg, signature, slen)) != 0)
970 fatal_fr(r, "compose");
971 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
972 fatal_fr(r, "compose failure");
973
974 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
975 fatal_fr(r, "enqueue");
976
977 sshbuf_free(sid);
978 sshbuf_free(data);
979 sshbuf_free(msg);
980 sshkey_free(key);
981 sshkey_free(hostkey);
982 free(fp);
983 free(signature);
984 free(sig_dest);
985 free(user);
986 free(prompt);
987 if (pin != NULL)
988 freezero(pin, strlen(pin));
989 }
990
991 /* shared */
992 static void
process_remove_identity(SocketEntry * e)993 process_remove_identity(SocketEntry *e)
994 {
995 int r, success = 0;
996 struct sshkey *key = NULL;
997 Identity *id;
998
999 debug2_f("entering");
1000 if ((r = sshkey_froms(e->request, &key)) != 0) {
1001 error_fr(r, "parse key");
1002 goto done;
1003 }
1004 if ((id = lookup_identity(key)) == NULL) {
1005 debug_f("key not found");
1006 goto done;
1007 }
1008 /* identity not visible, cannot be removed */
1009 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1010 goto done; /* error already logged */
1011 /* We have this key, free it. */
1012 if (idtab->nentries < 1)
1013 fatal_f("internal error: nentries %d", idtab->nentries);
1014 TAILQ_REMOVE(&idtab->idlist, id, next);
1015 free_identity(id);
1016 idtab->nentries--;
1017 success = 1;
1018 done:
1019 sshkey_free(key);
1020 send_status(e, success);
1021 }
1022
1023 static void
remove_all_identities(void)1024 remove_all_identities(void)
1025 {
1026 Identity *id;
1027
1028 debug2_f("entering");
1029 /* Loop over all identities and clear the keys. */
1030 for (id = TAILQ_FIRST(&idtab->idlist); id;
1031 id = TAILQ_FIRST(&idtab->idlist)) {
1032 TAILQ_REMOVE(&idtab->idlist, id, next);
1033 free_identity(id);
1034 }
1035
1036 /* Mark that there are no identities. */
1037 idtab->nentries = 0;
1038 }
1039
1040 static void
process_remove_all_identities(SocketEntry * e)1041 process_remove_all_identities(SocketEntry *e)
1042 {
1043 remove_all_identities();
1044
1045 /* Send success. */
1046 send_status(e, 1);
1047 }
1048
1049 /* removes expired keys and returns number of seconds until the next expiry */
1050 static time_t
reaper(void)1051 reaper(void)
1052 {
1053 time_t deadline = 0, now = monotime();
1054 Identity *id, *nxt;
1055
1056 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1057 nxt = TAILQ_NEXT(id, next);
1058 if (id->death == 0)
1059 continue;
1060 if (now >= id->death) {
1061 debug("expiring key '%s'", id->comment);
1062 TAILQ_REMOVE(&idtab->idlist, id, next);
1063 free_identity(id);
1064 idtab->nentries--;
1065 } else
1066 deadline = (deadline == 0) ? id->death :
1067 MINIMUM(deadline, id->death);
1068 }
1069 if (deadline == 0 || deadline <= now)
1070 return 0;
1071 else
1072 return (deadline - now);
1073 }
1074
1075 static int
parse_dest_constraint_hop(struct sshbuf * b,struct dest_constraint_hop * dch)1076 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
1077 {
1078 u_char key_is_ca;
1079 size_t elen = 0;
1080 int r;
1081 struct sshkey *k = NULL;
1082 char *fp;
1083
1084 memset(dch, '\0', sizeof(*dch));
1085 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
1086 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
1087 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1088 error_fr(r, "parse");
1089 goto out;
1090 }
1091 if (elen != 0) {
1092 error_f("unsupported extensions (len %zu)", elen);
1093 r = SSH_ERR_FEATURE_UNSUPPORTED;
1094 goto out;
1095 }
1096 if (*dch->hostname == '\0') {
1097 free(dch->hostname);
1098 dch->hostname = NULL;
1099 }
1100 if (*dch->user == '\0') {
1101 free(dch->user);
1102 dch->user = NULL;
1103 }
1104 while (sshbuf_len(b) != 0) {
1105 dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1106 dch->nkeys + 1, sizeof(*dch->keys));
1107 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1108 dch->nkeys + 1, sizeof(*dch->key_is_ca));
1109 if ((r = sshkey_froms(b, &k)) != 0 ||
1110 (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1111 goto out;
1112 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1113 SSH_FP_DEFAULT)) == NULL)
1114 fatal_f("fingerprint failed");
1115 debug3_f("%s%s%s: adding %skey %s %s",
1116 dch->user == NULL ? "" : dch->user,
1117 dch->user == NULL ? "" : "@",
1118 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1119 free(fp);
1120 dch->keys[dch->nkeys] = k;
1121 dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1122 dch->nkeys++;
1123 k = NULL; /* transferred */
1124 }
1125 /* success */
1126 r = 0;
1127 out:
1128 sshkey_free(k);
1129 return r;
1130 }
1131
1132 static int
parse_dest_constraint(struct sshbuf * m,struct dest_constraint * dc)1133 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1134 {
1135 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1136 int r;
1137 size_t elen = 0;
1138
1139 debug3_f("entering");
1140
1141 memset(dc, '\0', sizeof(*dc));
1142 if ((r = sshbuf_froms(m, &b)) != 0 ||
1143 (r = sshbuf_froms(b, &frombuf)) != 0 ||
1144 (r = sshbuf_froms(b, &tobuf)) != 0 ||
1145 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1146 error_fr(r, "parse");
1147 goto out;
1148 }
1149 if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1150 (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1151 goto out; /* already logged */
1152 if (elen != 0) {
1153 error_f("unsupported extensions (len %zu)", elen);
1154 r = SSH_ERR_FEATURE_UNSUPPORTED;
1155 goto out;
1156 }
1157 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1158 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1159 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1160 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1161 /* check consistency */
1162 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1163 dc->from.user != NULL) {
1164 error_f("inconsistent \"from\" specification");
1165 r = SSH_ERR_INVALID_FORMAT;
1166 goto out;
1167 }
1168 if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1169 error_f("incomplete \"to\" specification");
1170 r = SSH_ERR_INVALID_FORMAT;
1171 goto out;
1172 }
1173 /* success */
1174 r = 0;
1175 out:
1176 sshbuf_free(b);
1177 sshbuf_free(frombuf);
1178 sshbuf_free(tobuf);
1179 return r;
1180 }
1181
1182 static int
parse_key_constraint_extension(struct sshbuf * m,char ** sk_providerp,struct dest_constraint ** dcsp,size_t * ndcsp,int * cert_onlyp,struct sshkey *** certs,size_t * ncerts)1183 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1184 struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
1185 struct sshkey ***certs, size_t *ncerts)
1186 {
1187 char *ext_name = NULL;
1188 int r;
1189 struct sshbuf *b = NULL;
1190 u_char v;
1191 struct sshkey *k;
1192
1193 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1194 error_fr(r, "parse constraint extension");
1195 goto out;
1196 }
1197 debug_f("constraint ext %s", ext_name);
1198 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1199 if (sk_providerp == NULL) {
1200 error_f("%s not valid here", ext_name);
1201 r = SSH_ERR_INVALID_FORMAT;
1202 goto out;
1203 }
1204 if (*sk_providerp != NULL) {
1205 error_f("%s already set", ext_name);
1206 r = SSH_ERR_INVALID_FORMAT;
1207 goto out;
1208 }
1209 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1210 error_fr(r, "parse %s", ext_name);
1211 goto out;
1212 }
1213 } else if (strcmp(ext_name,
1214 "restrict-destination-v00@openssh.com") == 0) {
1215 if (*dcsp != NULL) {
1216 error_f("%s already set", ext_name);
1217 r = SSH_ERR_INVALID_FORMAT;
1218 goto out;
1219 }
1220 if ((r = sshbuf_froms(m, &b)) != 0) {
1221 error_fr(r, "parse %s outer", ext_name);
1222 goto out;
1223 }
1224 while (sshbuf_len(b) != 0) {
1225 if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1226 error_f("too many %s constraints", ext_name);
1227 r = SSH_ERR_INVALID_FORMAT;
1228 goto out;
1229 }
1230 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1231 sizeof(**dcsp));
1232 if ((r = parse_dest_constraint(b,
1233 *dcsp + (*ndcsp)++)) != 0)
1234 goto out; /* error already logged */
1235 }
1236 } else if (strcmp(ext_name,
1237 "associated-certs-v00@openssh.com") == 0) {
1238 if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
1239 error_f("%s not valid here", ext_name);
1240 r = SSH_ERR_INVALID_FORMAT;
1241 goto out;
1242 }
1243 if (*certs != NULL) {
1244 error_f("%s already set", ext_name);
1245 r = SSH_ERR_INVALID_FORMAT;
1246 goto out;
1247 }
1248 if ((r = sshbuf_get_u8(m, &v)) != 0 ||
1249 (r = sshbuf_froms(m, &b)) != 0) {
1250 error_fr(r, "parse %s", ext_name);
1251 goto out;
1252 }
1253 *cert_onlyp = v != 0;
1254 while (sshbuf_len(b) != 0) {
1255 if (*ncerts >= AGENT_MAX_EXT_CERTS) {
1256 error_f("too many %s constraints", ext_name);
1257 r = SSH_ERR_INVALID_FORMAT;
1258 goto out;
1259 }
1260 *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
1261 sizeof(**certs));
1262 if ((r = sshkey_froms(b, &k)) != 0) {
1263 error_fr(r, "parse key");
1264 goto out;
1265 }
1266 (*certs)[(*ncerts)++] = k;
1267 }
1268 } else {
1269 error_f("unsupported constraint \"%s\"", ext_name);
1270 r = SSH_ERR_FEATURE_UNSUPPORTED;
1271 goto out;
1272 }
1273 /* success */
1274 r = 0;
1275 out:
1276 free(ext_name);
1277 sshbuf_free(b);
1278 return r;
1279 }
1280
1281 static int
parse_key_constraints(struct sshbuf * m,struct sshkey * k,time_t * deathp,u_int * secondsp,int * confirmp,char ** sk_providerp,struct dest_constraint ** dcsp,size_t * ndcsp,int * cert_onlyp,size_t * ncerts,struct sshkey *** certs)1282 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1283 u_int *secondsp, int *confirmp, char **sk_providerp,
1284 struct dest_constraint **dcsp, size_t *ndcsp,
1285 int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
1286 {
1287 u_char ctype;
1288 int r;
1289 u_int seconds, maxsign = 0;
1290
1291 while (sshbuf_len(m)) {
1292 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1293 error_fr(r, "parse constraint type");
1294 goto out;
1295 }
1296 switch (ctype) {
1297 case SSH_AGENT_CONSTRAIN_LIFETIME:
1298 if (*deathp != 0) {
1299 error_f("lifetime already set");
1300 r = SSH_ERR_INVALID_FORMAT;
1301 goto out;
1302 }
1303 if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1304 error_fr(r, "parse lifetime constraint");
1305 goto out;
1306 }
1307 *deathp = monotime() + seconds;
1308 *secondsp = seconds;
1309 break;
1310 case SSH_AGENT_CONSTRAIN_CONFIRM:
1311 if (*confirmp != 0) {
1312 error_f("confirm already set");
1313 r = SSH_ERR_INVALID_FORMAT;
1314 goto out;
1315 }
1316 *confirmp = 1;
1317 break;
1318 case SSH_AGENT_CONSTRAIN_MAXSIGN:
1319 if (k == NULL) {
1320 error_f("maxsign not valid here");
1321 r = SSH_ERR_INVALID_FORMAT;
1322 goto out;
1323 }
1324 if (maxsign != 0) {
1325 error_f("maxsign already set");
1326 r = SSH_ERR_INVALID_FORMAT;
1327 goto out;
1328 }
1329 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1330 error_fr(r, "parse maxsign constraint");
1331 goto out;
1332 }
1333 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1334 error_fr(r, "enable maxsign");
1335 goto out;
1336 }
1337 break;
1338 case SSH_AGENT_CONSTRAIN_EXTENSION:
1339 if ((r = parse_key_constraint_extension(m,
1340 sk_providerp, dcsp, ndcsp,
1341 cert_onlyp, certs, ncerts)) != 0)
1342 goto out; /* error already logged */
1343 break;
1344 default:
1345 error_f("Unknown constraint %d", ctype);
1346 r = SSH_ERR_FEATURE_UNSUPPORTED;
1347 goto out;
1348 }
1349 }
1350 /* success */
1351 r = 0;
1352 out:
1353 return r;
1354 }
1355
1356 static void
process_add_identity(SocketEntry * e)1357 process_add_identity(SocketEntry *e)
1358 {
1359 Identity *id;
1360 int success = 0, confirm = 0;
1361 char *fp, *comment = NULL, *sk_provider = NULL;
1362 char canonical_provider[PATH_MAX];
1363 time_t death = 0;
1364 u_int seconds = 0;
1365 struct dest_constraint *dest_constraints = NULL;
1366 size_t ndest_constraints = 0;
1367 struct sshkey *k = NULL;
1368 int r = SSH_ERR_INTERNAL_ERROR;
1369
1370 debug2_f("entering");
1371 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1372 k == NULL ||
1373 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1374 error_fr(r, "parse");
1375 goto out;
1376 }
1377 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1378 &sk_provider, &dest_constraints, &ndest_constraints,
1379 NULL, NULL, NULL) != 0) {
1380 error_f("failed to parse constraints");
1381 sshbuf_reset(e->request);
1382 goto out;
1383 }
1384 dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1385
1386 if (sk_provider != NULL) {
1387 if (!sshkey_is_sk(k)) {
1388 error("Cannot add provider: %s is not an "
1389 "authenticator-hosted key", sshkey_type(k));
1390 goto out;
1391 }
1392 if (strcasecmp(sk_provider, "internal") == 0) {
1393 debug_f("internal provider");
1394 } else {
1395 if (socket_is_remote(e) && !remote_add_provider) {
1396 verbose("failed add of SK provider \"%.100s\": "
1397 "remote addition of providers is disabled",
1398 sk_provider);
1399 goto out;
1400 }
1401 if (realpath(sk_provider, canonical_provider) == NULL) {
1402 verbose("failed provider \"%.100s\": "
1403 "realpath: %s", sk_provider,
1404 strerror(errno));
1405 goto out;
1406 }
1407 free(sk_provider);
1408 sk_provider = xstrdup(canonical_provider);
1409 if (match_pattern_list(sk_provider,
1410 allowed_providers, 0) != 1) {
1411 error("Refusing add key: "
1412 "provider %s not allowed", sk_provider);
1413 goto out;
1414 }
1415 }
1416 }
1417 if ((r = sshkey_shield_private(k)) != 0) {
1418 error_fr(r, "shield private");
1419 goto out;
1420 }
1421 if (lifetime && !death)
1422 death = monotime() + lifetime;
1423 if ((id = lookup_identity(k)) == NULL) {
1424 id = xcalloc(1, sizeof(Identity));
1425 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1426 /* Increment the number of identities. */
1427 idtab->nentries++;
1428 } else {
1429 /* identity not visible, do not update */
1430 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1431 goto out; /* error already logged */
1432 /* key state might have been updated */
1433 sshkey_free(id->key);
1434 free(id->comment);
1435 free(id->sk_provider);
1436 free_dest_constraints(id->dest_constraints,
1437 id->ndest_constraints);
1438 }
1439 /* success */
1440 id->key = k;
1441 id->comment = comment;
1442 id->death = death;
1443 id->confirm = confirm;
1444 id->sk_provider = sk_provider;
1445 id->dest_constraints = dest_constraints;
1446 id->ndest_constraints = ndest_constraints;
1447
1448 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1449 SSH_FP_DEFAULT)) == NULL)
1450 fatal_f("sshkey_fingerprint failed");
1451 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1452 "(provider: %s) (destination constraints: %zu)",
1453 sshkey_ssh_name(k), fp, comment, seconds, confirm,
1454 sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1455 free(fp);
1456 /* transferred */
1457 k = NULL;
1458 comment = NULL;
1459 sk_provider = NULL;
1460 dest_constraints = NULL;
1461 ndest_constraints = 0;
1462 success = 1;
1463 out:
1464 free(sk_provider);
1465 free(comment);
1466 sshkey_free(k);
1467 free_dest_constraints(dest_constraints, ndest_constraints);
1468 send_status(e, success);
1469 }
1470
1471 /* XXX todo: encrypt sensitive data with passphrase */
1472 static void
process_lock_agent(SocketEntry * e,int lock)1473 process_lock_agent(SocketEntry *e, int lock)
1474 {
1475 int r, success = 0, delay;
1476 char *passwd;
1477 u_char passwdhash[LOCK_SIZE];
1478 static u_int fail_count = 0;
1479 size_t pwlen;
1480
1481 debug2_f("entering");
1482 /*
1483 * This is deliberately fatal: the user has requested that we lock,
1484 * but we can't parse their request properly. The only safe thing to
1485 * do is abort.
1486 */
1487 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1488 fatal_fr(r, "parse");
1489 if (pwlen == 0) {
1490 debug("empty password not supported");
1491 } else if (locked && !lock) {
1492 if (bcrypt_pbkdf(passwd, pwlen, (uint8_t *)lock_salt, sizeof(lock_salt),
1493 (uint8_t *)passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1494 fatal("bcrypt_pbkdf");
1495 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1496 debug("agent unlocked");
1497 locked = 0;
1498 fail_count = 0;
1499 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1500 success = 1;
1501 } else {
1502 /* delay in 0.1s increments up to 10s */
1503 if (fail_count < 100)
1504 fail_count++;
1505 delay = 100000 * fail_count;
1506 debug("unlock failed, delaying %0.1lf seconds",
1507 (double)delay/1000000);
1508 usleep(delay);
1509 }
1510 explicit_bzero(passwdhash, sizeof(passwdhash));
1511 } else if (!locked && lock) {
1512 debug("agent locked");
1513 locked = 1;
1514 arc4random_buf(lock_salt, sizeof(lock_salt));
1515 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1516 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1517 fatal("bcrypt_pbkdf");
1518 success = 1;
1519 }
1520 freezero(passwd, pwlen);
1521 send_status(e, success);
1522 }
1523
1524 static void
no_identities(SocketEntry * e)1525 no_identities(SocketEntry *e)
1526 {
1527 struct sshbuf *msg;
1528 int r;
1529
1530 if ((msg = sshbuf_new()) == NULL)
1531 fatal_f("sshbuf_new failed");
1532 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1533 (r = sshbuf_put_u32(msg, 0)) != 0 ||
1534 (r = sshbuf_put_stringb(e->output, msg)) != 0)
1535 fatal_fr(r, "compose");
1536 sshbuf_free(msg);
1537 }
1538
1539 #ifdef ENABLE_PKCS11
1540 /* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1541 static void
add_p11_identity(struct sshkey * key,char * comment,const char * provider,time_t death,u_int confirm,struct dest_constraint * dest_constraints,size_t ndest_constraints)1542 add_p11_identity(struct sshkey *key, char *comment, const char *provider,
1543 time_t death, u_int confirm, struct dest_constraint *dest_constraints,
1544 size_t ndest_constraints)
1545 {
1546 Identity *id;
1547
1548 if (lookup_identity(key) != NULL) {
1549 sshkey_free(key);
1550 free(comment);
1551 return;
1552 }
1553 id = xcalloc(1, sizeof(Identity));
1554 id->key = key;
1555 id->comment = comment;
1556 id->provider = xstrdup(provider);
1557 id->death = death;
1558 id->confirm = confirm;
1559 id->dest_constraints = dup_dest_constraints(dest_constraints,
1560 ndest_constraints);
1561 id->ndest_constraints = ndest_constraints;
1562 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1563 idtab->nentries++;
1564 }
1565
1566 static void
process_add_smartcard_key(SocketEntry * e)1567 process_add_smartcard_key(SocketEntry *e)
1568 {
1569 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1570 char **comments = NULL;
1571 int r, i, count = 0, success = 0, confirm = 0;
1572 u_int seconds = 0;
1573 time_t death = 0;
1574 struct sshkey **keys = NULL, *k;
1575 struct dest_constraint *dest_constraints = NULL;
1576 size_t j, ndest_constraints = 0, ncerts = 0;
1577 struct sshkey **certs = NULL;
1578 int cert_only = 0;
1579
1580 debug2_f("entering");
1581 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1582 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1583 error_fr(r, "parse");
1584 goto send;
1585 }
1586 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1587 NULL, &dest_constraints, &ndest_constraints, &cert_only,
1588 &ncerts, &certs) != 0) {
1589 error_f("failed to parse constraints");
1590 goto send;
1591 }
1592 dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1593 if (socket_is_remote(e) && !remote_add_provider) {
1594 verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1595 "providers is disabled", provider);
1596 goto send;
1597 }
1598 if (realpath(provider, canonical_provider) == NULL) {
1599 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1600 provider, strerror(errno));
1601 goto send;
1602 }
1603 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1604 verbose("refusing PKCS#11 add of \"%.100s\": "
1605 "provider not allowed", canonical_provider);
1606 goto send;
1607 }
1608 debug_f("add %.100s", canonical_provider);
1609 if (lifetime && !death)
1610 death = monotime() + lifetime;
1611
1612 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1613 for (i = 0; i < count; i++) {
1614 if (comments[i] == NULL || comments[i][0] == '\0') {
1615 free(comments[i]);
1616 comments[i] = xstrdup(canonical_provider);
1617 }
1618 for (j = 0; j < ncerts; j++) {
1619 if (!sshkey_is_cert(certs[j]))
1620 continue;
1621 if (!sshkey_equal_public(keys[i], certs[j]))
1622 continue;
1623 if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
1624 continue;
1625 add_p11_identity(k, xstrdup(comments[i]),
1626 canonical_provider, death, confirm,
1627 dest_constraints, ndest_constraints);
1628 success = 1;
1629 }
1630 if (!cert_only && lookup_identity(keys[i]) == NULL) {
1631 add_p11_identity(keys[i], comments[i],
1632 canonical_provider, death, confirm,
1633 dest_constraints, ndest_constraints);
1634 keys[i] = NULL; /* transferred */
1635 comments[i] = NULL; /* transferred */
1636 success = 1;
1637 }
1638 /* XXX update constraints for existing keys */
1639 sshkey_free(keys[i]);
1640 free(comments[i]);
1641 }
1642 send:
1643 free(pin);
1644 free(provider);
1645 free(keys);
1646 free(comments);
1647 free_dest_constraints(dest_constraints, ndest_constraints);
1648 for (j = 0; j < ncerts; j++)
1649 sshkey_free(certs[j]);
1650 free(certs);
1651 send_status(e, success);
1652 }
1653
1654 static void
process_remove_smartcard_key(SocketEntry * e)1655 process_remove_smartcard_key(SocketEntry *e)
1656 {
1657 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1658 int r, success = 0;
1659 Identity *id, *nxt;
1660
1661 debug2_f("entering");
1662 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1663 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1664 error_fr(r, "parse");
1665 goto send;
1666 }
1667 free(pin);
1668
1669 if (realpath(provider, canonical_provider) == NULL) {
1670 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1671 provider, strerror(errno));
1672 goto send;
1673 }
1674
1675 debug_f("remove %.100s", canonical_provider);
1676 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1677 nxt = TAILQ_NEXT(id, next);
1678 /* Skip file--based keys */
1679 if (id->provider == NULL)
1680 continue;
1681 if (!strcmp(canonical_provider, id->provider)) {
1682 TAILQ_REMOVE(&idtab->idlist, id, next);
1683 free_identity(id);
1684 idtab->nentries--;
1685 }
1686 }
1687 if (pkcs11_del_provider(canonical_provider) == 0)
1688 success = 1;
1689 else
1690 error_f("pkcs11_del_provider failed");
1691 send:
1692 free(provider);
1693 send_status(e, success);
1694 }
1695 #endif /* ENABLE_PKCS11 */
1696
1697 static int
process_ext_session_bind(SocketEntry * e)1698 process_ext_session_bind(SocketEntry *e)
1699 {
1700 int r, sid_match, key_match;
1701 struct sshkey *key = NULL;
1702 struct sshbuf *sid = NULL, *sig = NULL;
1703 char *fp = NULL;
1704 size_t i;
1705 u_char fwd = 0;
1706
1707 debug2_f("entering");
1708 e->session_bind_attempted = 1;
1709 if ((r = sshkey_froms(e->request, &key)) != 0 ||
1710 (r = sshbuf_froms(e->request, &sid)) != 0 ||
1711 (r = sshbuf_froms(e->request, &sig)) != 0 ||
1712 (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1713 error_fr(r, "parse");
1714 goto out;
1715 }
1716 if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) {
1717 error_f("session ID too long");
1718 goto out;
1719 }
1720 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1721 SSH_FP_DEFAULT)) == NULL)
1722 fatal_f("fingerprint failed");
1723 /* check signature with hostkey on session ID */
1724 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1725 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1726 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1727 goto out;
1728 }
1729 /* check whether sid/key already recorded */
1730 for (i = 0; i < e->nsession_ids; i++) {
1731 if (!e->session_ids[i].forwarded) {
1732 error_f("attempt to bind session ID to socket "
1733 "previously bound for authentication attempt");
1734 r = -1;
1735 goto out;
1736 }
1737 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1738 key_match = sshkey_equal(key, e->session_ids[i].key);
1739 if (sid_match && key_match) {
1740 debug_f("session ID already recorded for %s %s",
1741 sshkey_type(key), fp);
1742 r = 0;
1743 goto out;
1744 } else if (sid_match) {
1745 error_f("session ID recorded against different key "
1746 "for %s %s", sshkey_type(key), fp);
1747 r = -1;
1748 goto out;
1749 }
1750 /*
1751 * new sid with previously-seen key can happen, e.g. multiple
1752 * connections to the same host.
1753 */
1754 }
1755 /* record new key/sid */
1756 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1757 error_f("too many session IDs recorded");
1758 r = -1;
1759 goto out;
1760 }
1761 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1762 e->nsession_ids + 1, sizeof(*e->session_ids));
1763 i = e->nsession_ids++;
1764 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1765 AGENT_MAX_SESSION_IDS);
1766 e->session_ids[i].key = key;
1767 e->session_ids[i].forwarded = fwd != 0;
1768 key = NULL; /* transferred */
1769 /* can't transfer sid; it's refcounted and scoped to request's life */
1770 if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1771 fatal_f("sshbuf_new");
1772 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1773 fatal_fr(r, "sshbuf_putb session ID");
1774 /* success */
1775 r = 0;
1776 out:
1777 free(fp);
1778 sshkey_free(key);
1779 sshbuf_free(sid);
1780 sshbuf_free(sig);
1781 return r == 0 ? 1 : 0;
1782 }
1783
1784 static void
process_extension(SocketEntry * e)1785 process_extension(SocketEntry *e)
1786 {
1787 int r, success = 0;
1788 char *name;
1789
1790 debug2_f("entering");
1791 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1792 error_fr(r, "parse");
1793 goto send;
1794 }
1795 if (strcmp(name, "session-bind@openssh.com") == 0)
1796 success = process_ext_session_bind(e);
1797 else
1798 debug_f("unsupported extension \"%s\"", name);
1799 free(name);
1800 send:
1801 send_status(e, success);
1802 }
1803 /*
1804 * dispatch incoming message.
1805 * returns 1 on success, 0 for incomplete messages or -1 on error.
1806 */
1807 static int
process_message(u_int socknum)1808 process_message(u_int socknum)
1809 {
1810 u_int msg_len;
1811 u_char type;
1812 const u_char *cp;
1813 int r;
1814 SocketEntry *e;
1815
1816 if (socknum >= sockets_alloc)
1817 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1818 e = &sockets[socknum];
1819
1820 if (sshbuf_len(e->input) < 5)
1821 return 0; /* Incomplete message header. */
1822 cp = sshbuf_ptr(e->input);
1823 msg_len = PEEK_U32(cp);
1824 if (msg_len > AGENT_MAX_LEN) {
1825 debug_f("socket %u (fd=%d) message too long %u > %u",
1826 socknum, e->fd, msg_len, AGENT_MAX_LEN);
1827 return -1;
1828 }
1829 if (sshbuf_len(e->input) < msg_len + 4)
1830 return 0; /* Incomplete message body. */
1831
1832 /* move the current input to e->request */
1833 sshbuf_reset(e->request);
1834 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1835 (r = sshbuf_get_u8(e->request, &type)) != 0) {
1836 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1837 r == SSH_ERR_STRING_TOO_LARGE) {
1838 error_fr(r, "parse");
1839 return -1;
1840 }
1841 fatal_fr(r, "parse");
1842 }
1843
1844 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1845
1846 /* check whether agent is locked */
1847 if (locked && type != SSH_AGENTC_UNLOCK) {
1848 sshbuf_reset(e->request);
1849 switch (type) {
1850 case SSH2_AGENTC_REQUEST_IDENTITIES:
1851 /* send empty lists */
1852 no_identities(e);
1853 break;
1854 default:
1855 /* send a fail message for all other request types */
1856 send_status(e, 0);
1857 }
1858 return 1;
1859 }
1860
1861 switch (type) {
1862 case SSH_AGENTC_LOCK:
1863 case SSH_AGENTC_UNLOCK:
1864 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1865 break;
1866 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1867 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1868 break;
1869 /* ssh2 */
1870 case SSH2_AGENTC_SIGN_REQUEST:
1871 process_sign_request2(e);
1872 break;
1873 case SSH2_AGENTC_REQUEST_IDENTITIES:
1874 process_request_identities(e);
1875 break;
1876 case SSH2_AGENTC_ADD_IDENTITY:
1877 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1878 process_add_identity(e);
1879 break;
1880 case SSH2_AGENTC_REMOVE_IDENTITY:
1881 process_remove_identity(e);
1882 break;
1883 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1884 process_remove_all_identities(e);
1885 break;
1886 #ifdef ENABLE_PKCS11
1887 case SSH_AGENTC_ADD_SMARTCARD_KEY:
1888 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1889 process_add_smartcard_key(e);
1890 break;
1891 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1892 process_remove_smartcard_key(e);
1893 break;
1894 #endif /* ENABLE_PKCS11 */
1895 case SSH_AGENTC_EXTENSION:
1896 process_extension(e);
1897 break;
1898 default:
1899 /* Unknown message. Respond with failure. */
1900 error("Unknown message %d", type);
1901 sshbuf_reset(e->request);
1902 send_status(e, 0);
1903 break;
1904 }
1905 return 1;
1906 }
1907
1908 static void
new_socket(sock_type type,int fd)1909 new_socket(sock_type type, int fd)
1910 {
1911 u_int i, old_alloc, new_alloc;
1912
1913 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1914 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1915 set_nonblock(fd);
1916
1917 if (fd > max_fd)
1918 max_fd = fd;
1919
1920 for (i = 0; i < sockets_alloc; i++)
1921 if (sockets[i].type == AUTH_UNUSED) {
1922 sockets[i].fd = fd;
1923 if ((sockets[i].input = sshbuf_new()) == NULL ||
1924 (sockets[i].output = sshbuf_new()) == NULL ||
1925 (sockets[i].request = sshbuf_new()) == NULL)
1926 fatal_f("sshbuf_new failed");
1927 sockets[i].type = type;
1928 return;
1929 }
1930 old_alloc = sockets_alloc;
1931 new_alloc = sockets_alloc + 10;
1932 sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1933 sizeof(sockets[0]));
1934 for (i = old_alloc; i < new_alloc; i++)
1935 sockets[i].type = AUTH_UNUSED;
1936 sockets_alloc = new_alloc;
1937 sockets[old_alloc].fd = fd;
1938 if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1939 (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1940 (sockets[old_alloc].request = sshbuf_new()) == NULL)
1941 fatal_f("sshbuf_new failed");
1942 sockets[old_alloc].type = type;
1943 }
1944
1945 static int
handle_socket_read(u_int socknum)1946 handle_socket_read(u_int socknum)
1947 {
1948 struct sockaddr_un sunaddr;
1949 socklen_t slen;
1950 uid_t euid;
1951 gid_t egid;
1952 int fd;
1953
1954 slen = sizeof(sunaddr);
1955 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1956 if (fd == -1) {
1957 error("accept from AUTH_SOCKET: %s", strerror(errno));
1958 return -1;
1959 }
1960 if (getpeereid(fd, &euid, &egid) == -1) {
1961 error("getpeereid %d failed: %s", fd, strerror(errno));
1962 close(fd);
1963 return -1;
1964 }
1965 if ((euid != 0) && (getuid() != euid)) {
1966 error("uid mismatch: peer euid %u != uid %u",
1967 (u_int) euid, (u_int) getuid());
1968 close(fd);
1969 return -1;
1970 }
1971 new_socket(AUTH_CONNECTION, fd);
1972 return 0;
1973 }
1974
1975 static int
handle_conn_read(u_int socknum)1976 handle_conn_read(u_int socknum)
1977 {
1978 char buf[AGENT_RBUF_LEN];
1979 ssize_t len;
1980 int r;
1981
1982 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1983 if (len == -1) {
1984 if (errno == EAGAIN || errno == EINTR)
1985 return 0;
1986 error_f("read error on socket %u (fd %d): %s",
1987 socknum, sockets[socknum].fd, strerror(errno));
1988 }
1989 return -1;
1990 }
1991 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1992 fatal_fr(r, "compose");
1993 explicit_bzero(buf, sizeof(buf));
1994 for (;;) {
1995 if ((r = process_message(socknum)) == -1)
1996 return -1;
1997 else if (r == 0)
1998 break;
1999 }
2000 return 0;
2001 }
2002
2003 static int
handle_conn_write(u_int socknum)2004 handle_conn_write(u_int socknum)
2005 {
2006 ssize_t len;
2007 int r;
2008
2009 if (sshbuf_len(sockets[socknum].output) == 0)
2010 return 0; /* shouldn't happen */
2011 if ((len = write(sockets[socknum].fd,
2012 sshbuf_ptr(sockets[socknum].output),
2013 sshbuf_len(sockets[socknum].output))) <= 0) {
2014 if (len == -1) {
2015 if (errno == EAGAIN || errno == EINTR)
2016 return 0;
2017 error_f("read error on socket %u (fd %d): %s",
2018 socknum, sockets[socknum].fd, strerror(errno));
2019 }
2020 return -1;
2021 }
2022 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
2023 fatal_fr(r, "consume");
2024 return 0;
2025 }
2026
2027 static void
after_poll(struct pollfd * pfd,size_t npfd,u_int maxfds)2028 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
2029 {
2030 size_t i;
2031 u_int socknum, activefds = npfd;
2032
2033 for (i = 0; i < npfd; i++) {
2034 if (pfd[i].revents == 0)
2035 continue;
2036 /* Find sockets entry */
2037 for (socknum = 0; socknum < sockets_alloc; socknum++) {
2038 if (sockets[socknum].type != AUTH_SOCKET &&
2039 sockets[socknum].type != AUTH_CONNECTION)
2040 continue;
2041 if (pfd[i].fd == sockets[socknum].fd)
2042 break;
2043 }
2044 if (socknum >= sockets_alloc) {
2045 error_f("no socket for fd %d", pfd[i].fd);
2046 continue;
2047 }
2048 /* Process events */
2049 switch (sockets[socknum].type) {
2050 case AUTH_SOCKET:
2051 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
2052 break;
2053 if (npfd > maxfds) {
2054 debug3("out of fds (active %u >= limit %u); "
2055 "skipping accept", activefds, maxfds);
2056 break;
2057 }
2058 if (handle_socket_read(socknum) == 0)
2059 activefds++;
2060 break;
2061 case AUTH_CONNECTION:
2062 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
2063 handle_conn_read(socknum) != 0)
2064 goto close_sock;
2065 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
2066 handle_conn_write(socknum) != 0) {
2067 close_sock:
2068 if (activefds == 0)
2069 fatal("activefds == 0 at close_sock");
2070 close_socket(&sockets[socknum]);
2071 activefds--;
2072 break;
2073 }
2074 break;
2075 default:
2076 break;
2077 }
2078 }
2079 }
2080
2081 static int
prepare_poll(struct pollfd ** pfdp,size_t * npfdp,struct timespec * timeoutp,u_int maxfds)2082 prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds)
2083 {
2084 struct pollfd *pfd = *pfdp;
2085 size_t i, j, npfd = 0;
2086 time_t deadline;
2087 int r;
2088
2089 /* Count active sockets */
2090 for (i = 0; i < sockets_alloc; i++) {
2091 switch (sockets[i].type) {
2092 case AUTH_SOCKET:
2093 case AUTH_CONNECTION:
2094 npfd++;
2095 break;
2096 case AUTH_UNUSED:
2097 break;
2098 default:
2099 fatal("Unknown socket type %d", sockets[i].type);
2100 break;
2101 }
2102 }
2103 if (npfd != *npfdp &&
2104 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
2105 fatal_f("recallocarray failed");
2106 *pfdp = pfd;
2107 *npfdp = npfd;
2108
2109 for (i = j = 0; i < sockets_alloc; i++) {
2110 switch (sockets[i].type) {
2111 case AUTH_SOCKET:
2112 if (npfd > maxfds) {
2113 debug3("out of fds (active %zu >= limit %u); "
2114 "skipping arming listener", npfd, maxfds);
2115 break;
2116 }
2117 pfd[j].fd = sockets[i].fd;
2118 pfd[j].revents = 0;
2119 pfd[j].events = POLLIN;
2120 j++;
2121 break;
2122 case AUTH_CONNECTION:
2123 pfd[j].fd = sockets[i].fd;
2124 pfd[j].revents = 0;
2125 /*
2126 * Only prepare to read if we can handle a full-size
2127 * input read buffer and enqueue a max size reply..
2128 */
2129 if ((r = sshbuf_check_reserve(sockets[i].input,
2130 AGENT_RBUF_LEN)) == 0 &&
2131 (r = sshbuf_check_reserve(sockets[i].output,
2132 AGENT_MAX_LEN)) == 0)
2133 pfd[j].events = POLLIN;
2134 else if (r != SSH_ERR_NO_BUFFER_SPACE)
2135 fatal_fr(r, "reserve");
2136 if (sshbuf_len(sockets[i].output) > 0)
2137 pfd[j].events |= POLLOUT;
2138 j++;
2139 break;
2140 default:
2141 break;
2142 }
2143 }
2144 deadline = reaper();
2145 if (parent_alive_interval != 0)
2146 deadline = (deadline == 0) ? parent_alive_interval :
2147 MINIMUM(deadline, parent_alive_interval);
2148 if (deadline != 0)
2149 ptimeout_deadline_sec(timeoutp, deadline);
2150 return (1);
2151 }
2152
2153 static void
cleanup_socket(void)2154 cleanup_socket(void)
2155 {
2156 if (cleanup_pid != 0 && getpid() != cleanup_pid)
2157 return;
2158 debug_f("cleanup");
2159 if (socket_name[0])
2160 unlink(socket_name);
2161 if (socket_dir[0])
2162 rmdir(socket_dir);
2163 }
2164
2165 void
cleanup_exit(int i)2166 cleanup_exit(int i)
2167 {
2168 cleanup_socket();
2169 #ifdef ENABLE_PKCS11
2170 pkcs11_terminate();
2171 #endif
2172 _exit(i);
2173 }
2174
2175 static void
cleanup_handler(int sig)2176 cleanup_handler(int sig)
2177 {
2178 signalled_exit = sig;
2179 }
2180
2181 static void
keydrop_handler(int sig)2182 keydrop_handler(int sig)
2183 {
2184 signalled_keydrop = sig;
2185 }
2186
2187 static void
check_parent_exists(void)2188 check_parent_exists(void)
2189 {
2190 /*
2191 * If our parent has exited then getppid() will return (pid_t)1,
2192 * so testing for that should be safe.
2193 */
2194 if (parent_pid != -1 && getppid() != parent_pid) {
2195 /* printf("Parent has died - Authentication agent exiting.\n"); */
2196 cleanup_socket();
2197 _exit(2);
2198 }
2199 }
2200
2201 __dead static void
usage(void)2202 usage(void)
2203 {
2204 fprintf(stderr,
2205 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
2206 " [-O option] [-P allowed_providers] [-t life]\n"
2207 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2208 " [-P allowed_providers] [-t life] command [arg ...]\n"
2209 " ssh-agent [-c | -s] -k\n");
2210 exit(1);
2211 }
2212
2213 static void
csh_setenv(const char * name,const char * value)2214 csh_setenv(const char *name, const char *value)
2215 {
2216 printf("setenv %s %s;\n", name, value);
2217 }
2218
2219 static void
csh_unsetenv(const char * name)2220 csh_unsetenv(const char *name)
2221 {
2222 printf("unsetenv %s;\n", name);
2223 }
2224
2225 static void
sh_setenv(const char * name,const char * value)2226 sh_setenv(const char *name, const char *value)
2227 {
2228 printf("%s=%s; export %s;\n", name, value, name);
2229 }
2230
2231 static void
sh_unsetenv(const char * name)2232 sh_unsetenv(const char *name)
2233 {
2234 printf("unset %s;\n", name);
2235 }
2236 int
main(int ac,char ** av)2237 main(int ac, char **av)
2238 {
2239 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2240 int sock, ch, result, saved_errno;
2241 char *shell, *pidstr, *agentsocket = NULL;
2242 const char *ccp;
2243 struct rlimit rlim;
2244 void (*f_setenv)(const char *, const char *);
2245 void (*f_unsetenv)(const char *);
2246 extern int optind;
2247 extern char *optarg;
2248 pid_t pid;
2249 char pidstrbuf[1 + 3 * sizeof pid];
2250 size_t len;
2251 mode_t prev_mask;
2252 struct timespec timeout;
2253 struct pollfd *pfd = NULL;
2254 size_t npfd = 0;
2255 u_int maxfds;
2256 sigset_t nsigset, osigset;
2257
2258 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2259 sanitise_stdfd();
2260
2261 /* drop */
2262 (void)setegid(getgid());
2263 (void)setgid(getgid());
2264
2265 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2266 fatal("%s: getrlimit: %s", __progname, strerror(errno));
2267
2268 #ifdef WITH_OPENSSL
2269 OpenSSL_add_all_algorithms();
2270 #endif
2271
2272 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
2273 switch (ch) {
2274 case 'E':
2275 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2276 if (fingerprint_hash == -1)
2277 fatal("Invalid hash algorithm \"%s\"", optarg);
2278 break;
2279 case 'c':
2280 if (s_flag)
2281 usage();
2282 c_flag++;
2283 break;
2284 case 'k':
2285 k_flag++;
2286 break;
2287 case 'O':
2288 if (strcmp(optarg, "no-restrict-websafe") == 0)
2289 restrict_websafe = 0;
2290 else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2291 remote_add_provider = 1;
2292 else if ((ccp = strprefix(optarg,
2293 "websafe-allow=", 0)) != NULL) {
2294 if (websafe_allowlist != NULL)
2295 fatal("websafe-allow already set");
2296 websafe_allowlist = xstrdup(ccp);
2297 } else
2298 fatal("Unknown -O option");
2299 break;
2300 case 'P':
2301 if (allowed_providers != NULL)
2302 fatal("-P option already specified");
2303 allowed_providers = xstrdup(optarg);
2304 break;
2305 case 's':
2306 if (c_flag)
2307 usage();
2308 s_flag++;
2309 break;
2310 case 'd':
2311 if (d_flag || D_flag)
2312 usage();
2313 d_flag++;
2314 break;
2315 case 'D':
2316 if (d_flag || D_flag)
2317 usage();
2318 D_flag++;
2319 break;
2320 case 'a':
2321 agentsocket = optarg;
2322 break;
2323 case 't':
2324 if ((lifetime = convtime(optarg)) == -1) {
2325 fprintf(stderr, "Invalid lifetime\n");
2326 usage();
2327 }
2328 break;
2329 default:
2330 usage();
2331 }
2332 }
2333 ac -= optind;
2334 av += optind;
2335
2336 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2337 usage();
2338
2339 if (allowed_providers == NULL)
2340 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2341 if (websafe_allowlist == NULL)
2342 websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST);
2343
2344 if (ac == 0 && !c_flag && !s_flag) {
2345 shell = getenv("SHELL");
2346 if (shell != NULL && (len = strlen(shell)) > 2 &&
2347 strncmp(shell + len - 3, "csh", 3) == 0)
2348 c_flag = 1;
2349 }
2350 if (c_flag) {
2351 f_setenv = csh_setenv;
2352 f_unsetenv = csh_unsetenv;
2353 } else {
2354 f_setenv = sh_setenv;
2355 f_unsetenv = sh_unsetenv;
2356 }
2357 if (k_flag) {
2358 const char *errstr = NULL;
2359
2360 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2361 if (pidstr == NULL) {
2362 fprintf(stderr, "%s not set, cannot kill agent\n",
2363 SSH_AGENTPID_ENV_NAME);
2364 exit(1);
2365 }
2366 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2367 if (errstr) {
2368 fprintf(stderr,
2369 "%s=\"%s\", which is not a good PID: %s\n",
2370 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2371 exit(1);
2372 }
2373 if (kill(pid, SIGTERM) == -1) {
2374 perror("kill");
2375 exit(1);
2376 }
2377 (*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME);
2378 (*f_unsetenv)(SSH_AGENTPID_ENV_NAME);
2379 printf("echo Agent pid %ld killed;\n", (long)pid);
2380 exit(0);
2381 }
2382
2383 /*
2384 * Minimum file descriptors:
2385 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2386 * a few spare for libc / stack protectors / sanitisers, etc.
2387 */
2388 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2389 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2390 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2391 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2392 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2393
2394 parent_pid = getpid();
2395
2396 if (agentsocket == NULL) {
2397 /* Create private directory for agent socket */
2398 mktemp_proto(socket_dir, sizeof(socket_dir));
2399 if (mkdtemp(socket_dir) == NULL) {
2400 perror("mkdtemp: private socket dir");
2401 exit(1);
2402 }
2403 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2404 (long)parent_pid);
2405 } else {
2406 /* Try to use specified agent socket */
2407 socket_dir[0] = '\0';
2408 strlcpy(socket_name, agentsocket, sizeof socket_name);
2409 }
2410
2411 /*
2412 * Create socket early so it will exist before command gets run from
2413 * the parent.
2414 */
2415 prev_mask = umask(0177);
2416 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2417 if (sock < 0) {
2418 /* XXX - unix_listener() calls error() not perror() */
2419 *socket_name = '\0'; /* Don't unlink any existing file */
2420 cleanup_exit(1);
2421 }
2422 umask(prev_mask);
2423
2424 /*
2425 * Fork, and have the parent execute the command, if any, or present
2426 * the socket data. The child continues as the authentication agent.
2427 */
2428 if (D_flag || d_flag) {
2429 log_init(__progname,
2430 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2431 SYSLOG_FACILITY_AUTH, 1);
2432 if (c_flag)
2433 printf("setenv %s %s;\n",
2434 SSH_AUTHSOCKET_ENV_NAME, socket_name);
2435 else
2436 printf("%s=%s; export %s;\n",
2437 SSH_AUTHSOCKET_ENV_NAME, socket_name,
2438 SSH_AUTHSOCKET_ENV_NAME);
2439 printf("echo Agent pid %ld;\n", (long)parent_pid);
2440 fflush(stdout);
2441 goto skip;
2442 }
2443 pid = fork();
2444 if (pid == -1) {
2445 perror("fork");
2446 cleanup_exit(1);
2447 }
2448 if (pid != 0) { /* Parent - execute the given command. */
2449 close(sock);
2450 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2451 if (ac == 0) {
2452 (*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
2453 (*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf);
2454 printf("echo Agent pid %ld;\n", (long)pid);
2455 exit(0);
2456 }
2457 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2458 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2459 perror("setenv");
2460 exit(1);
2461 }
2462 execvp(av[0], av);
2463 perror(av[0]);
2464 exit(1);
2465 }
2466 /* child */
2467 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2468
2469 if (setsid() == -1) {
2470 error("setsid: %s", strerror(errno));
2471 cleanup_exit(1);
2472 }
2473
2474 (void)chdir("/");
2475 if (stdfd_devnull(1, 1, 1) == -1)
2476 error_f("stdfd_devnull failed");
2477
2478 /* deny core dumps, since memory contains unencrypted private keys */
2479 rlim.rlim_cur = rlim.rlim_max = 0;
2480 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2481 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2482 cleanup_exit(1);
2483 }
2484
2485 skip:
2486
2487 cleanup_pid = getpid();
2488
2489 #ifdef ENABLE_PKCS11
2490 pkcs11_init(0);
2491 #endif
2492 new_socket(AUTH_SOCKET, sock);
2493 if (ac > 0)
2494 parent_alive_interval = 10;
2495 idtab_init();
2496 ssh_signal(SIGPIPE, SIG_IGN);
2497 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2498 ssh_signal(SIGHUP, cleanup_handler);
2499 ssh_signal(SIGTERM, cleanup_handler);
2500 ssh_signal(SIGUSR1, keydrop_handler);
2501
2502 sigemptyset(&nsigset);
2503 sigaddset(&nsigset, SIGINT);
2504 sigaddset(&nsigset, SIGHUP);
2505 sigaddset(&nsigset, SIGTERM);
2506 sigaddset(&nsigset, SIGUSR1);
2507
2508 #ifdef __OpenBSD__
2509 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2510 fatal("%s: pledge: %s", __progname, strerror(errno));
2511 #endif
2512
2513 while (1) {
2514 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
2515 if (signalled_exit != 0) {
2516 logit("exiting on signal %d", (int)signalled_exit);
2517 cleanup_exit(2);
2518 }
2519 if (signalled_keydrop) {
2520 logit("signal %d received; removing all keys",
2521 (int)signalled_keydrop);
2522 remove_all_identities();
2523 signalled_keydrop = 0;
2524 }
2525 ptimeout_init(&timeout);
2526 prepare_poll(&pfd, &npfd, &timeout, maxfds);
2527 result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset);
2528 sigprocmask(SIG_SETMASK, &osigset, NULL);
2529 saved_errno = errno;
2530 if (parent_alive_interval != 0)
2531 check_parent_exists();
2532 (void) reaper(); /* remove expired keys */
2533 if (result == -1) {
2534 if (saved_errno == EINTR)
2535 continue;
2536 fatal("poll: %s", strerror(saved_errno));
2537 } else if (result > 0)
2538 after_poll(pfd, npfd, maxfds);
2539 }
2540 /* NOTREACHED */
2541 }
2542