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