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