]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - ssh-agent.c
Vendor import of OpenSSH 5.4p1
[FreeBSD/FreeBSD.git] / ssh-agent.c
1 /* $OpenBSD: ssh-agent.c,v 1.165 2010/02/26 20:29:54 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         u_int 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 u_int 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 (0 == forever) */
138 static int 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         if (id->provider != NULL)
176                 xfree(id->provider);
177         xfree(id->comment);
178         xfree(id);
179 }
180
181 /* return matching private key for given public key */
182 static Identity *
183 lookup_identity(Key *key, int version)
184 {
185         Identity *id;
186
187         Idtab *tab = idtab_lookup(version);
188         TAILQ_FOREACH(id, &tab->idlist, next) {
189                 if (key_equal(key, id->key))
190                         return (id);
191         }
192         return (NULL);
193 }
194
195 /* Check confirmation of keysign request */
196 static int
197 confirm_key(Identity *id)
198 {
199         char *p;
200         int ret = -1;
201
202         p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
203         if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
204             id->comment, p))
205                 ret = 0;
206         xfree(p);
207
208         return (ret);
209 }
210
211 /* send list of supported public keys to 'client' */
212 static void
213 process_request_identities(SocketEntry *e, int version)
214 {
215         Idtab *tab = idtab_lookup(version);
216         Identity *id;
217         Buffer msg;
218
219         buffer_init(&msg);
220         buffer_put_char(&msg, (version == 1) ?
221             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
222         buffer_put_int(&msg, tab->nentries);
223         TAILQ_FOREACH(id, &tab->idlist, next) {
224                 if (id->key->type == KEY_RSA1) {
225                         buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
226                         buffer_put_bignum(&msg, id->key->rsa->e);
227                         buffer_put_bignum(&msg, id->key->rsa->n);
228                 } else {
229                         u_char *blob;
230                         u_int blen;
231                         key_to_blob(id->key, &blob, &blen);
232                         buffer_put_string(&msg, blob, blen);
233                         xfree(blob);
234                 }
235                 buffer_put_cstring(&msg, id->comment);
236         }
237         buffer_put_int(&e->output, buffer_len(&msg));
238         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
239         buffer_free(&msg);
240 }
241
242 /* ssh1 only */
243 static void
244 process_authentication_challenge1(SocketEntry *e)
245 {
246         u_char buf[32], mdbuf[16], session_id[16];
247         u_int response_type;
248         BIGNUM *challenge;
249         Identity *id;
250         int i, len;
251         Buffer msg;
252         MD5_CTX md;
253         Key *key;
254
255         buffer_init(&msg);
256         key = key_new(KEY_RSA1);
257         if ((challenge = BN_new()) == NULL)
258                 fatal("process_authentication_challenge1: BN_new failed");
259
260         (void) buffer_get_int(&e->request);                     /* ignored */
261         buffer_get_bignum(&e->request, key->rsa->e);
262         buffer_get_bignum(&e->request, key->rsa->n);
263         buffer_get_bignum(&e->request, challenge);
264
265         /* Only protocol 1.1 is supported */
266         if (buffer_len(&e->request) == 0)
267                 goto failure;
268         buffer_get(&e->request, session_id, 16);
269         response_type = buffer_get_int(&e->request);
270         if (response_type != 1)
271                 goto failure;
272
273         id = lookup_identity(key, 1);
274         if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
275                 Key *private = id->key;
276                 /* Decrypt the challenge using the private key. */
277                 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
278                         goto failure;
279
280                 /* The response is MD5 of decrypted challenge plus session id. */
281                 len = BN_num_bytes(challenge);
282                 if (len <= 0 || len > 32) {
283                         logit("process_authentication_challenge: bad challenge length %d", len);
284                         goto failure;
285                 }
286                 memset(buf, 0, 32);
287                 BN_bn2bin(challenge, buf + 32 - len);
288                 MD5_Init(&md);
289                 MD5_Update(&md, buf, 32);
290                 MD5_Update(&md, session_id, 16);
291                 MD5_Final(mdbuf, &md);
292
293                 /* Send the response. */
294                 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
295                 for (i = 0; i < 16; i++)
296                         buffer_put_char(&msg, mdbuf[i]);
297                 goto send;
298         }
299
300 failure:
301         /* Unknown identity or protocol error.  Send failure. */
302         buffer_put_char(&msg, SSH_AGENT_FAILURE);
303 send:
304         buffer_put_int(&e->output, buffer_len(&msg));
305         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
306         key_free(key);
307         BN_clear_free(challenge);
308         buffer_free(&msg);
309 }
310
311 /* ssh2 only */
312 static void
313 process_sign_request2(SocketEntry *e)
314 {
315         u_char *blob, *data, *signature = NULL;
316         u_int blen, dlen, slen = 0;
317         extern int datafellows;
318         int odatafellows;
319         int ok = -1, flags;
320         Buffer msg;
321         Key *key;
322
323         datafellows = 0;
324
325         blob = buffer_get_string(&e->request, &blen);
326         data = buffer_get_string(&e->request, &dlen);
327
328         flags = buffer_get_int(&e->request);
329         odatafellows = datafellows;
330         if (flags & SSH_AGENT_OLD_SIGNATURE)
331                 datafellows = SSH_BUG_SIGBLOB;
332
333         key = key_from_blob(blob, blen);
334         if (key != NULL) {
335                 Identity *id = lookup_identity(key, 2);
336                 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
337                         ok = key_sign(id->key, &signature, &slen, data, dlen);
338                 key_free(key);
339         }
340         buffer_init(&msg);
341         if (ok == 0) {
342                 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
343                 buffer_put_string(&msg, signature, slen);
344         } else {
345                 buffer_put_char(&msg, SSH_AGENT_FAILURE);
346         }
347         buffer_put_int(&e->output, buffer_len(&msg));
348         buffer_append(&e->output, buffer_ptr(&msg),
349             buffer_len(&msg));
350         buffer_free(&msg);
351         xfree(data);
352         xfree(blob);
353         if (signature != NULL)
354                 xfree(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                 xfree(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 u_int
434 reaper(void)
435 {
436         u_int deadline = 0, now = time(NULL);
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, death = 0, confirm = 0;
469         char *type_name, *comment;
470         Key *k = NULL;
471         u_char *cert;
472         u_int len;
473
474         switch (version) {
475         case 1:
476                 k = key_new_private(KEY_RSA1);
477                 (void) buffer_get_int(&e->request);             /* ignored */
478                 buffer_get_bignum(&e->request, k->rsa->n);
479                 buffer_get_bignum(&e->request, k->rsa->e);
480                 buffer_get_bignum(&e->request, k->rsa->d);
481                 buffer_get_bignum(&e->request, k->rsa->iqmp);
482
483                 /* SSH and SSL have p and q swapped */
484                 buffer_get_bignum(&e->request, k->rsa->q);      /* p */
485                 buffer_get_bignum(&e->request, k->rsa->p);      /* q */
486
487                 /* Generate additional parameters */
488                 rsa_generate_additional_parameters(k->rsa);
489                 break;
490         case 2:
491                 type_name = buffer_get_string(&e->request, NULL);
492                 type = key_type_from_name(type_name);
493                 xfree(type_name);
494                 switch (type) {
495                 case KEY_DSA:
496                         k = key_new_private(type);
497                         buffer_get_bignum2(&e->request, k->dsa->p);
498                         buffer_get_bignum2(&e->request, k->dsa->q);
499                         buffer_get_bignum2(&e->request, k->dsa->g);
500                         buffer_get_bignum2(&e->request, k->dsa->pub_key);
501                         buffer_get_bignum2(&e->request, k->dsa->priv_key);
502                         break;
503                 case KEY_DSA_CERT:
504                         cert = buffer_get_string(&e->request, &len);
505                         if ((k = key_from_blob(cert, len)) == NULL)
506                                 fatal("Certificate parse failed");
507                         xfree(cert);
508                         key_add_private(k);
509                         buffer_get_bignum2(&e->request, k->dsa->priv_key);
510                         break;
511                 case KEY_RSA:
512                         k = key_new_private(type);
513                         buffer_get_bignum2(&e->request, k->rsa->n);
514                         buffer_get_bignum2(&e->request, k->rsa->e);
515                         buffer_get_bignum2(&e->request, k->rsa->d);
516                         buffer_get_bignum2(&e->request, k->rsa->iqmp);
517                         buffer_get_bignum2(&e->request, k->rsa->p);
518                         buffer_get_bignum2(&e->request, k->rsa->q);
519
520                         /* Generate additional parameters */
521                         rsa_generate_additional_parameters(k->rsa);
522                         break;
523                 case KEY_RSA_CERT:
524                         cert = buffer_get_string(&e->request, &len);
525                         if ((k = key_from_blob(cert, len)) == NULL)
526                                 fatal("Certificate parse failed");
527                         xfree(cert);
528                         key_add_private(k);
529                         buffer_get_bignum2(&e->request, k->rsa->d);
530                         buffer_get_bignum2(&e->request, k->rsa->iqmp);
531                         buffer_get_bignum2(&e->request, k->rsa->p);
532                         buffer_get_bignum2(&e->request, k->rsa->q);
533                         break;
534                 default:
535                         buffer_clear(&e->request);
536                         goto send;
537                 }
538                 break;
539         }
540         /* enable blinding */
541         switch (k->type) {
542         case KEY_RSA:
543         case KEY_RSA_CERT:
544         case KEY_RSA1:
545                 if (RSA_blinding_on(k->rsa, NULL) != 1) {
546                         error("process_add_identity: RSA_blinding_on failed");
547                         key_free(k);
548                         goto send;
549                 }
550                 break;
551         }
552         comment = buffer_get_string(&e->request, NULL);
553         if (k == NULL) {
554                 xfree(comment);
555                 goto send;
556         }
557         while (buffer_len(&e->request)) {
558                 switch ((type = buffer_get_char(&e->request))) {
559                 case SSH_AGENT_CONSTRAIN_LIFETIME:
560                         death = time(NULL) + buffer_get_int(&e->request);
561                         break;
562                 case SSH_AGENT_CONSTRAIN_CONFIRM:
563                         confirm = 1;
564                         break;
565                 default:
566                         error("process_add_identity: "
567                             "Unknown constraint type %d", type);
568                         xfree(comment);
569                         key_free(k);
570                         goto send;
571                 }
572         }
573         success = 1;
574         if (lifetime && !death)
575                 death = time(NULL) + lifetime;
576         if ((id = lookup_identity(k, version)) == NULL) {
577                 id = xcalloc(1, sizeof(Identity));
578                 id->key = k;
579                 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
580                 /* Increment the number of identities. */
581                 tab->nentries++;
582         } else {
583                 key_free(k);
584                 xfree(id->comment);
585         }
586         id->comment = comment;
587         id->death = death;
588         id->confirm = confirm;
589 send:
590         buffer_put_int(&e->output, 1);
591         buffer_put_char(&e->output,
592             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
593 }
594
595 /* XXX todo: encrypt sensitive data with passphrase */
596 static void
597 process_lock_agent(SocketEntry *e, int lock)
598 {
599         int success = 0;
600         char *passwd;
601
602         passwd = buffer_get_string(&e->request, NULL);
603         if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
604                 locked = 0;
605                 memset(lock_passwd, 0, strlen(lock_passwd));
606                 xfree(lock_passwd);
607                 lock_passwd = NULL;
608                 success = 1;
609         } else if (!locked && lock) {
610                 locked = 1;
611                 lock_passwd = xstrdup(passwd);
612                 success = 1;
613         }
614         memset(passwd, 0, strlen(passwd));
615         xfree(passwd);
616
617         buffer_put_int(&e->output, 1);
618         buffer_put_char(&e->output,
619             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
620 }
621
622 static void
623 no_identities(SocketEntry *e, u_int type)
624 {
625         Buffer msg;
626
627         buffer_init(&msg);
628         buffer_put_char(&msg,
629             (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
630             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
631         buffer_put_int(&msg, 0);
632         buffer_put_int(&e->output, buffer_len(&msg));
633         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
634         buffer_free(&msg);
635 }
636
637 #ifdef ENABLE_PKCS11
638 static void
639 process_add_smartcard_key(SocketEntry *e)
640 {
641         char *provider = NULL, *pin;
642         int i, type, version, count = 0, success = 0, death = 0, confirm = 0;
643         Key **keys = NULL, *k;
644         Identity *id;
645         Idtab *tab;
646
647         provider = buffer_get_string(&e->request, NULL);
648         pin = buffer_get_string(&e->request, NULL);
649
650         while (buffer_len(&e->request)) {
651                 switch ((type = buffer_get_char(&e->request))) {
652                 case SSH_AGENT_CONSTRAIN_LIFETIME:
653                         death = time(NULL) + buffer_get_int(&e->request);
654                         break;
655                 case SSH_AGENT_CONSTRAIN_CONFIRM:
656                         confirm = 1;
657                         break;
658                 default:
659                         error("process_add_smartcard_key: "
660                             "Unknown constraint type %d", type);
661                         goto send;
662                 }
663         }
664         if (lifetime && !death)
665                 death = time(NULL) + lifetime;
666
667         count = pkcs11_add_provider(provider, pin, &keys);
668         for (i = 0; i < count; i++) {
669                 k = keys[i];
670                 version = k->type == KEY_RSA1 ? 1 : 2;
671                 tab = idtab_lookup(version);
672                 if (lookup_identity(k, version) == NULL) {
673                         id = xcalloc(1, sizeof(Identity));
674                         id->key = k;
675                         id->provider = xstrdup(provider);
676                         id->comment = xstrdup(provider); /* XXX */
677                         id->death = death;
678                         id->confirm = confirm;
679                         TAILQ_INSERT_TAIL(&tab->idlist, id, next);
680                         tab->nentries++;
681                         success = 1;
682                 } else {
683                         key_free(k);
684                 }
685                 keys[i] = NULL;
686         }
687 send:
688         if (pin)
689                 xfree(pin);
690         if (provider)
691                 xfree(provider);
692         if (keys)
693                 xfree(keys);
694         buffer_put_int(&e->output, 1);
695         buffer_put_char(&e->output,
696             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
697 }
698
699 static void
700 process_remove_smartcard_key(SocketEntry *e)
701 {
702         char *provider = NULL, *pin = NULL;
703         int version, success = 0;
704         Identity *id, *nxt;
705         Idtab *tab;
706
707         provider = buffer_get_string(&e->request, NULL);
708         pin = buffer_get_string(&e->request, NULL);
709         xfree(pin);
710
711         for (version = 1; version < 3; version++) {
712                 tab = idtab_lookup(version);
713                 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
714                         nxt = TAILQ_NEXT(id, next);
715                         if (!strcmp(provider, id->provider)) {
716                                 TAILQ_REMOVE(&tab->idlist, id, next);
717                                 free_identity(id);
718                                 tab->nentries--;
719                         }
720                 }
721         }
722         if (pkcs11_del_provider(provider) == 0)
723                 success = 1;
724         else
725                 error("process_remove_smartcard_key:"
726                     " pkcs11_del_provider failed");
727         xfree(provider);
728         buffer_put_int(&e->output, 1);
729         buffer_put_char(&e->output,
730             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
731 }
732 #endif /* ENABLE_PKCS11 */
733
734 /* dispatch incoming messages */
735
736 static void
737 process_message(SocketEntry *e)
738 {
739         u_int msg_len, type;
740         u_char *cp;
741
742         if (buffer_len(&e->input) < 5)
743                 return;         /* Incomplete message. */
744         cp = buffer_ptr(&e->input);
745         msg_len = get_u32(cp);
746         if (msg_len > 256 * 1024) {
747                 close_socket(e);
748                 return;
749         }
750         if (buffer_len(&e->input) < msg_len + 4)
751                 return;
752
753         /* move the current input to e->request */
754         buffer_consume(&e->input, 4);
755         buffer_clear(&e->request);
756         buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
757         buffer_consume(&e->input, msg_len);
758         type = buffer_get_char(&e->request);
759
760         /* check wheter agent is locked */
761         if (locked && type != SSH_AGENTC_UNLOCK) {
762                 buffer_clear(&e->request);
763                 switch (type) {
764                 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
765                 case SSH2_AGENTC_REQUEST_IDENTITIES:
766                         /* send empty lists */
767                         no_identities(e, type);
768                         break;
769                 default:
770                         /* send a fail message for all other request types */
771                         buffer_put_int(&e->output, 1);
772                         buffer_put_char(&e->output, SSH_AGENT_FAILURE);
773                 }
774                 return;
775         }
776
777         debug("type %d", type);
778         switch (type) {
779         case SSH_AGENTC_LOCK:
780         case SSH_AGENTC_UNLOCK:
781                 process_lock_agent(e, type == SSH_AGENTC_LOCK);
782                 break;
783         /* ssh1 */
784         case SSH_AGENTC_RSA_CHALLENGE:
785                 process_authentication_challenge1(e);
786                 break;
787         case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
788                 process_request_identities(e, 1);
789                 break;
790         case SSH_AGENTC_ADD_RSA_IDENTITY:
791         case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
792                 process_add_identity(e, 1);
793                 break;
794         case SSH_AGENTC_REMOVE_RSA_IDENTITY:
795                 process_remove_identity(e, 1);
796                 break;
797         case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
798                 process_remove_all_identities(e, 1);
799                 break;
800         /* ssh2 */
801         case SSH2_AGENTC_SIGN_REQUEST:
802                 process_sign_request2(e);
803                 break;
804         case SSH2_AGENTC_REQUEST_IDENTITIES:
805                 process_request_identities(e, 2);
806                 break;
807         case SSH2_AGENTC_ADD_IDENTITY:
808         case SSH2_AGENTC_ADD_ID_CONSTRAINED:
809                 process_add_identity(e, 2);
810                 break;
811         case SSH2_AGENTC_REMOVE_IDENTITY:
812                 process_remove_identity(e, 2);
813                 break;
814         case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
815                 process_remove_all_identities(e, 2);
816                 break;
817 #ifdef ENABLE_PKCS11
818         case SSH_AGENTC_ADD_SMARTCARD_KEY:
819         case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
820                 process_add_smartcard_key(e);
821                 break;
822         case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
823                 process_remove_smartcard_key(e);
824                 break;
825 #endif /* ENABLE_PKCS11 */
826         default:
827                 /* Unknown message.  Respond with failure. */
828                 error("Unknown message %d", type);
829                 buffer_clear(&e->request);
830                 buffer_put_int(&e->output, 1);
831                 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
832                 break;
833         }
834 }
835
836 static void
837 new_socket(sock_type type, int fd)
838 {
839         u_int i, old_alloc, new_alloc;
840
841         set_nonblock(fd);
842
843         if (fd > max_fd)
844                 max_fd = fd;
845
846         for (i = 0; i < sockets_alloc; i++)
847                 if (sockets[i].type == AUTH_UNUSED) {
848                         sockets[i].fd = fd;
849                         buffer_init(&sockets[i].input);
850                         buffer_init(&sockets[i].output);
851                         buffer_init(&sockets[i].request);
852                         sockets[i].type = type;
853                         return;
854                 }
855         old_alloc = sockets_alloc;
856         new_alloc = sockets_alloc + 10;
857         sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
858         for (i = old_alloc; i < new_alloc; i++)
859                 sockets[i].type = AUTH_UNUSED;
860         sockets_alloc = new_alloc;
861         sockets[old_alloc].fd = fd;
862         buffer_init(&sockets[old_alloc].input);
863         buffer_init(&sockets[old_alloc].output);
864         buffer_init(&sockets[old_alloc].request);
865         sockets[old_alloc].type = type;
866 }
867
868 static int
869 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
870     struct timeval **tvpp)
871 {
872         u_int i, sz, deadline;
873         int n = 0;
874         static struct timeval tv;
875
876         for (i = 0; i < sockets_alloc; i++) {
877                 switch (sockets[i].type) {
878                 case AUTH_SOCKET:
879                 case AUTH_CONNECTION:
880                         n = MAX(n, sockets[i].fd);
881                         break;
882                 case AUTH_UNUSED:
883                         break;
884                 default:
885                         fatal("Unknown socket type %d", sockets[i].type);
886                         break;
887                 }
888         }
889
890         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
891         if (*fdrp == NULL || sz > *nallocp) {
892                 if (*fdrp)
893                         xfree(*fdrp);
894                 if (*fdwp)
895                         xfree(*fdwp);
896                 *fdrp = xmalloc(sz);
897                 *fdwp = xmalloc(sz);
898                 *nallocp = sz;
899         }
900         if (n < *fdl)
901                 debug("XXX shrink: %d < %d", n, *fdl);
902         *fdl = n;
903         memset(*fdrp, 0, sz);
904         memset(*fdwp, 0, sz);
905
906         for (i = 0; i < sockets_alloc; i++) {
907                 switch (sockets[i].type) {
908                 case AUTH_SOCKET:
909                 case AUTH_CONNECTION:
910                         FD_SET(sockets[i].fd, *fdrp);
911                         if (buffer_len(&sockets[i].output) > 0)
912                                 FD_SET(sockets[i].fd, *fdwp);
913                         break;
914                 default:
915                         break;
916                 }
917         }
918         deadline = reaper();
919         if (parent_alive_interval != 0)
920                 deadline = (deadline == 0) ? parent_alive_interval :
921                     MIN(deadline, parent_alive_interval);
922         if (deadline == 0) {
923                 *tvpp = NULL;
924         } else {
925                 tv.tv_sec = deadline;
926                 tv.tv_usec = 0;
927                 *tvpp = &tv;
928         }
929         return (1);
930 }
931
932 static void
933 after_select(fd_set *readset, fd_set *writeset)
934 {
935         struct sockaddr_un sunaddr;
936         socklen_t slen;
937         char buf[1024];
938         int len, sock;
939         u_int i, orig_alloc;
940         uid_t euid;
941         gid_t egid;
942
943         for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
944                 switch (sockets[i].type) {
945                 case AUTH_UNUSED:
946                         break;
947                 case AUTH_SOCKET:
948                         if (FD_ISSET(sockets[i].fd, readset)) {
949                                 slen = sizeof(sunaddr);
950                                 sock = accept(sockets[i].fd,
951                                     (struct sockaddr *)&sunaddr, &slen);
952                                 if (sock < 0) {
953                                         error("accept from AUTH_SOCKET: %s",
954                                             strerror(errno));
955                                         break;
956                                 }
957                                 if (getpeereid(sock, &euid, &egid) < 0) {
958                                         error("getpeereid %d failed: %s",
959                                             sock, strerror(errno));
960                                         close(sock);
961                                         break;
962                                 }
963                                 if ((euid != 0) && (getuid() != euid)) {
964                                         error("uid mismatch: "
965                                             "peer euid %u != uid %u",
966                                             (u_int) euid, (u_int) getuid());
967                                         close(sock);
968                                         break;
969                                 }
970                                 new_socket(AUTH_CONNECTION, sock);
971                         }
972                         break;
973                 case AUTH_CONNECTION:
974                         if (buffer_len(&sockets[i].output) > 0 &&
975                             FD_ISSET(sockets[i].fd, writeset)) {
976                                 len = write(sockets[i].fd,
977                                     buffer_ptr(&sockets[i].output),
978                                     buffer_len(&sockets[i].output));
979                                 if (len == -1 && (errno == EAGAIN ||
980                                     errno == EWOULDBLOCK ||
981                                     errno == EINTR))
982                                         continue;
983                                 if (len <= 0) {
984                                         close_socket(&sockets[i]);
985                                         break;
986                                 }
987                                 buffer_consume(&sockets[i].output, len);
988                         }
989                         if (FD_ISSET(sockets[i].fd, readset)) {
990                                 len = read(sockets[i].fd, buf, sizeof(buf));
991                                 if (len == -1 && (errno == EAGAIN ||
992                                     errno == EWOULDBLOCK ||
993                                     errno == EINTR))
994                                         continue;
995                                 if (len <= 0) {
996                                         close_socket(&sockets[i]);
997                                         break;
998                                 }
999                                 buffer_append(&sockets[i].input, buf, len);
1000                                 process_message(&sockets[i]);
1001                         }
1002                         break;
1003                 default:
1004                         fatal("Unknown type %d", sockets[i].type);
1005                 }
1006 }
1007
1008 static void
1009 cleanup_socket(void)
1010 {
1011         if (socket_name[0])
1012                 unlink(socket_name);
1013         if (socket_dir[0])
1014                 rmdir(socket_dir);
1015 }
1016
1017 void
1018 cleanup_exit(int i)
1019 {
1020         cleanup_socket();
1021         _exit(i);
1022 }
1023
1024 /*ARGSUSED*/
1025 static void
1026 cleanup_handler(int sig)
1027 {
1028         cleanup_socket();
1029 #ifdef ENABLE_PKCS11
1030         pkcs11_terminate();
1031 #endif
1032         _exit(2);
1033 }
1034
1035 static void
1036 check_parent_exists(void)
1037 {
1038         if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
1039                 /* printf("Parent has died - Authentication agent exiting.\n"); */
1040                 cleanup_socket();
1041                 _exit(2);
1042         }
1043 }
1044
1045 static void
1046 usage(void)
1047 {
1048         fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
1049             __progname);
1050         fprintf(stderr, "Options:\n");
1051         fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
1052         fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
1053         fprintf(stderr, "  -k          Kill the current agent.\n");
1054         fprintf(stderr, "  -d          Debug mode.\n");
1055         fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
1056         fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
1057         exit(1);
1058 }
1059
1060 int
1061 main(int ac, char **av)
1062 {
1063         int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1064         int sock, fd, ch, result, saved_errno;
1065         u_int nalloc;
1066         char *shell, *format, *pidstr, *agentsocket = NULL;
1067         fd_set *readsetp = NULL, *writesetp = NULL;
1068         struct sockaddr_un sunaddr;
1069 #ifdef HAVE_SETRLIMIT
1070         struct rlimit rlim;
1071 #endif
1072         int prev_mask;
1073         extern int optind;
1074         extern char *optarg;
1075         pid_t pid;
1076         char pidstrbuf[1 + 3 * sizeof pid];
1077         struct timeval *tvp = NULL;
1078         size_t len;
1079
1080         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1081         sanitise_stdfd();
1082
1083         /* drop */
1084         setegid(getgid());
1085         setgid(getgid());
1086
1087 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1088         /* Disable ptrace on Linux without sgid bit */
1089         prctl(PR_SET_DUMPABLE, 0);
1090 #endif
1091
1092         SSLeay_add_all_algorithms();
1093
1094         __progname = ssh_get_progname(av[0]);
1095         init_rng();
1096         seed_rng();
1097
1098         while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1099                 switch (ch) {
1100                 case 'c':
1101                         if (s_flag)
1102                                 usage();
1103                         c_flag++;
1104                         break;
1105                 case 'k':
1106                         k_flag++;
1107                         break;
1108                 case 's':
1109                         if (c_flag)
1110                                 usage();
1111                         s_flag++;
1112                         break;
1113                 case 'd':
1114                         if (d_flag)
1115                                 usage();
1116                         d_flag++;
1117                         break;
1118                 case 'a':
1119                         agentsocket = optarg;
1120                         break;
1121                 case 't':
1122                         if ((lifetime = convtime(optarg)) == -1) {
1123                                 fprintf(stderr, "Invalid lifetime\n");
1124                                 usage();
1125                         }
1126                         break;
1127                 default:
1128                         usage();
1129                 }
1130         }
1131         ac -= optind;
1132         av += optind;
1133
1134         if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1135                 usage();
1136
1137         if (ac == 0 && !c_flag && !s_flag) {
1138                 shell = getenv("SHELL");
1139                 if (shell != NULL && (len = strlen(shell)) > 2 &&
1140                     strncmp(shell + len - 3, "csh", 3) == 0)
1141                         c_flag = 1;
1142         }
1143         if (k_flag) {
1144                 const char *errstr = NULL;
1145
1146                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1147                 if (pidstr == NULL) {
1148                         fprintf(stderr, "%s not set, cannot kill agent\n",
1149                             SSH_AGENTPID_ENV_NAME);
1150                         exit(1);
1151                 }
1152                 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1153                 if (errstr) {
1154                         fprintf(stderr,
1155                             "%s=\"%s\", which is not a good PID: %s\n",
1156                             SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1157                         exit(1);
1158                 }
1159                 if (kill(pid, SIGTERM) == -1) {
1160                         perror("kill");
1161                         exit(1);
1162                 }
1163                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1164                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1165                 printf(format, SSH_AGENTPID_ENV_NAME);
1166                 printf("echo Agent pid %ld killed;\n", (long)pid);
1167                 exit(0);
1168         }
1169         parent_pid = getpid();
1170
1171         if (agentsocket == NULL) {
1172                 /* Create private directory for agent socket */
1173                 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1174                 if (mkdtemp(socket_dir) == NULL) {
1175                         perror("mkdtemp: private socket dir");
1176                         exit(1);
1177                 }
1178                 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1179                     (long)parent_pid);
1180         } else {
1181                 /* Try to use specified agent socket */
1182                 socket_dir[0] = '\0';
1183                 strlcpy(socket_name, agentsocket, sizeof socket_name);
1184         }
1185
1186         /*
1187          * Create socket early so it will exist before command gets run from
1188          * the parent.
1189          */
1190         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1191         if (sock < 0) {
1192                 perror("socket");
1193                 *socket_name = '\0'; /* Don't unlink any existing file */
1194                 cleanup_exit(1);
1195         }
1196         memset(&sunaddr, 0, sizeof(sunaddr));
1197         sunaddr.sun_family = AF_UNIX;
1198         strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1199         prev_mask = umask(0177);
1200         if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1201                 perror("bind");
1202                 *socket_name = '\0'; /* Don't unlink any existing file */
1203                 umask(prev_mask);
1204                 cleanup_exit(1);
1205         }
1206         umask(prev_mask);
1207         if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1208                 perror("listen");
1209                 cleanup_exit(1);
1210         }
1211
1212         /*
1213          * Fork, and have the parent execute the command, if any, or present
1214          * the socket data.  The child continues as the authentication agent.
1215          */
1216         if (d_flag) {
1217                 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1218                 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1219                 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1220                     SSH_AUTHSOCKET_ENV_NAME);
1221                 printf("echo Agent pid %ld;\n", (long)parent_pid);
1222                 goto skip;
1223         }
1224         pid = fork();
1225         if (pid == -1) {
1226                 perror("fork");
1227                 cleanup_exit(1);
1228         }
1229         if (pid != 0) {         /* Parent - execute the given command. */
1230                 close(sock);
1231                 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1232                 if (ac == 0) {
1233                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1234                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1235                             SSH_AUTHSOCKET_ENV_NAME);
1236                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1237                             SSH_AGENTPID_ENV_NAME);
1238                         printf("echo Agent pid %ld;\n", (long)pid);
1239                         exit(0);
1240                 }
1241                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1242                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1243                         perror("setenv");
1244                         exit(1);
1245                 }
1246                 execvp(av[0], av);
1247                 perror(av[0]);
1248                 exit(1);
1249         }
1250         /* child */
1251         log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1252
1253         if (setsid() == -1) {
1254                 error("setsid: %s", strerror(errno));
1255                 cleanup_exit(1);
1256         }
1257
1258         (void)chdir("/");
1259         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1260                 /* XXX might close listen socket */
1261                 (void)dup2(fd, STDIN_FILENO);
1262                 (void)dup2(fd, STDOUT_FILENO);
1263                 (void)dup2(fd, STDERR_FILENO);
1264                 if (fd > 2)
1265                         close(fd);
1266         }
1267
1268 #ifdef HAVE_SETRLIMIT
1269         /* deny core dumps, since memory contains unencrypted private keys */
1270         rlim.rlim_cur = rlim.rlim_max = 0;
1271         if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1272                 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1273                 cleanup_exit(1);
1274         }
1275 #endif
1276
1277 skip:
1278
1279 #ifdef ENABLE_PKCS11
1280         pkcs11_init(0);
1281 #endif
1282         new_socket(AUTH_SOCKET, sock);
1283         if (ac > 0)
1284                 parent_alive_interval = 10;
1285         idtab_init();
1286         if (!d_flag)
1287                 signal(SIGINT, SIG_IGN);
1288         signal(SIGPIPE, SIG_IGN);
1289         signal(SIGHUP, cleanup_handler);
1290         signal(SIGTERM, cleanup_handler);
1291         nalloc = 0;
1292
1293         while (1) {
1294                 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1295                 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1296                 saved_errno = errno;
1297                 if (parent_alive_interval != 0)
1298                         check_parent_exists();
1299                 (void) reaper();        /* remove expired keys */
1300                 if (result < 0) {
1301                         if (saved_errno == EINTR)
1302                                 continue;
1303                         fatal("select: %s", strerror(saved_errno));
1304                 } else if (result > 0)
1305                         after_select(readsetp, writesetp);
1306         }
1307         /* NOTREACHED */
1308 }