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