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