]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/ssh-agent.c
tcp: Rack compressed ack path updates the recv window too easily
[FreeBSD/FreeBSD.git] / crypto / openssh / ssh-agent.c
1 /* $OpenBSD: ssh-agent.c,v 1.278 2021/04/03 06:18:41 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 __RCSID("$FreeBSD$");
39
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #include <sys/wait.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49 #ifdef HAVE_SYS_UN_H
50 # include <sys/un.h>
51 #endif
52 #include "openbsd-compat/sys-queue.h"
53
54 #ifdef WITH_OPENSSL
55 #include <openssl/evp.h>
56 #include "openbsd-compat/openssl-compat.h"
57 #endif
58
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <limits.h>
62 #ifdef HAVE_PATHS_H
63 # include <paths.h>
64 #endif
65 #ifdef HAVE_POLL_H
66 # include <poll.h>
67 #endif
68 #include <signal.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <time.h>
73 #include <string.h>
74 #include <unistd.h>
75 #ifdef HAVE_UTIL_H
76 # include <util.h>
77 #endif
78
79 #include "xmalloc.h"
80 #include "ssh.h"
81 #include "ssh2.h"
82 #include "sshbuf.h"
83 #include "sshkey.h"
84 #include "authfd.h"
85 #include "compat.h"
86 #include "log.h"
87 #include "misc.h"
88 #include "digest.h"
89 #include "ssherr.h"
90 #include "match.h"
91 #include "msg.h"
92 #include "ssherr.h"
93 #include "pathnames.h"
94 #include "ssh-pkcs11.h"
95 #include "sk-api.h"
96
97 #ifndef DEFAULT_ALLOWED_PROVIDERS
98 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
99 #endif
100
101 /* Maximum accepted message length */
102 #define AGENT_MAX_LEN   (256*1024)
103 /* Maximum bytes to read from client socket */
104 #define AGENT_RBUF_LEN  (4096)
105
106 typedef enum {
107         AUTH_UNUSED = 0,
108         AUTH_SOCKET = 1,
109         AUTH_CONNECTION = 2,
110 } sock_type;
111
112 typedef struct socket_entry {
113         int fd;
114         sock_type type;
115         struct sshbuf *input;
116         struct sshbuf *output;
117         struct sshbuf *request;
118 } SocketEntry;
119
120 u_int sockets_alloc = 0;
121 SocketEntry *sockets = NULL;
122
123 typedef struct identity {
124         TAILQ_ENTRY(identity) next;
125         struct sshkey *key;
126         char *comment;
127         char *provider;
128         time_t death;
129         u_int confirm;
130         char *sk_provider;
131 } Identity;
132
133 struct idtable {
134         int nentries;
135         TAILQ_HEAD(idqueue, identity) idlist;
136 };
137
138 /* private key table */
139 struct idtable *idtab;
140
141 int max_fd = 0;
142
143 /* pid of shell == parent of agent */
144 pid_t parent_pid = -1;
145 time_t parent_alive_interval = 0;
146
147 /* pid of process for which cleanup_socket is applicable */
148 pid_t cleanup_pid = 0;
149
150 /* pathname and directory for AUTH_SOCKET */
151 char socket_name[PATH_MAX];
152 char socket_dir[PATH_MAX];
153
154 /* Pattern-list of allowed PKCS#11/Security key paths */
155 static char *allowed_providers;
156
157 /* locking */
158 #define LOCK_SIZE       32
159 #define LOCK_SALT_SIZE  16
160 #define LOCK_ROUNDS     1
161 int locked = 0;
162 u_char lock_pwhash[LOCK_SIZE];
163 u_char lock_salt[LOCK_SALT_SIZE];
164
165 extern char *__progname;
166
167 /* Default lifetime in seconds (0 == forever) */
168 static int lifetime = 0;
169
170 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
171
172 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
173 static int restrict_websafe = 1;
174
175 /*
176  * Client connection count; incremented in new_socket() and decremented in
177  * close_socket().  When it reaches 0, ssh-agent will exit.  Since it is
178  * normally initialized to 1, it will never reach 0.  However, if the -x
179  * option is specified, it is initialized to 0 in main(); in that case,
180  * ssh-agent will exit as soon as it has had at least one client but no
181  * longer has any.
182  */
183 static int xcount = 1;
184
185 static void
186 close_socket(SocketEntry *e)
187 {
188         int last = 0;
189
190         if (e->type == AUTH_CONNECTION) {
191                 debug("xcount %d -> %d", xcount, xcount - 1);
192                 if (--xcount == 0)
193                         last = 1;
194         }
195         close(e->fd);
196         sshbuf_free(e->input);
197         sshbuf_free(e->output);
198         sshbuf_free(e->request);
199         memset(e, '\0', sizeof(*e));
200         e->fd = -1;
201         e->type = AUTH_UNUSED;
202         if (last)
203                 cleanup_exit(0);
204 }
205
206 static void
207 idtab_init(void)
208 {
209         idtab = xcalloc(1, sizeof(*idtab));
210         TAILQ_INIT(&idtab->idlist);
211         idtab->nentries = 0;
212 }
213
214 static void
215 free_identity(Identity *id)
216 {
217         sshkey_free(id->key);
218         free(id->provider);
219         free(id->comment);
220         free(id->sk_provider);
221         free(id);
222 }
223
224 /* return matching private key for given public key */
225 static Identity *
226 lookup_identity(struct sshkey *key)
227 {
228         Identity *id;
229
230         TAILQ_FOREACH(id, &idtab->idlist, next) {
231                 if (sshkey_equal(key, id->key))
232                         return (id);
233         }
234         return (NULL);
235 }
236
237 /* Check confirmation of keysign request */
238 static int
239 confirm_key(Identity *id, const char *extra)
240 {
241         char *p;
242         int ret = -1;
243
244         p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
245         if (p != NULL &&
246             ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
247             id->comment, p,
248             extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
249                 ret = 0;
250         free(p);
251
252         return (ret);
253 }
254
255 static void
256 send_status(SocketEntry *e, int success)
257 {
258         int r;
259
260         if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
261             (r = sshbuf_put_u8(e->output, success ?
262             SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
263                 fatal_fr(r, "compose");
264 }
265
266 /* send list of supported public keys to 'client' */
267 static void
268 process_request_identities(SocketEntry *e)
269 {
270         Identity *id;
271         struct sshbuf *msg;
272         int r;
273
274         debug2_f("entering");
275
276         if ((msg = sshbuf_new()) == NULL)
277                 fatal_f("sshbuf_new failed");
278         if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
279             (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
280                 fatal_fr(r, "compose");
281         TAILQ_FOREACH(id, &idtab->idlist, next) {
282                 if ((r = sshkey_puts_opts(id->key, msg,
283                     SSHKEY_SERIALIZE_INFO)) != 0 ||
284                     (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
285                         error_fr(r, "compose key/comment");
286                         continue;
287                 }
288         }
289         if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
290                 fatal_fr(r, "enqueue");
291         sshbuf_free(msg);
292 }
293
294
295 static char *
296 agent_decode_alg(struct sshkey *key, u_int flags)
297 {
298         if (key->type == KEY_RSA) {
299                 if (flags & SSH_AGENT_RSA_SHA2_256)
300                         return "rsa-sha2-256";
301                 else if (flags & SSH_AGENT_RSA_SHA2_512)
302                         return "rsa-sha2-512";
303         } else if (key->type == KEY_RSA_CERT) {
304                 if (flags & SSH_AGENT_RSA_SHA2_256)
305                         return "rsa-sha2-256-cert-v01@openssh.com";
306                 else if (flags & SSH_AGENT_RSA_SHA2_512)
307                         return "rsa-sha2-512-cert-v01@openssh.com";
308         }
309         return NULL;
310 }
311
312 /*
313  * Attempt to parse the contents of a buffer as a SSH publickey userauth
314  * request, checking its contents for consistency and matching the embedded
315  * key against the one that is being used for signing.
316  * Note: does not modify msg buffer.
317  * Optionally extract the username and session ID from the request.
318  */
319 static int
320 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
321     char **userp, struct sshbuf **sess_idp)
322 {
323         struct sshbuf *b = NULL, *sess_id = NULL;
324         char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
325         int r;
326         u_char t, sig_follows;
327         struct sshkey *mkey = NULL;
328
329         if (userp != NULL)
330                 *userp = NULL;
331         if (sess_idp != NULL)
332                 *sess_idp = NULL;
333         if ((b = sshbuf_fromb(msg)) == NULL)
334                 fatal_f("sshbuf_fromb");
335
336         /* SSH userauth request */
337         if ((r = sshbuf_froms(b, &sess_id)) != 0)
338                 goto out;
339         if (sshbuf_len(sess_id) == 0) {
340                 r = SSH_ERR_INVALID_FORMAT;
341                 goto out;
342         }
343         if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
344             (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
345             (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
346             (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
347             (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
348             (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
349             (r = sshkey_froms(b, &mkey)) != 0) /* key */
350                 goto out;
351         if (t != SSH2_MSG_USERAUTH_REQUEST ||
352             sig_follows != 1 ||
353             strcmp(service, "ssh-connection") != 0 ||
354             !sshkey_equal(expected_key, mkey) ||
355             sshkey_type_from_name(pkalg) != expected_key->type) {
356                 r = SSH_ERR_INVALID_FORMAT;
357                 goto out;
358         }
359         if (strcmp(method, "publickey") != 0) {
360                 r = SSH_ERR_INVALID_FORMAT;
361                 goto out;
362         }
363         if (sshbuf_len(b) != 0) {
364                 r = SSH_ERR_INVALID_FORMAT;
365                 goto out;
366         }
367         /* success */
368         r = 0;
369         debug3_f("well formed userauth");
370         if (userp != NULL) {
371                 *userp = user;
372                 user = NULL;
373         }
374         if (sess_idp != NULL) {
375                 *sess_idp = sess_id;
376                 sess_id = NULL;
377         }
378  out:
379         sshbuf_free(b);
380         sshbuf_free(sess_id);
381         free(user);
382         free(service);
383         free(method);
384         free(pkalg);
385         sshkey_free(mkey);
386         return r;
387 }
388
389 /*
390  * Attempt to parse the contents of a buffer as a SSHSIG signature request.
391  * Note: does not modify buffer.
392  */
393 static int
394 parse_sshsig_request(struct sshbuf *msg)
395 {
396         int r;
397         struct sshbuf *b;
398
399         if ((b = sshbuf_fromb(msg)) == NULL)
400                 fatal_f("sshbuf_fromb");
401
402         if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
403             (r = sshbuf_consume(b, 6)) != 0 ||
404             (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
405             (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
406             (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
407             (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
408                 goto out;
409         if (sshbuf_len(b) != 0) {
410                 r = SSH_ERR_INVALID_FORMAT;
411                 goto out;
412         }
413         /* success */
414         r = 0;
415  out:
416         sshbuf_free(b);
417         return r;
418 }
419
420 /*
421  * This function inspects a message to be signed by a FIDO key that has a
422  * web-like application string (i.e. one that does not begin with "ssh:".
423  * It checks that the message is one of those expected for SSH operations
424  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
425  * for the web.
426  */
427 static int
428 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
429 {
430         if (parse_userauth_request(data, key, NULL, NULL) == 0) {
431                 debug_f("signed data matches public key userauth request");
432                 return 1;
433         }
434         if (parse_sshsig_request(data) == 0) {
435                 debug_f("signed data matches SSHSIG signature request");
436                 return 1;
437         }
438
439         /* XXX check CA signature operation */
440
441         error("web-origin key attempting to sign non-SSH message");
442         return 0;
443 }
444
445 /* ssh2 only */
446 static void
447 process_sign_request2(SocketEntry *e)
448 {
449         u_char *signature = NULL;
450         size_t slen = 0;
451         u_int compat = 0, flags;
452         int r, ok = -1;
453         char *fp = NULL;
454         struct sshbuf *msg = NULL, *data = NULL;
455         struct sshkey *key = NULL;
456         struct identity *id;
457         struct notifier_ctx *notifier = NULL;
458
459         debug_f("entering");
460
461         if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
462                 fatal_f("sshbuf_new failed");
463         if ((r = sshkey_froms(e->request, &key)) != 0 ||
464             (r = sshbuf_get_stringb(e->request, data)) != 0 ||
465             (r = sshbuf_get_u32(e->request, &flags)) != 0) {
466                 error_fr(r, "parse");
467                 goto send;
468         }
469
470         if ((id = lookup_identity(key)) == NULL) {
471                 verbose_f("%s key not found", sshkey_type(key));
472                 goto send;
473         }
474         if (id->confirm && confirm_key(id, NULL) != 0) {
475                 verbose_f("user refused key");
476                 goto send;
477         }
478         if (sshkey_is_sk(id->key)) {
479                 if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
480                     !check_websafe_message_contents(key, data)) {
481                         /* error already logged */
482                         goto send;
483                 }
484                 if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
485                         if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
486                             SSH_FP_DEFAULT)) == NULL)
487                                 fatal_f("fingerprint failed");
488                         notifier = notify_start(0,
489                             "Confirm user presence for key %s %s",
490                             sshkey_type(id->key), fp);
491                 }
492         }
493         /* XXX support PIN required FIDO keys */
494         if ((r = sshkey_sign(id->key, &signature, &slen,
495             sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
496             id->sk_provider, NULL, compat)) != 0) {
497                 error_fr(r, "sshkey_sign");
498                 goto send;
499         }
500         /* Success */
501         ok = 0;
502  send:
503         notify_complete(notifier, "User presence confirmed");
504
505         if (ok == 0) {
506                 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
507                     (r = sshbuf_put_string(msg, signature, slen)) != 0)
508                         fatal_fr(r, "compose");
509         } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
510                 fatal_fr(r, "compose failure");
511
512         if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
513                 fatal_fr(r, "enqueue");
514
515         sshbuf_free(data);
516         sshbuf_free(msg);
517         sshkey_free(key);
518         free(fp);
519         free(signature);
520 }
521
522 /* shared */
523 static void
524 process_remove_identity(SocketEntry *e)
525 {
526         int r, success = 0;
527         struct sshkey *key = NULL;
528         Identity *id;
529
530         debug2_f("entering");
531         if ((r = sshkey_froms(e->request, &key)) != 0) {
532                 error_fr(r, "parse key");
533                 goto done;
534         }
535         if ((id = lookup_identity(key)) == NULL) {
536                 debug_f("key not found");
537                 goto done;
538         }
539         /* We have this key, free it. */
540         if (idtab->nentries < 1)
541                 fatal_f("internal error: nentries %d", idtab->nentries);
542         TAILQ_REMOVE(&idtab->idlist, id, next);
543         free_identity(id);
544         idtab->nentries--;
545         success = 1;
546  done:
547         sshkey_free(key);
548         send_status(e, success);
549 }
550
551 static void
552 process_remove_all_identities(SocketEntry *e)
553 {
554         Identity *id;
555
556         debug2_f("entering");
557         /* Loop over all identities and clear the keys. */
558         for (id = TAILQ_FIRST(&idtab->idlist); id;
559             id = TAILQ_FIRST(&idtab->idlist)) {
560                 TAILQ_REMOVE(&idtab->idlist, id, next);
561                 free_identity(id);
562         }
563
564         /* Mark that there are no identities. */
565         idtab->nentries = 0;
566
567         /* Send success. */
568         send_status(e, 1);
569 }
570
571 /* removes expired keys and returns number of seconds until the next expiry */
572 static time_t
573 reaper(void)
574 {
575         time_t deadline = 0, now = monotime();
576         Identity *id, *nxt;
577
578         for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
579                 nxt = TAILQ_NEXT(id, next);
580                 if (id->death == 0)
581                         continue;
582                 if (now >= id->death) {
583                         debug("expiring key '%s'", id->comment);
584                         TAILQ_REMOVE(&idtab->idlist, id, next);
585                         free_identity(id);
586                         idtab->nentries--;
587                 } else
588                         deadline = (deadline == 0) ? id->death :
589                             MINIMUM(deadline, id->death);
590         }
591         if (deadline == 0 || deadline <= now)
592                 return 0;
593         else
594                 return (deadline - now);
595 }
596
597 static int
598 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp)
599 {
600         char *ext_name = NULL;
601         int r;
602
603         if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
604                 error_fr(r, "parse constraint extension");
605                 goto out;
606         }
607         debug_f("constraint ext %s", ext_name);
608         if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
609                 if (sk_providerp == NULL) {
610                         error_f("%s not valid here", ext_name);
611                         r = SSH_ERR_INVALID_FORMAT;
612                         goto out;
613                 }
614                 if (*sk_providerp != NULL) {
615                         error_f("%s already set", ext_name);
616                         r = SSH_ERR_INVALID_FORMAT;
617                         goto out;
618                 }
619                 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
620                         error_fr(r, "parse %s", ext_name);
621                         goto out;
622                 }
623         } else {
624                 error_f("unsupported constraint \"%s\"", ext_name);
625                 r = SSH_ERR_FEATURE_UNSUPPORTED;
626                 goto out;
627         }
628         /* success */
629         r = 0;
630  out:
631         free(ext_name);
632         return r;
633 }
634
635 static int
636 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
637     u_int *secondsp, int *confirmp, char **sk_providerp)
638 {
639         u_char ctype;
640         int r;
641         u_int seconds, maxsign = 0;
642
643         while (sshbuf_len(m)) {
644                 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
645                         error_fr(r, "parse constraint type");
646                         goto out;
647                 }
648                 switch (ctype) {
649                 case SSH_AGENT_CONSTRAIN_LIFETIME:
650                         if (*deathp != 0) {
651                                 error_f("lifetime already set");
652                                 r = SSH_ERR_INVALID_FORMAT;
653                                 goto out;
654                         }
655                         if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
656                                 error_fr(r, "parse lifetime constraint");
657                                 goto out;
658                         }
659                         *deathp = monotime() + seconds;
660                         *secondsp = seconds;
661                         break;
662                 case SSH_AGENT_CONSTRAIN_CONFIRM:
663                         if (*confirmp != 0) {
664                                 error_f("confirm already set");
665                                 r = SSH_ERR_INVALID_FORMAT;
666                                 goto out;
667                         }
668                         *confirmp = 1;
669                         break;
670                 case SSH_AGENT_CONSTRAIN_MAXSIGN:
671                         if (k == NULL) {
672                                 error_f("maxsign not valid here");
673                                 r = SSH_ERR_INVALID_FORMAT;
674                                 goto out;
675                         }
676                         if (maxsign != 0) {
677                                 error_f("maxsign already set");
678                                 r = SSH_ERR_INVALID_FORMAT;
679                                 goto out;
680                         }
681                         if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
682                                 error_fr(r, "parse maxsign constraint");
683                                 goto out;
684                         }
685                         if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
686                                 error_fr(r, "enable maxsign");
687                                 goto out;
688                         }
689                         break;
690                 case SSH_AGENT_CONSTRAIN_EXTENSION:
691                         if ((r = parse_key_constraint_extension(m,
692                             sk_providerp)) != 0)
693                                 goto out; /* error already logged */
694                         break;
695                 default:
696                         error_f("Unknown constraint %d", ctype);
697                         r = SSH_ERR_FEATURE_UNSUPPORTED;
698                         goto out;
699                 }
700         }
701         /* success */
702         r = 0;
703  out:
704         return r;
705 }
706
707 static void
708 process_add_identity(SocketEntry *e)
709 {
710         Identity *id;
711         int success = 0, confirm = 0;
712         char *fp, *comment = NULL, *sk_provider = NULL;
713         char canonical_provider[PATH_MAX];
714         time_t death = 0;
715         u_int seconds = 0;
716         struct sshkey *k = NULL;
717         int r = SSH_ERR_INTERNAL_ERROR;
718
719         debug2_f("entering");
720         if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
721             k == NULL ||
722             (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
723                 error_fr(r, "parse");
724                 goto out;
725         }
726         if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
727             &sk_provider) != 0) {
728                 error_f("failed to parse constraints");
729                 sshbuf_reset(e->request);
730                 goto out;
731         }
732
733         if (sk_provider != NULL) {
734                 if (!sshkey_is_sk(k)) {
735                         error("Cannot add provider: %s is not an "
736                             "authenticator-hosted key", sshkey_type(k));
737                         goto out;
738                 }
739                 if (strcasecmp(sk_provider, "internal") == 0) {
740                         debug_f("internal provider");
741                 } else {
742                         if (realpath(sk_provider, canonical_provider) == NULL) {
743                                 verbose("failed provider \"%.100s\": "
744                                     "realpath: %s", sk_provider,
745                                     strerror(errno));
746                                 goto out;
747                         }
748                         free(sk_provider);
749                         sk_provider = xstrdup(canonical_provider);
750                         if (match_pattern_list(sk_provider,
751                             allowed_providers, 0) != 1) {
752                                 error("Refusing add key: "
753                                     "provider %s not allowed", sk_provider);
754                                 goto out;
755                         }
756                 }
757         }
758         if ((r = sshkey_shield_private(k)) != 0) {
759                 error_fr(r, "shield private");
760                 goto out;
761         }
762         if (lifetime && !death)
763                 death = monotime() + lifetime;
764         if ((id = lookup_identity(k)) == NULL) {
765                 id = xcalloc(1, sizeof(Identity));
766                 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
767                 /* Increment the number of identities. */
768                 idtab->nentries++;
769         } else {
770                 /* key state might have been updated */
771                 sshkey_free(id->key);
772                 free(id->comment);
773                 free(id->sk_provider);
774         }
775         /* success */
776         id->key = k;
777         id->comment = comment;
778         id->death = death;
779         id->confirm = confirm;
780         id->sk_provider = sk_provider;
781
782         if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
783             SSH_FP_DEFAULT)) == NULL)
784                 fatal_f("sshkey_fingerprint failed");
785         debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
786             "(provider: %s)", sshkey_ssh_name(k), fp, comment, seconds,
787             confirm, sk_provider == NULL ? "none" : sk_provider);
788         free(fp);
789         /* transferred */
790         k = NULL;
791         comment = NULL;
792         sk_provider = NULL;
793         success = 1;
794  out:
795         free(sk_provider);
796         free(comment);
797         sshkey_free(k);
798         send_status(e, success);
799 }
800
801 /* XXX todo: encrypt sensitive data with passphrase */
802 static void
803 process_lock_agent(SocketEntry *e, int lock)
804 {
805         int r, success = 0, delay;
806         char *passwd;
807         u_char passwdhash[LOCK_SIZE];
808         static u_int fail_count = 0;
809         size_t pwlen;
810
811         debug2_f("entering");
812         /*
813          * This is deliberately fatal: the user has requested that we lock,
814          * but we can't parse their request properly. The only safe thing to
815          * do is abort.
816          */
817         if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
818                 fatal_fr(r, "parse");
819         if (pwlen == 0) {
820                 debug("empty password not supported");
821         } else if (locked && !lock) {
822                 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
823                     passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
824                         fatal("bcrypt_pbkdf");
825                 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
826                         debug("agent unlocked");
827                         locked = 0;
828                         fail_count = 0;
829                         explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
830                         success = 1;
831                 } else {
832                         /* delay in 0.1s increments up to 10s */
833                         if (fail_count < 100)
834                                 fail_count++;
835                         delay = 100000 * fail_count;
836                         debug("unlock failed, delaying %0.1lf seconds",
837                             (double)delay/1000000);
838                         usleep(delay);
839                 }
840                 explicit_bzero(passwdhash, sizeof(passwdhash));
841         } else if (!locked && lock) {
842                 debug("agent locked");
843                 locked = 1;
844                 arc4random_buf(lock_salt, sizeof(lock_salt));
845                 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
846                     lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
847                         fatal("bcrypt_pbkdf");
848                 success = 1;
849         }
850         freezero(passwd, pwlen);
851         send_status(e, success);
852 }
853
854 static void
855 no_identities(SocketEntry *e)
856 {
857         struct sshbuf *msg;
858         int r;
859
860         if ((msg = sshbuf_new()) == NULL)
861                 fatal_f("sshbuf_new failed");
862         if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
863             (r = sshbuf_put_u32(msg, 0)) != 0 ||
864             (r = sshbuf_put_stringb(e->output, msg)) != 0)
865                 fatal_fr(r, "compose");
866         sshbuf_free(msg);
867 }
868
869 #ifdef ENABLE_PKCS11
870 static void
871 process_add_smartcard_key(SocketEntry *e)
872 {
873         char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
874         char **comments = NULL;
875         int r, i, count = 0, success = 0, confirm = 0;
876         u_int seconds = 0;
877         time_t death = 0;
878         struct sshkey **keys = NULL, *k;
879         Identity *id;
880
881         debug2_f("entering");
882         if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
883             (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
884                 error_fr(r, "parse");
885                 goto send;
886         }
887         if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
888             NULL) != 0) {
889                 error_f("failed to parse constraints");
890                 goto send;
891         }
892         if (realpath(provider, canonical_provider) == NULL) {
893                 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
894                     provider, strerror(errno));
895                 goto send;
896         }
897         if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
898                 verbose("refusing PKCS#11 add of \"%.100s\": "
899                     "provider not allowed", canonical_provider);
900                 goto send;
901         }
902         debug_f("add %.100s", canonical_provider);
903         if (lifetime && !death)
904                 death = monotime() + lifetime;
905
906         count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
907         for (i = 0; i < count; i++) {
908                 k = keys[i];
909                 if (lookup_identity(k) == NULL) {
910                         id = xcalloc(1, sizeof(Identity));
911                         id->key = k;
912                         keys[i] = NULL; /* transferred */
913                         id->provider = xstrdup(canonical_provider);
914                         if (*comments[i] != '\0') {
915                                 id->comment = comments[i];
916                                 comments[i] = NULL; /* transferred */
917                         } else {
918                                 id->comment = xstrdup(canonical_provider);
919                         }
920                         id->death = death;
921                         id->confirm = confirm;
922                         TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
923                         idtab->nentries++;
924                         success = 1;
925                 }
926                 /* XXX update constraints for existing keys */
927                 sshkey_free(keys[i]);
928                 free(comments[i]);
929         }
930 send:
931         free(pin);
932         free(provider);
933         free(keys);
934         free(comments);
935         send_status(e, success);
936 }
937
938 static void
939 process_remove_smartcard_key(SocketEntry *e)
940 {
941         char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
942         int r, success = 0;
943         Identity *id, *nxt;
944
945         debug2_f("entering");
946         if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
947             (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
948                 error_fr(r, "parse");
949                 goto send;
950         }
951         free(pin);
952
953         if (realpath(provider, canonical_provider) == NULL) {
954                 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
955                     provider, strerror(errno));
956                 goto send;
957         }
958
959         debug_f("remove %.100s", canonical_provider);
960         for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
961                 nxt = TAILQ_NEXT(id, next);
962                 /* Skip file--based keys */
963                 if (id->provider == NULL)
964                         continue;
965                 if (!strcmp(canonical_provider, id->provider)) {
966                         TAILQ_REMOVE(&idtab->idlist, id, next);
967                         free_identity(id);
968                         idtab->nentries--;
969                 }
970         }
971         if (pkcs11_del_provider(canonical_provider) == 0)
972                 success = 1;
973         else
974                 error_f("pkcs11_del_provider failed");
975 send:
976         free(provider);
977         send_status(e, success);
978 }
979 #endif /* ENABLE_PKCS11 */
980
981 /*
982  * dispatch incoming message.
983  * returns 1 on success, 0 for incomplete messages or -1 on error.
984  */
985 static int
986 process_message(u_int socknum)
987 {
988         u_int msg_len;
989         u_char type;
990         const u_char *cp;
991         int r;
992         SocketEntry *e;
993
994         if (socknum >= sockets_alloc)
995                 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
996         e = &sockets[socknum];
997
998         if (sshbuf_len(e->input) < 5)
999                 return 0;               /* Incomplete message header. */
1000         cp = sshbuf_ptr(e->input);
1001         msg_len = PEEK_U32(cp);
1002         if (msg_len > AGENT_MAX_LEN) {
1003                 debug_f("socket %u (fd=%d) message too long %u > %u",
1004                     socknum, e->fd, msg_len, AGENT_MAX_LEN);
1005                 return -1;
1006         }
1007         if (sshbuf_len(e->input) < msg_len + 4)
1008                 return 0;               /* Incomplete message body. */
1009
1010         /* move the current input to e->request */
1011         sshbuf_reset(e->request);
1012         if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1013             (r = sshbuf_get_u8(e->request, &type)) != 0) {
1014                 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1015                     r == SSH_ERR_STRING_TOO_LARGE) {
1016                         error_fr(r, "parse");
1017                         return -1;
1018                 }
1019                 fatal_fr(r, "parse");
1020         }
1021
1022         debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1023
1024         /* check whether agent is locked */
1025         if (locked && type != SSH_AGENTC_UNLOCK) {
1026                 sshbuf_reset(e->request);
1027                 switch (type) {
1028                 case SSH2_AGENTC_REQUEST_IDENTITIES:
1029                         /* send empty lists */
1030                         no_identities(e);
1031                         break;
1032                 default:
1033                         /* send a fail message for all other request types */
1034                         send_status(e, 0);
1035                 }
1036                 return 1;
1037         }
1038
1039         switch (type) {
1040         case SSH_AGENTC_LOCK:
1041         case SSH_AGENTC_UNLOCK:
1042                 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1043                 break;
1044         case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1045                 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1046                 break;
1047         /* ssh2 */
1048         case SSH2_AGENTC_SIGN_REQUEST:
1049                 process_sign_request2(e);
1050                 break;
1051         case SSH2_AGENTC_REQUEST_IDENTITIES:
1052                 process_request_identities(e);
1053                 break;
1054         case SSH2_AGENTC_ADD_IDENTITY:
1055         case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1056                 process_add_identity(e);
1057                 break;
1058         case SSH2_AGENTC_REMOVE_IDENTITY:
1059                 process_remove_identity(e);
1060                 break;
1061         case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1062                 process_remove_all_identities(e);
1063                 break;
1064 #ifdef ENABLE_PKCS11
1065         case SSH_AGENTC_ADD_SMARTCARD_KEY:
1066         case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1067                 process_add_smartcard_key(e);
1068                 break;
1069         case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1070                 process_remove_smartcard_key(e);
1071                 break;
1072 #endif /* ENABLE_PKCS11 */
1073         default:
1074                 /* Unknown message.  Respond with failure. */
1075                 error("Unknown message %d", type);
1076                 sshbuf_reset(e->request);
1077                 send_status(e, 0);
1078                 break;
1079         }
1080         return 1;
1081 }
1082
1083 static void
1084 new_socket(sock_type type, int fd)
1085 {
1086         u_int i, old_alloc, new_alloc;
1087
1088         debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1089             (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1090         if (type == AUTH_CONNECTION) {
1091                 debug("xcount %d -> %d", xcount, xcount + 1);
1092                 ++xcount;
1093         }
1094         set_nonblock(fd);
1095
1096         if (fd > max_fd)
1097                 max_fd = fd;
1098
1099         for (i = 0; i < sockets_alloc; i++)
1100                 if (sockets[i].type == AUTH_UNUSED) {
1101                         sockets[i].fd = fd;
1102                         if ((sockets[i].input = sshbuf_new()) == NULL ||
1103                             (sockets[i].output = sshbuf_new()) == NULL ||
1104                             (sockets[i].request = sshbuf_new()) == NULL)
1105                                 fatal_f("sshbuf_new failed");
1106                         sockets[i].type = type;
1107                         return;
1108                 }
1109         old_alloc = sockets_alloc;
1110         new_alloc = sockets_alloc + 10;
1111         sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1112             sizeof(sockets[0]));
1113         for (i = old_alloc; i < new_alloc; i++)
1114                 sockets[i].type = AUTH_UNUSED;
1115         sockets_alloc = new_alloc;
1116         sockets[old_alloc].fd = fd;
1117         if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1118             (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1119             (sockets[old_alloc].request = sshbuf_new()) == NULL)
1120                 fatal_f("sshbuf_new failed");
1121         sockets[old_alloc].type = type;
1122 }
1123
1124 static int
1125 handle_socket_read(u_int socknum)
1126 {
1127         struct sockaddr_un sunaddr;
1128         socklen_t slen;
1129         uid_t euid;
1130         gid_t egid;
1131         int fd;
1132
1133         slen = sizeof(sunaddr);
1134         fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1135         if (fd == -1) {
1136                 error("accept from AUTH_SOCKET: %s", strerror(errno));
1137                 return -1;
1138         }
1139         if (getpeereid(fd, &euid, &egid) == -1) {
1140                 error("getpeereid %d failed: %s", fd, strerror(errno));
1141                 close(fd);
1142                 return -1;
1143         }
1144         if ((euid != 0) && (getuid() != euid)) {
1145                 error("uid mismatch: peer euid %u != uid %u",
1146                     (u_int) euid, (u_int) getuid());
1147                 close(fd);
1148                 return -1;
1149         }
1150         new_socket(AUTH_CONNECTION, fd);
1151         return 0;
1152 }
1153
1154 static int
1155 handle_conn_read(u_int socknum)
1156 {
1157         char buf[AGENT_RBUF_LEN];
1158         ssize_t len;
1159         int r;
1160
1161         if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1162                 if (len == -1) {
1163                         if (errno == EAGAIN || errno == EINTR)
1164                                 return 0;
1165                         error_f("read error on socket %u (fd %d): %s",
1166                             socknum, sockets[socknum].fd, strerror(errno));
1167                 }
1168                 return -1;
1169         }
1170         if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1171                 fatal_fr(r, "compose");
1172         explicit_bzero(buf, sizeof(buf));
1173         for (;;) {
1174                 if ((r = process_message(socknum)) == -1)
1175                         return -1;
1176                 else if (r == 0)
1177                         break;
1178         }
1179         return 0;
1180 }
1181
1182 static int
1183 handle_conn_write(u_int socknum)
1184 {
1185         ssize_t len;
1186         int r;
1187
1188         if (sshbuf_len(sockets[socknum].output) == 0)
1189                 return 0; /* shouldn't happen */
1190         if ((len = write(sockets[socknum].fd,
1191             sshbuf_ptr(sockets[socknum].output),
1192             sshbuf_len(sockets[socknum].output))) <= 0) {
1193                 if (len == -1) {
1194                         if (errno == EAGAIN || errno == EINTR)
1195                                 return 0;
1196                         error_f("read error on socket %u (fd %d): %s",
1197                             socknum, sockets[socknum].fd, strerror(errno));
1198                 }
1199                 return -1;
1200         }
1201         if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1202                 fatal_fr(r, "consume");
1203         return 0;
1204 }
1205
1206 static void
1207 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1208 {
1209         size_t i;
1210         u_int socknum, activefds = npfd;
1211
1212         for (i = 0; i < npfd; i++) {
1213                 if (pfd[i].revents == 0)
1214                         continue;
1215                 /* Find sockets entry */
1216                 for (socknum = 0; socknum < sockets_alloc; socknum++) {
1217                         if (sockets[socknum].type != AUTH_SOCKET &&
1218                             sockets[socknum].type != AUTH_CONNECTION)
1219                                 continue;
1220                         if (pfd[i].fd == sockets[socknum].fd)
1221                                 break;
1222                 }
1223                 if (socknum >= sockets_alloc) {
1224                         error_f("no socket for fd %d", pfd[i].fd);
1225                         continue;
1226                 }
1227                 /* Process events */
1228                 switch (sockets[socknum].type) {
1229                 case AUTH_SOCKET:
1230                         if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1231                                 break;
1232                         if (npfd > maxfds) {
1233                                 debug3("out of fds (active %u >= limit %u); "
1234                                     "skipping accept", activefds, maxfds);
1235                                 break;
1236                         }
1237                         if (handle_socket_read(socknum) == 0)
1238                                 activefds++;
1239                         break;
1240                 case AUTH_CONNECTION:
1241                         if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1242                             handle_conn_read(socknum) != 0) {
1243                                 goto close_sock;
1244                         }
1245                         if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1246                             handle_conn_write(socknum) != 0) {
1247  close_sock:
1248                                 if (activefds == 0)
1249                                         fatal("activefds == 0 at close_sock");
1250                                 close_socket(&sockets[socknum]);
1251                                 activefds--;
1252                                 break;
1253                         }
1254                         break;
1255                 default:
1256                         break;
1257                 }
1258         }
1259 }
1260
1261 static int
1262 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1263 {
1264         struct pollfd *pfd = *pfdp;
1265         size_t i, j, npfd = 0;
1266         time_t deadline;
1267         int r;
1268
1269         /* Count active sockets */
1270         for (i = 0; i < sockets_alloc; i++) {
1271                 switch (sockets[i].type) {
1272                 case AUTH_SOCKET:
1273                 case AUTH_CONNECTION:
1274                         npfd++;
1275                         break;
1276                 case AUTH_UNUSED:
1277                         break;
1278                 default:
1279                         fatal("Unknown socket type %d", sockets[i].type);
1280                         break;
1281                 }
1282         }
1283         if (npfd != *npfdp &&
1284             (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1285                 fatal_f("recallocarray failed");
1286         *pfdp = pfd;
1287         *npfdp = npfd;
1288
1289         for (i = j = 0; i < sockets_alloc; i++) {
1290                 switch (sockets[i].type) {
1291                 case AUTH_SOCKET:
1292                         if (npfd > maxfds) {
1293                                 debug3("out of fds (active %zu >= limit %u); "
1294                                     "skipping arming listener", npfd, maxfds);
1295                                 break;
1296                         }
1297                         pfd[j].fd = sockets[i].fd;
1298                         pfd[j].revents = 0;
1299                         pfd[j].events = POLLIN;
1300                         j++;
1301                         break;
1302                 case AUTH_CONNECTION:
1303                         pfd[j].fd = sockets[i].fd;
1304                         pfd[j].revents = 0;
1305                         /*
1306                          * Only prepare to read if we can handle a full-size
1307                          * input read buffer and enqueue a max size reply..
1308                          */
1309                         if ((r = sshbuf_check_reserve(sockets[i].input,
1310                             AGENT_RBUF_LEN)) == 0 &&
1311                             (r = sshbuf_check_reserve(sockets[i].output,
1312                             AGENT_MAX_LEN)) == 0)
1313                                 pfd[j].events = POLLIN;
1314                         else if (r != SSH_ERR_NO_BUFFER_SPACE)
1315                                 fatal_fr(r, "reserve");
1316                         if (sshbuf_len(sockets[i].output) > 0)
1317                                 pfd[j].events |= POLLOUT;
1318                         j++;
1319                         break;
1320                 default:
1321                         break;
1322                 }
1323         }
1324         deadline = reaper();
1325         if (parent_alive_interval != 0)
1326                 deadline = (deadline == 0) ? parent_alive_interval :
1327                     MINIMUM(deadline, parent_alive_interval);
1328         if (deadline == 0) {
1329                 *timeoutp = -1; /* INFTIM */
1330         } else {
1331                 if (deadline > INT_MAX / 1000)
1332                         *timeoutp = INT_MAX / 1000;
1333                 else
1334                         *timeoutp = deadline * 1000;
1335         }
1336         return (1);
1337 }
1338
1339 static void
1340 cleanup_socket(void)
1341 {
1342         if (cleanup_pid != 0 && getpid() != cleanup_pid)
1343                 return;
1344         debug_f("cleanup");
1345         if (socket_name[0])
1346                 unlink(socket_name);
1347         if (socket_dir[0])
1348                 rmdir(socket_dir);
1349 }
1350
1351 void
1352 cleanup_exit(int i)
1353 {
1354         cleanup_socket();
1355         _exit(i);
1356 }
1357
1358 /*ARGSUSED*/
1359 static void
1360 cleanup_handler(int sig)
1361 {
1362         cleanup_socket();
1363 #ifdef ENABLE_PKCS11
1364         pkcs11_terminate();
1365 #endif
1366         _exit(2);
1367 }
1368
1369 static void
1370 check_parent_exists(void)
1371 {
1372         /*
1373          * If our parent has exited then getppid() will return (pid_t)1,
1374          * so testing for that should be safe.
1375          */
1376         if (parent_pid != -1 && getppid() != parent_pid) {
1377                 /* printf("Parent has died - Authentication agent exiting.\n"); */
1378                 cleanup_socket();
1379                 _exit(2);
1380         }
1381 }
1382
1383 static void
1384 usage(void)
1385 {
1386         fprintf(stderr,
1387             "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1388             "                 [-P allowed_providers] [-t life]\n"
1389             "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
1390             "                 [-t life] command [arg ...]\n"
1391             "       ssh-agent [-c | -s] -k\n");
1392         exit(1);
1393 }
1394
1395 int
1396 main(int ac, char **av)
1397 {
1398         int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1399         int sock, ch, result, saved_errno;
1400         char *shell, *format, *pidstr, *agentsocket = NULL;
1401 #ifdef HAVE_SETRLIMIT
1402         struct rlimit rlim;
1403 #endif
1404         extern int optind;
1405         extern char *optarg;
1406         pid_t pid;
1407         char pidstrbuf[1 + 3 * sizeof pid];
1408         size_t len;
1409         mode_t prev_mask;
1410         int timeout = -1; /* INFTIM */
1411         struct pollfd *pfd = NULL;
1412         size_t npfd = 0;
1413         u_int maxfds;
1414
1415         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1416         sanitise_stdfd();
1417
1418         /* drop */
1419         setegid(getgid());
1420         setgid(getgid());
1421         setuid(geteuid());
1422
1423         platform_disable_tracing(0);    /* strict=no */
1424
1425 #ifdef RLIMIT_NOFILE
1426         if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1427                 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1428 #endif
1429
1430         __progname = ssh_get_progname(av[0]);
1431         seed_rng();
1432
1433         while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
1434                 switch (ch) {
1435                 case 'E':
1436                         fingerprint_hash = ssh_digest_alg_by_name(optarg);
1437                         if (fingerprint_hash == -1)
1438                                 fatal("Invalid hash algorithm \"%s\"", optarg);
1439                         break;
1440                 case 'c':
1441                         if (s_flag)
1442                                 usage();
1443                         c_flag++;
1444                         break;
1445                 case 'k':
1446                         k_flag++;
1447                         break;
1448                 case 'O':
1449                         if (strcmp(optarg, "no-restrict-websafe") == 0)
1450                                 restrict_websafe  = 0;
1451                         else
1452                                 fatal("Unknown -O option");
1453                         break;
1454                 case 'P':
1455                         if (allowed_providers != NULL)
1456                                 fatal("-P option already specified");
1457                         allowed_providers = xstrdup(optarg);
1458                         break;
1459                 case 's':
1460                         if (c_flag)
1461                                 usage();
1462                         s_flag++;
1463                         break;
1464                 case 'd':
1465                         if (d_flag || D_flag)
1466                                 usage();
1467                         d_flag++;
1468                         break;
1469                 case 'D':
1470                         if (d_flag || D_flag)
1471                                 usage();
1472                         D_flag++;
1473                         break;
1474                 case 'a':
1475                         agentsocket = optarg;
1476                         break;
1477                 case 't':
1478                         if ((lifetime = convtime(optarg)) == -1) {
1479                                 fprintf(stderr, "Invalid lifetime\n");
1480                                 usage();
1481                         }
1482                         break;
1483                 case 'x':
1484                         xcount = 0;
1485                         break;
1486                 default:
1487                         usage();
1488                 }
1489         }
1490         ac -= optind;
1491         av += optind;
1492
1493         if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1494                 usage();
1495
1496         if (allowed_providers == NULL)
1497                 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
1498
1499         if (ac == 0 && !c_flag && !s_flag) {
1500                 shell = getenv("SHELL");
1501                 if (shell != NULL && (len = strlen(shell)) > 2 &&
1502                     strncmp(shell + len - 3, "csh", 3) == 0)
1503                         c_flag = 1;
1504         }
1505         if (k_flag) {
1506                 const char *errstr = NULL;
1507
1508                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1509                 if (pidstr == NULL) {
1510                         fprintf(stderr, "%s not set, cannot kill agent\n",
1511                             SSH_AGENTPID_ENV_NAME);
1512                         exit(1);
1513                 }
1514                 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1515                 if (errstr) {
1516                         fprintf(stderr,
1517                             "%s=\"%s\", which is not a good PID: %s\n",
1518                             SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1519                         exit(1);
1520                 }
1521                 if (kill(pid, SIGTERM) == -1) {
1522                         perror("kill");
1523                         exit(1);
1524                 }
1525                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1526                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1527                 printf(format, SSH_AGENTPID_ENV_NAME);
1528                 printf("echo Agent pid %ld killed;\n", (long)pid);
1529                 exit(0);
1530         }
1531
1532         /*
1533          * Minimum file descriptors:
1534          * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1535          * a few spare for libc / stack protectors / sanitisers, etc.
1536          */
1537 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1538         if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1539                 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1540                     __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1541         maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1542
1543         parent_pid = getpid();
1544
1545         if (agentsocket == NULL) {
1546                 /* Create private directory for agent socket */
1547                 mktemp_proto(socket_dir, sizeof(socket_dir));
1548                 if (mkdtemp(socket_dir) == NULL) {
1549                         perror("mkdtemp: private socket dir");
1550                         exit(1);
1551                 }
1552                 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1553                     (long)parent_pid);
1554         } else {
1555                 /* Try to use specified agent socket */
1556                 socket_dir[0] = '\0';
1557                 strlcpy(socket_name, agentsocket, sizeof socket_name);
1558         }
1559
1560         /*
1561          * Create socket early so it will exist before command gets run from
1562          * the parent.
1563          */
1564         prev_mask = umask(0177);
1565         sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1566         if (sock < 0) {
1567                 /* XXX - unix_listener() calls error() not perror() */
1568                 *socket_name = '\0'; /* Don't unlink any existing file */
1569                 cleanup_exit(1);
1570         }
1571         umask(prev_mask);
1572
1573         /*
1574          * Fork, and have the parent execute the command, if any, or present
1575          * the socket data.  The child continues as the authentication agent.
1576          */
1577         if (D_flag || d_flag) {
1578                 log_init(__progname,
1579                     d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1580                     SYSLOG_FACILITY_AUTH, 1);
1581                 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1582                 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1583                     SSH_AUTHSOCKET_ENV_NAME);
1584                 printf("echo Agent pid %ld;\n", (long)parent_pid);
1585                 fflush(stdout);
1586                 goto skip;
1587         }
1588         pid = fork();
1589         if (pid == -1) {
1590                 perror("fork");
1591                 cleanup_exit(1);
1592         }
1593         if (pid != 0) {         /* Parent - execute the given command. */
1594                 close(sock);
1595                 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1596                 if (ac == 0) {
1597                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1598                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1599                             SSH_AUTHSOCKET_ENV_NAME);
1600                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1601                             SSH_AGENTPID_ENV_NAME);
1602                         printf("echo Agent pid %ld;\n", (long)pid);
1603                         exit(0);
1604                 }
1605                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1606                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1607                         perror("setenv");
1608                         exit(1);
1609                 }
1610                 execvp(av[0], av);
1611                 perror(av[0]);
1612                 exit(1);
1613         }
1614         /* child */
1615         log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1616
1617         if (setsid() == -1) {
1618                 error("setsid: %s", strerror(errno));
1619                 cleanup_exit(1);
1620         }
1621
1622         (void)chdir("/");
1623         if (stdfd_devnull(1, 1, 1) == -1)
1624                 error_f("stdfd_devnull failed");
1625
1626 #ifdef HAVE_SETRLIMIT
1627         /* deny core dumps, since memory contains unencrypted private keys */
1628         rlim.rlim_cur = rlim.rlim_max = 0;
1629         if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1630                 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1631                 cleanup_exit(1);
1632         }
1633 #endif
1634
1635 skip:
1636
1637         cleanup_pid = getpid();
1638
1639 #ifdef ENABLE_PKCS11
1640         pkcs11_init(0);
1641 #endif
1642         new_socket(AUTH_SOCKET, sock);
1643         if (ac > 0)
1644                 parent_alive_interval = 10;
1645         idtab_init();
1646         ssh_signal(SIGPIPE, SIG_IGN);
1647         ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1648         ssh_signal(SIGHUP, cleanup_handler);
1649         ssh_signal(SIGTERM, cleanup_handler);
1650
1651         if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1652                 fatal("%s: pledge: %s", __progname, strerror(errno));
1653         platform_pledge_agent();
1654
1655         while (1) {
1656                 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1657                 result = poll(pfd, npfd, timeout);
1658                 saved_errno = errno;
1659                 if (parent_alive_interval != 0)
1660                         check_parent_exists();
1661                 (void) reaper();        /* remove expired keys */
1662                 if (result == -1) {
1663                         if (saved_errno == EINTR)
1664                                 continue;
1665                         fatal("poll: %s", strerror(saved_errno));
1666                 } else if (result > 0)
1667                         after_poll(pfd, npfd, maxfds);
1668         }
1669         /* NOTREACHED */
1670 }