]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - ssh-agent.c
Vendor import of OpenSSH 6.6p1.
[FreeBSD/FreeBSD.git] / ssh-agent.c
1 /* $OpenBSD: ssh-agent.c,v 1.183 2014/02/02 03:44:31 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/param.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43 #include <sys/socket.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 #include <openssl/evp.h>
53 #include "openbsd-compat/openssl-compat.h"
54
55 #include <errno.h>
56 #include <fcntl.h>
57 #ifdef HAVE_PATHS_H
58 # include <paths.h>
59 #endif
60 #include <signal.h>
61 #include <stdarg.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <time.h>
65 #include <string.h>
66 #include <unistd.h>
67
68 #include "xmalloc.h"
69 #include "ssh.h"
70 #include "rsa.h"
71 #include "buffer.h"
72 #include "key.h"
73 #include "authfd.h"
74 #include "compat.h"
75 #include "log.h"
76 #include "misc.h"
77 #include "digest.h"
78
79 #ifdef ENABLE_PKCS11
80 #include "ssh-pkcs11.h"
81 #endif
82
83 #if defined(HAVE_SYS_PRCTL_H)
84 #include <sys/prctl.h>  /* For prctl() and PR_SET_DUMPABLE */
85 #endif
86
87 typedef enum {
88         AUTH_UNUSED,
89         AUTH_SOCKET,
90         AUTH_CONNECTION
91 } sock_type;
92
93 typedef struct {
94         int fd;
95         sock_type type;
96         Buffer input;
97         Buffer output;
98         Buffer request;
99 } SocketEntry;
100
101 u_int sockets_alloc = 0;
102 SocketEntry *sockets = NULL;
103
104 typedef struct identity {
105         TAILQ_ENTRY(identity) next;
106         Key *key;
107         char *comment;
108         char *provider;
109         time_t death;
110         u_int confirm;
111 } Identity;
112
113 typedef struct {
114         int nentries;
115         TAILQ_HEAD(idqueue, identity) idlist;
116 } Idtab;
117
118 /* private key table, one per protocol version */
119 Idtab idtable[3];
120
121 int max_fd = 0;
122
123 /* pid of shell == parent of agent */
124 pid_t parent_pid = -1;
125 time_t parent_alive_interval = 0;
126
127 /* pathname and directory for AUTH_SOCKET */
128 char socket_name[MAXPATHLEN];
129 char socket_dir[MAXPATHLEN];
130
131 /* locking */
132 int locked = 0;
133 char *lock_passwd = NULL;
134
135 extern char *__progname;
136
137 /* Default lifetime in seconds (0 == forever) */
138 static long lifetime = 0;
139
140 static void
141 close_socket(SocketEntry *e)
142 {
143         close(e->fd);
144         e->fd = -1;
145         e->type = AUTH_UNUSED;
146         buffer_free(&e->input);
147         buffer_free(&e->output);
148         buffer_free(&e->request);
149 }
150
151 static void
152 idtab_init(void)
153 {
154         int i;
155
156         for (i = 0; i <=2; i++) {
157                 TAILQ_INIT(&idtable[i].idlist);
158                 idtable[i].nentries = 0;
159         }
160 }
161
162 /* return private key table for requested protocol version */
163 static Idtab *
164 idtab_lookup(int version)
165 {
166         if (version < 1 || version > 2)
167                 fatal("internal error, bad protocol version %d", version);
168         return &idtable[version];
169 }
170
171 static void
172 free_identity(Identity *id)
173 {
174         key_free(id->key);
175         free(id->provider);
176         free(id->comment);
177         free(id);
178 }
179
180 /* return matching private key for given public key */
181 static Identity *
182 lookup_identity(Key *key, int version)
183 {
184         Identity *id;
185
186         Idtab *tab = idtab_lookup(version);
187         TAILQ_FOREACH(id, &tab->idlist, next) {
188                 if (key_equal(key, id->key))
189                         return (id);
190         }
191         return (NULL);
192 }
193
194 /* Check confirmation of keysign request */
195 static int
196 confirm_key(Identity *id)
197 {
198         char *p;
199         int ret = -1;
200
201         p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
202         if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
203             id->comment, p))
204                 ret = 0;
205         free(p);
206
207         return (ret);
208 }
209
210 /* send list of supported public keys to 'client' */
211 static void
212 process_request_identities(SocketEntry *e, int version)
213 {
214         Idtab *tab = idtab_lookup(version);
215         Identity *id;
216         Buffer msg;
217
218         buffer_init(&msg);
219         buffer_put_char(&msg, (version == 1) ?
220             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
221         buffer_put_int(&msg, tab->nentries);
222         TAILQ_FOREACH(id, &tab->idlist, next) {
223                 if (id->key->type == KEY_RSA1) {
224                         buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
225                         buffer_put_bignum(&msg, id->key->rsa->e);
226                         buffer_put_bignum(&msg, id->key->rsa->n);
227                 } else {
228                         u_char *blob;
229                         u_int blen;
230                         key_to_blob(id->key, &blob, &blen);
231                         buffer_put_string(&msg, blob, blen);
232                         free(blob);
233                 }
234                 buffer_put_cstring(&msg, id->comment);
235         }
236         buffer_put_int(&e->output, buffer_len(&msg));
237         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
238         buffer_free(&msg);
239 }
240
241 /* ssh1 only */
242 static void
243 process_authentication_challenge1(SocketEntry *e)
244 {
245         u_char buf[32], mdbuf[16], session_id[16];
246         u_int response_type;
247         BIGNUM *challenge;
248         Identity *id;
249         int i, len;
250         Buffer msg;
251         struct ssh_digest_ctx *md;
252         Key *key;
253
254         buffer_init(&msg);
255         key = key_new(KEY_RSA1);
256         if ((challenge = BN_new()) == NULL)
257                 fatal("process_authentication_challenge1: BN_new failed");
258
259         (void) buffer_get_int(&e->request);                     /* ignored */
260         buffer_get_bignum(&e->request, key->rsa->e);
261         buffer_get_bignum(&e->request, key->rsa->n);
262         buffer_get_bignum(&e->request, challenge);
263
264         /* Only protocol 1.1 is supported */
265         if (buffer_len(&e->request) == 0)
266                 goto failure;
267         buffer_get(&e->request, session_id, 16);
268         response_type = buffer_get_int(&e->request);
269         if (response_type != 1)
270                 goto failure;
271
272         id = lookup_identity(key, 1);
273         if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
274                 Key *private = id->key;
275                 /* Decrypt the challenge using the private key. */
276                 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
277                         goto failure;
278
279                 /* The response is MD5 of decrypted challenge plus session id. */
280                 len = BN_num_bytes(challenge);
281                 if (len <= 0 || len > 32) {
282                         logit("process_authentication_challenge: bad challenge length %d", len);
283                         goto failure;
284                 }
285                 memset(buf, 0, 32);
286                 BN_bn2bin(challenge, buf + 32 - len);
287                 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
288                     ssh_digest_update(md, buf, 32) < 0 ||
289                     ssh_digest_update(md, session_id, 16) < 0 ||
290                     ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
291                         fatal("%s: md5 failed", __func__);
292                 ssh_digest_free(md);
293
294                 /* Send the response. */
295                 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
296                 for (i = 0; i < 16; i++)
297                         buffer_put_char(&msg, mdbuf[i]);
298                 goto send;
299         }
300
301 failure:
302         /* Unknown identity or protocol error.  Send failure. */
303         buffer_put_char(&msg, SSH_AGENT_FAILURE);
304 send:
305         buffer_put_int(&e->output, buffer_len(&msg));
306         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
307         key_free(key);
308         BN_clear_free(challenge);
309         buffer_free(&msg);
310 }
311
312 /* ssh2 only */
313 static void
314 process_sign_request2(SocketEntry *e)
315 {
316         u_char *blob, *data, *signature = NULL;
317         u_int blen, dlen, slen = 0;
318         extern int datafellows;
319         int odatafellows;
320         int ok = -1, flags;
321         Buffer msg;
322         Key *key;
323
324         datafellows = 0;
325
326         blob = buffer_get_string(&e->request, &blen);
327         data = buffer_get_string(&e->request, &dlen);
328
329         flags = buffer_get_int(&e->request);
330         odatafellows = datafellows;
331         if (flags & SSH_AGENT_OLD_SIGNATURE)
332                 datafellows = SSH_BUG_SIGBLOB;
333
334         key = key_from_blob(blob, blen);
335         if (key != NULL) {
336                 Identity *id = lookup_identity(key, 2);
337                 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
338                         ok = key_sign(id->key, &signature, &slen, data, dlen);
339                 key_free(key);
340         }
341         buffer_init(&msg);
342         if (ok == 0) {
343                 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
344                 buffer_put_string(&msg, signature, slen);
345         } else {
346                 buffer_put_char(&msg, SSH_AGENT_FAILURE);
347         }
348         buffer_put_int(&e->output, buffer_len(&msg));
349         buffer_append(&e->output, buffer_ptr(&msg),
350             buffer_len(&msg));
351         buffer_free(&msg);
352         free(data);
353         free(blob);
354         free(signature);
355         datafellows = odatafellows;
356 }
357
358 /* shared */
359 static void
360 process_remove_identity(SocketEntry *e, int version)
361 {
362         u_int blen, bits;
363         int success = 0;
364         Key *key = NULL;
365         u_char *blob;
366
367         switch (version) {
368         case 1:
369                 key = key_new(KEY_RSA1);
370                 bits = buffer_get_int(&e->request);
371                 buffer_get_bignum(&e->request, key->rsa->e);
372                 buffer_get_bignum(&e->request, key->rsa->n);
373
374                 if (bits != key_size(key))
375                         logit("Warning: identity keysize mismatch: actual %u, announced %u",
376                             key_size(key), bits);
377                 break;
378         case 2:
379                 blob = buffer_get_string(&e->request, &blen);
380                 key = key_from_blob(blob, blen);
381                 free(blob);
382                 break;
383         }
384         if (key != NULL) {
385                 Identity *id = lookup_identity(key, version);
386                 if (id != NULL) {
387                         /*
388                          * We have this key.  Free the old key.  Since we
389                          * don't want to leave empty slots in the middle of
390                          * the array, we actually free the key there and move
391                          * all the entries between the empty slot and the end
392                          * of the array.
393                          */
394                         Idtab *tab = idtab_lookup(version);
395                         if (tab->nentries < 1)
396                                 fatal("process_remove_identity: "
397                                     "internal error: tab->nentries %d",
398                                     tab->nentries);
399                         TAILQ_REMOVE(&tab->idlist, id, next);
400                         free_identity(id);
401                         tab->nentries--;
402                         success = 1;
403                 }
404                 key_free(key);
405         }
406         buffer_put_int(&e->output, 1);
407         buffer_put_char(&e->output,
408             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
409 }
410
411 static void
412 process_remove_all_identities(SocketEntry *e, int version)
413 {
414         Idtab *tab = idtab_lookup(version);
415         Identity *id;
416
417         /* Loop over all identities and clear the keys. */
418         for (id = TAILQ_FIRST(&tab->idlist); id;
419             id = TAILQ_FIRST(&tab->idlist)) {
420                 TAILQ_REMOVE(&tab->idlist, id, next);
421                 free_identity(id);
422         }
423
424         /* Mark that there are no identities. */
425         tab->nentries = 0;
426
427         /* Send success. */
428         buffer_put_int(&e->output, 1);
429         buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
430 }
431
432 /* removes expired keys and returns number of seconds until the next expiry */
433 static time_t
434 reaper(void)
435 {
436         time_t deadline = 0, now = monotime();
437         Identity *id, *nxt;
438         int version;
439         Idtab *tab;
440
441         for (version = 1; version < 3; version++) {
442                 tab = idtab_lookup(version);
443                 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
444                         nxt = TAILQ_NEXT(id, next);
445                         if (id->death == 0)
446                                 continue;
447                         if (now >= id->death) {
448                                 debug("expiring key '%s'", id->comment);
449                                 TAILQ_REMOVE(&tab->idlist, id, next);
450                                 free_identity(id);
451                                 tab->nentries--;
452                         } else
453                                 deadline = (deadline == 0) ? id->death :
454                                     MIN(deadline, id->death);
455                 }
456         }
457         if (deadline == 0 || deadline <= now)
458                 return 0;
459         else
460                 return (deadline - now);
461 }
462
463 static void
464 process_add_identity(SocketEntry *e, int version)
465 {
466         Idtab *tab = idtab_lookup(version);
467         Identity *id;
468         int type, success = 0, confirm = 0;
469         char *comment;
470         time_t death = 0;
471         Key *k = NULL;
472
473         switch (version) {
474         case 1:
475                 k = key_new_private(KEY_RSA1);
476                 (void) buffer_get_int(&e->request);             /* ignored */
477                 buffer_get_bignum(&e->request, k->rsa->n);
478                 buffer_get_bignum(&e->request, k->rsa->e);
479                 buffer_get_bignum(&e->request, k->rsa->d);
480                 buffer_get_bignum(&e->request, k->rsa->iqmp);
481
482                 /* SSH and SSL have p and q swapped */
483                 buffer_get_bignum(&e->request, k->rsa->q);      /* p */
484                 buffer_get_bignum(&e->request, k->rsa->p);      /* q */
485
486                 /* Generate additional parameters */
487                 rsa_generate_additional_parameters(k->rsa);
488
489                 /* enable blinding */
490                 if (RSA_blinding_on(k->rsa, NULL) != 1) {
491                         error("process_add_identity: RSA_blinding_on failed");
492                         key_free(k);
493                         goto send;
494                 }
495                 break;
496         case 2:
497                 k = key_private_deserialize(&e->request);
498                 if (k == NULL) {
499                         buffer_clear(&e->request);
500                         goto send;
501                 }
502                 break;
503         }
504         comment = buffer_get_string(&e->request, NULL);
505         if (k == NULL) {
506                 free(comment);
507                 goto send;
508         }
509         while (buffer_len(&e->request)) {
510                 switch ((type = buffer_get_char(&e->request))) {
511                 case SSH_AGENT_CONSTRAIN_LIFETIME:
512                         death = monotime() + buffer_get_int(&e->request);
513                         break;
514                 case SSH_AGENT_CONSTRAIN_CONFIRM:
515                         confirm = 1;
516                         break;
517                 default:
518                         error("process_add_identity: "
519                             "Unknown constraint type %d", type);
520                         free(comment);
521                         key_free(k);
522                         goto send;
523                 }
524         }
525         success = 1;
526         if (lifetime && !death)
527                 death = monotime() + lifetime;
528         if ((id = lookup_identity(k, version)) == NULL) {
529                 id = xcalloc(1, sizeof(Identity));
530                 id->key = k;
531                 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
532                 /* Increment the number of identities. */
533                 tab->nentries++;
534         } else {
535                 key_free(k);
536                 free(id->comment);
537         }
538         id->comment = comment;
539         id->death = death;
540         id->confirm = confirm;
541 send:
542         buffer_put_int(&e->output, 1);
543         buffer_put_char(&e->output,
544             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
545 }
546
547 /* XXX todo: encrypt sensitive data with passphrase */
548 static void
549 process_lock_agent(SocketEntry *e, int lock)
550 {
551         int success = 0;
552         char *passwd;
553
554         passwd = buffer_get_string(&e->request, NULL);
555         if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
556                 locked = 0;
557                 explicit_bzero(lock_passwd, strlen(lock_passwd));
558                 free(lock_passwd);
559                 lock_passwd = NULL;
560                 success = 1;
561         } else if (!locked && lock) {
562                 locked = 1;
563                 lock_passwd = xstrdup(passwd);
564                 success = 1;
565         }
566         explicit_bzero(passwd, strlen(passwd));
567         free(passwd);
568
569         buffer_put_int(&e->output, 1);
570         buffer_put_char(&e->output,
571             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
572 }
573
574 static void
575 no_identities(SocketEntry *e, u_int type)
576 {
577         Buffer msg;
578
579         buffer_init(&msg);
580         buffer_put_char(&msg,
581             (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
582             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
583         buffer_put_int(&msg, 0);
584         buffer_put_int(&e->output, buffer_len(&msg));
585         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
586         buffer_free(&msg);
587 }
588
589 #ifdef ENABLE_PKCS11
590 static void
591 process_add_smartcard_key(SocketEntry *e)
592 {
593         char *provider = NULL, *pin;
594         int i, type, version, count = 0, success = 0, confirm = 0;
595         time_t death = 0;
596         Key **keys = NULL, *k;
597         Identity *id;
598         Idtab *tab;
599
600         provider = buffer_get_string(&e->request, NULL);
601         pin = buffer_get_string(&e->request, NULL);
602
603         while (buffer_len(&e->request)) {
604                 switch ((type = buffer_get_char(&e->request))) {
605                 case SSH_AGENT_CONSTRAIN_LIFETIME:
606                         death = monotime() + buffer_get_int(&e->request);
607                         break;
608                 case SSH_AGENT_CONSTRAIN_CONFIRM:
609                         confirm = 1;
610                         break;
611                 default:
612                         error("process_add_smartcard_key: "
613                             "Unknown constraint type %d", type);
614                         goto send;
615                 }
616         }
617         if (lifetime && !death)
618                 death = monotime() + lifetime;
619
620         count = pkcs11_add_provider(provider, pin, &keys);
621         for (i = 0; i < count; i++) {
622                 k = keys[i];
623                 version = k->type == KEY_RSA1 ? 1 : 2;
624                 tab = idtab_lookup(version);
625                 if (lookup_identity(k, version) == NULL) {
626                         id = xcalloc(1, sizeof(Identity));
627                         id->key = k;
628                         id->provider = xstrdup(provider);
629                         id->comment = xstrdup(provider); /* XXX */
630                         id->death = death;
631                         id->confirm = confirm;
632                         TAILQ_INSERT_TAIL(&tab->idlist, id, next);
633                         tab->nentries++;
634                         success = 1;
635                 } else {
636                         key_free(k);
637                 }
638                 keys[i] = NULL;
639         }
640 send:
641         free(pin);
642         free(provider);
643         free(keys);
644         buffer_put_int(&e->output, 1);
645         buffer_put_char(&e->output,
646             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
647 }
648
649 static void
650 process_remove_smartcard_key(SocketEntry *e)
651 {
652         char *provider = NULL, *pin = NULL;
653         int version, success = 0;
654         Identity *id, *nxt;
655         Idtab *tab;
656
657         provider = buffer_get_string(&e->request, NULL);
658         pin = buffer_get_string(&e->request, NULL);
659         free(pin);
660
661         for (version = 1; version < 3; version++) {
662                 tab = idtab_lookup(version);
663                 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
664                         nxt = TAILQ_NEXT(id, next);
665                         /* Skip file--based keys */
666                         if (id->provider == NULL)
667                                 continue;
668                         if (!strcmp(provider, id->provider)) {
669                                 TAILQ_REMOVE(&tab->idlist, id, next);
670                                 free_identity(id);
671                                 tab->nentries--;
672                         }
673                 }
674         }
675         if (pkcs11_del_provider(provider) == 0)
676                 success = 1;
677         else
678                 error("process_remove_smartcard_key:"
679                     " pkcs11_del_provider failed");
680         free(provider);
681         buffer_put_int(&e->output, 1);
682         buffer_put_char(&e->output,
683             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
684 }
685 #endif /* ENABLE_PKCS11 */
686
687 /* dispatch incoming messages */
688
689 static void
690 process_message(SocketEntry *e)
691 {
692         u_int msg_len, type;
693         u_char *cp;
694
695         if (buffer_len(&e->input) < 5)
696                 return;         /* Incomplete message. */
697         cp = buffer_ptr(&e->input);
698         msg_len = get_u32(cp);
699         if (msg_len > 256 * 1024) {
700                 close_socket(e);
701                 return;
702         }
703         if (buffer_len(&e->input) < msg_len + 4)
704                 return;
705
706         /* move the current input to e->request */
707         buffer_consume(&e->input, 4);
708         buffer_clear(&e->request);
709         buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
710         buffer_consume(&e->input, msg_len);
711         type = buffer_get_char(&e->request);
712
713         /* check wheter agent is locked */
714         if (locked && type != SSH_AGENTC_UNLOCK) {
715                 buffer_clear(&e->request);
716                 switch (type) {
717                 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
718                 case SSH2_AGENTC_REQUEST_IDENTITIES:
719                         /* send empty lists */
720                         no_identities(e, type);
721                         break;
722                 default:
723                         /* send a fail message for all other request types */
724                         buffer_put_int(&e->output, 1);
725                         buffer_put_char(&e->output, SSH_AGENT_FAILURE);
726                 }
727                 return;
728         }
729
730         debug("type %d", type);
731         switch (type) {
732         case SSH_AGENTC_LOCK:
733         case SSH_AGENTC_UNLOCK:
734                 process_lock_agent(e, type == SSH_AGENTC_LOCK);
735                 break;
736         /* ssh1 */
737         case SSH_AGENTC_RSA_CHALLENGE:
738                 process_authentication_challenge1(e);
739                 break;
740         case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
741                 process_request_identities(e, 1);
742                 break;
743         case SSH_AGENTC_ADD_RSA_IDENTITY:
744         case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
745                 process_add_identity(e, 1);
746                 break;
747         case SSH_AGENTC_REMOVE_RSA_IDENTITY:
748                 process_remove_identity(e, 1);
749                 break;
750         case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
751                 process_remove_all_identities(e, 1);
752                 break;
753         /* ssh2 */
754         case SSH2_AGENTC_SIGN_REQUEST:
755                 process_sign_request2(e);
756                 break;
757         case SSH2_AGENTC_REQUEST_IDENTITIES:
758                 process_request_identities(e, 2);
759                 break;
760         case SSH2_AGENTC_ADD_IDENTITY:
761         case SSH2_AGENTC_ADD_ID_CONSTRAINED:
762                 process_add_identity(e, 2);
763                 break;
764         case SSH2_AGENTC_REMOVE_IDENTITY:
765                 process_remove_identity(e, 2);
766                 break;
767         case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
768                 process_remove_all_identities(e, 2);
769                 break;
770 #ifdef ENABLE_PKCS11
771         case SSH_AGENTC_ADD_SMARTCARD_KEY:
772         case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
773                 process_add_smartcard_key(e);
774                 break;
775         case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
776                 process_remove_smartcard_key(e);
777                 break;
778 #endif /* ENABLE_PKCS11 */
779         default:
780                 /* Unknown message.  Respond with failure. */
781                 error("Unknown message %d", type);
782                 buffer_clear(&e->request);
783                 buffer_put_int(&e->output, 1);
784                 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
785                 break;
786         }
787 }
788
789 static void
790 new_socket(sock_type type, int fd)
791 {
792         u_int i, old_alloc, new_alloc;
793
794         set_nonblock(fd);
795
796         if (fd > max_fd)
797                 max_fd = fd;
798
799         for (i = 0; i < sockets_alloc; i++)
800                 if (sockets[i].type == AUTH_UNUSED) {
801                         sockets[i].fd = fd;
802                         buffer_init(&sockets[i].input);
803                         buffer_init(&sockets[i].output);
804                         buffer_init(&sockets[i].request);
805                         sockets[i].type = type;
806                         return;
807                 }
808         old_alloc = sockets_alloc;
809         new_alloc = sockets_alloc + 10;
810         sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
811         for (i = old_alloc; i < new_alloc; i++)
812                 sockets[i].type = AUTH_UNUSED;
813         sockets_alloc = new_alloc;
814         sockets[old_alloc].fd = fd;
815         buffer_init(&sockets[old_alloc].input);
816         buffer_init(&sockets[old_alloc].output);
817         buffer_init(&sockets[old_alloc].request);
818         sockets[old_alloc].type = type;
819 }
820
821 static int
822 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
823     struct timeval **tvpp)
824 {
825         u_int i, sz;
826         int n = 0;
827         static struct timeval tv;
828         time_t deadline;
829
830         for (i = 0; i < sockets_alloc; i++) {
831                 switch (sockets[i].type) {
832                 case AUTH_SOCKET:
833                 case AUTH_CONNECTION:
834                         n = MAX(n, sockets[i].fd);
835                         break;
836                 case AUTH_UNUSED:
837                         break;
838                 default:
839                         fatal("Unknown socket type %d", sockets[i].type);
840                         break;
841                 }
842         }
843
844         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
845         if (*fdrp == NULL || sz > *nallocp) {
846                 free(*fdrp);
847                 free(*fdwp);
848                 *fdrp = xmalloc(sz);
849                 *fdwp = xmalloc(sz);
850                 *nallocp = sz;
851         }
852         if (n < *fdl)
853                 debug("XXX shrink: %d < %d", n, *fdl);
854         *fdl = n;
855         memset(*fdrp, 0, sz);
856         memset(*fdwp, 0, sz);
857
858         for (i = 0; i < sockets_alloc; i++) {
859                 switch (sockets[i].type) {
860                 case AUTH_SOCKET:
861                 case AUTH_CONNECTION:
862                         FD_SET(sockets[i].fd, *fdrp);
863                         if (buffer_len(&sockets[i].output) > 0)
864                                 FD_SET(sockets[i].fd, *fdwp);
865                         break;
866                 default:
867                         break;
868                 }
869         }
870         deadline = reaper();
871         if (parent_alive_interval != 0)
872                 deadline = (deadline == 0) ? parent_alive_interval :
873                     MIN(deadline, parent_alive_interval);
874         if (deadline == 0) {
875                 *tvpp = NULL;
876         } else {
877                 tv.tv_sec = deadline;
878                 tv.tv_usec = 0;
879                 *tvpp = &tv;
880         }
881         return (1);
882 }
883
884 static void
885 after_select(fd_set *readset, fd_set *writeset)
886 {
887         struct sockaddr_un sunaddr;
888         socklen_t slen;
889         char buf[1024];
890         int len, sock;
891         u_int i, orig_alloc;
892         uid_t euid;
893         gid_t egid;
894
895         for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
896                 switch (sockets[i].type) {
897                 case AUTH_UNUSED:
898                         break;
899                 case AUTH_SOCKET:
900                         if (FD_ISSET(sockets[i].fd, readset)) {
901                                 slen = sizeof(sunaddr);
902                                 sock = accept(sockets[i].fd,
903                                     (struct sockaddr *)&sunaddr, &slen);
904                                 if (sock < 0) {
905                                         error("accept from AUTH_SOCKET: %s",
906                                             strerror(errno));
907                                         break;
908                                 }
909                                 if (getpeereid(sock, &euid, &egid) < 0) {
910                                         error("getpeereid %d failed: %s",
911                                             sock, strerror(errno));
912                                         close(sock);
913                                         break;
914                                 }
915                                 if ((euid != 0) && (getuid() != euid)) {
916                                         error("uid mismatch: "
917                                             "peer euid %u != uid %u",
918                                             (u_int) euid, (u_int) getuid());
919                                         close(sock);
920                                         break;
921                                 }
922                                 new_socket(AUTH_CONNECTION, sock);
923                         }
924                         break;
925                 case AUTH_CONNECTION:
926                         if (buffer_len(&sockets[i].output) > 0 &&
927                             FD_ISSET(sockets[i].fd, writeset)) {
928                                 len = write(sockets[i].fd,
929                                     buffer_ptr(&sockets[i].output),
930                                     buffer_len(&sockets[i].output));
931                                 if (len == -1 && (errno == EAGAIN ||
932                                     errno == EWOULDBLOCK ||
933                                     errno == EINTR))
934                                         continue;
935                                 if (len <= 0) {
936                                         close_socket(&sockets[i]);
937                                         break;
938                                 }
939                                 buffer_consume(&sockets[i].output, len);
940                         }
941                         if (FD_ISSET(sockets[i].fd, readset)) {
942                                 len = read(sockets[i].fd, buf, sizeof(buf));
943                                 if (len == -1 && (errno == EAGAIN ||
944                                     errno == EWOULDBLOCK ||
945                                     errno == EINTR))
946                                         continue;
947                                 if (len <= 0) {
948                                         close_socket(&sockets[i]);
949                                         break;
950                                 }
951                                 buffer_append(&sockets[i].input, buf, len);
952                                 process_message(&sockets[i]);
953                         }
954                         break;
955                 default:
956                         fatal("Unknown type %d", sockets[i].type);
957                 }
958 }
959
960 static void
961 cleanup_socket(void)
962 {
963         if (socket_name[0])
964                 unlink(socket_name);
965         if (socket_dir[0])
966                 rmdir(socket_dir);
967 }
968
969 void
970 cleanup_exit(int i)
971 {
972         cleanup_socket();
973         _exit(i);
974 }
975
976 /*ARGSUSED*/
977 static void
978 cleanup_handler(int sig)
979 {
980         cleanup_socket();
981 #ifdef ENABLE_PKCS11
982         pkcs11_terminate();
983 #endif
984         _exit(2);
985 }
986
987 static void
988 check_parent_exists(void)
989 {
990         /*
991          * If our parent has exited then getppid() will return (pid_t)1,
992          * so testing for that should be safe.
993          */
994         if (parent_pid != -1 && getppid() != parent_pid) {
995                 /* printf("Parent has died - Authentication agent exiting.\n"); */
996                 cleanup_socket();
997                 _exit(2);
998         }
999 }
1000
1001 static void
1002 usage(void)
1003 {
1004         fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1005             __progname);
1006         fprintf(stderr, "Options:\n");
1007         fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
1008         fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
1009         fprintf(stderr, "  -k          Kill the current agent.\n");
1010         fprintf(stderr, "  -d          Debug mode.\n");
1011         fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
1012         fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
1013         exit(1);
1014 }
1015
1016 int
1017 main(int ac, char **av)
1018 {
1019         int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1020         int sock, fd, ch, result, saved_errno;
1021         u_int nalloc;
1022         char *shell, *format, *pidstr, *agentsocket = NULL;
1023         fd_set *readsetp = NULL, *writesetp = NULL;
1024         struct sockaddr_un sunaddr;
1025 #ifdef HAVE_SETRLIMIT
1026         struct rlimit rlim;
1027 #endif
1028         int prev_mask;
1029         extern int optind;
1030         extern char *optarg;
1031         pid_t pid;
1032         char pidstrbuf[1 + 3 * sizeof pid];
1033         struct timeval *tvp = NULL;
1034         size_t len;
1035
1036         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1037         sanitise_stdfd();
1038
1039         /* drop */
1040         setegid(getgid());
1041         setgid(getgid());
1042
1043 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1044         /* Disable ptrace on Linux without sgid bit */
1045         prctl(PR_SET_DUMPABLE, 0);
1046 #endif
1047
1048         OpenSSL_add_all_algorithms();
1049
1050         __progname = ssh_get_progname(av[0]);
1051         seed_rng();
1052
1053         while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1054                 switch (ch) {
1055                 case 'c':
1056                         if (s_flag)
1057                                 usage();
1058                         c_flag++;
1059                         break;
1060                 case 'k':
1061                         k_flag++;
1062                         break;
1063                 case 's':
1064                         if (c_flag)
1065                                 usage();
1066                         s_flag++;
1067                         break;
1068                 case 'd':
1069                         if (d_flag)
1070                                 usage();
1071                         d_flag++;
1072                         break;
1073                 case 'a':
1074                         agentsocket = optarg;
1075                         break;
1076                 case 't':
1077                         if ((lifetime = convtime(optarg)) == -1) {
1078                                 fprintf(stderr, "Invalid lifetime\n");
1079                                 usage();
1080                         }
1081                         break;
1082                 default:
1083                         usage();
1084                 }
1085         }
1086         ac -= optind;
1087         av += optind;
1088
1089         if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1090                 usage();
1091
1092         if (ac == 0 && !c_flag && !s_flag) {
1093                 shell = getenv("SHELL");
1094                 if (shell != NULL && (len = strlen(shell)) > 2 &&
1095                     strncmp(shell + len - 3, "csh", 3) == 0)
1096                         c_flag = 1;
1097         }
1098         if (k_flag) {
1099                 const char *errstr = NULL;
1100
1101                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1102                 if (pidstr == NULL) {
1103                         fprintf(stderr, "%s not set, cannot kill agent\n",
1104                             SSH_AGENTPID_ENV_NAME);
1105                         exit(1);
1106                 }
1107                 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1108                 if (errstr) {
1109                         fprintf(stderr,
1110                             "%s=\"%s\", which is not a good PID: %s\n",
1111                             SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1112                         exit(1);
1113                 }
1114                 if (kill(pid, SIGTERM) == -1) {
1115                         perror("kill");
1116                         exit(1);
1117                 }
1118                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1119                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1120                 printf(format, SSH_AGENTPID_ENV_NAME);
1121                 printf("echo Agent pid %ld killed;\n", (long)pid);
1122                 exit(0);
1123         }
1124         parent_pid = getpid();
1125
1126         if (agentsocket == NULL) {
1127                 /* Create private directory for agent socket */
1128                 mktemp_proto(socket_dir, sizeof(socket_dir));
1129                 if (mkdtemp(socket_dir) == NULL) {
1130                         perror("mkdtemp: private socket dir");
1131                         exit(1);
1132                 }
1133                 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1134                     (long)parent_pid);
1135         } else {
1136                 /* Try to use specified agent socket */
1137                 socket_dir[0] = '\0';
1138                 strlcpy(socket_name, agentsocket, sizeof socket_name);
1139         }
1140
1141         /*
1142          * Create socket early so it will exist before command gets run from
1143          * the parent.
1144          */
1145         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1146         if (sock < 0) {
1147                 perror("socket");
1148                 *socket_name = '\0'; /* Don't unlink any existing file */
1149                 cleanup_exit(1);
1150         }
1151         memset(&sunaddr, 0, sizeof(sunaddr));
1152         sunaddr.sun_family = AF_UNIX;
1153         strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1154         prev_mask = umask(0177);
1155         if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1156                 perror("bind");
1157                 *socket_name = '\0'; /* Don't unlink any existing file */
1158                 umask(prev_mask);
1159                 cleanup_exit(1);
1160         }
1161         umask(prev_mask);
1162         if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1163                 perror("listen");
1164                 cleanup_exit(1);
1165         }
1166
1167         /*
1168          * Fork, and have the parent execute the command, if any, or present
1169          * the socket data.  The child continues as the authentication agent.
1170          */
1171         if (d_flag) {
1172                 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1173                 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1174                 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1175                     SSH_AUTHSOCKET_ENV_NAME);
1176                 printf("echo Agent pid %ld;\n", (long)parent_pid);
1177                 goto skip;
1178         }
1179         pid = fork();
1180         if (pid == -1) {
1181                 perror("fork");
1182                 cleanup_exit(1);
1183         }
1184         if (pid != 0) {         /* Parent - execute the given command. */
1185                 close(sock);
1186                 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1187                 if (ac == 0) {
1188                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1189                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1190                             SSH_AUTHSOCKET_ENV_NAME);
1191                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1192                             SSH_AGENTPID_ENV_NAME);
1193                         printf("echo Agent pid %ld;\n", (long)pid);
1194                         exit(0);
1195                 }
1196                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1197                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1198                         perror("setenv");
1199                         exit(1);
1200                 }
1201                 execvp(av[0], av);
1202                 perror(av[0]);
1203                 exit(1);
1204         }
1205         /* child */
1206         log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1207
1208         if (setsid() == -1) {
1209                 error("setsid: %s", strerror(errno));
1210                 cleanup_exit(1);
1211         }
1212
1213         (void)chdir("/");
1214         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1215                 /* XXX might close listen socket */
1216                 (void)dup2(fd, STDIN_FILENO);
1217                 (void)dup2(fd, STDOUT_FILENO);
1218                 (void)dup2(fd, STDERR_FILENO);
1219                 if (fd > 2)
1220                         close(fd);
1221         }
1222
1223 #ifdef HAVE_SETRLIMIT
1224         /* deny core dumps, since memory contains unencrypted private keys */
1225         rlim.rlim_cur = rlim.rlim_max = 0;
1226         if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1227                 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1228                 cleanup_exit(1);
1229         }
1230 #endif
1231
1232 skip:
1233
1234 #ifdef ENABLE_PKCS11
1235         pkcs11_init(0);
1236 #endif
1237         new_socket(AUTH_SOCKET, sock);
1238         if (ac > 0)
1239                 parent_alive_interval = 10;
1240         idtab_init();
1241         signal(SIGPIPE, SIG_IGN);
1242         signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
1243         signal(SIGHUP, cleanup_handler);
1244         signal(SIGTERM, cleanup_handler);
1245         nalloc = 0;
1246
1247         while (1) {
1248                 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1249                 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1250                 saved_errno = errno;
1251                 if (parent_alive_interval != 0)
1252                         check_parent_exists();
1253                 (void) reaper();        /* remove expired keys */
1254                 if (result < 0) {
1255                         if (saved_errno == EINTR)
1256                                 continue;
1257                         fatal("select: %s", strerror(saved_errno));
1258                 } else if (result > 0)
1259                         after_select(readsetp, writesetp);
1260         }
1261         /* NOTREACHED */
1262 }