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