]> andersk Git - openssh.git/blob - ssh-agent.c
- djm@cvs.openbsd.org 2004/06/14 01:44:39
[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.119 2004/06/14 01:44:39 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         set_nonblock(fd);
793
794         if (fd > max_fd)
795                 max_fd = fd;
796
797         for (i = 0; i < sockets_alloc; i++)
798                 if (sockets[i].type == AUTH_UNUSED) {
799                         sockets[i].fd = fd;
800                         buffer_init(&sockets[i].input);
801                         buffer_init(&sockets[i].output);
802                         buffer_init(&sockets[i].request);
803                         sockets[i].type = type;
804                         return;
805                 }
806         old_alloc = sockets_alloc;
807         new_alloc = sockets_alloc + 10;
808         if (sockets)
809                 sockets = xrealloc(sockets, new_alloc * sizeof(sockets[0]));
810         else
811                 sockets = xmalloc(new_alloc * sizeof(sockets[0]));
812         for (i = old_alloc; i < new_alloc; i++)
813                 sockets[i].type = AUTH_UNUSED;
814         sockets_alloc = new_alloc;
815         sockets[old_alloc].fd = fd;
816         buffer_init(&sockets[old_alloc].input);
817         buffer_init(&sockets[old_alloc].output);
818         buffer_init(&sockets[old_alloc].request);
819         sockets[old_alloc].type = type;
820 }
821
822 static int
823 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, int *nallocp)
824 {
825         u_int i, sz;
826         int n = 0;
827
828         for (i = 0; i < sockets_alloc; i++) {
829                 switch (sockets[i].type) {
830                 case AUTH_SOCKET:
831                 case AUTH_CONNECTION:
832                         n = MAX(n, sockets[i].fd);
833                         break;
834                 case AUTH_UNUSED:
835                         break;
836                 default:
837                         fatal("Unknown socket type %d", sockets[i].type);
838                         break;
839                 }
840         }
841
842         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
843         if (*fdrp == NULL || sz > *nallocp) {
844                 if (*fdrp)
845                         xfree(*fdrp);
846                 if (*fdwp)
847                         xfree(*fdwp);
848                 *fdrp = xmalloc(sz);
849                 *fdwp = xmalloc(sz);
850                 *nallocp = sz;
851         }
852         if (n < *fdl)
853                 debug("XXX shrink: %d < %d", n, *fdl);
854         *fdl = n;
855         memset(*fdrp, 0, sz);
856         memset(*fdwp, 0, sz);
857
858         for (i = 0; i < sockets_alloc; i++) {
859                 switch (sockets[i].type) {
860                 case AUTH_SOCKET:
861                 case AUTH_CONNECTION:
862                         FD_SET(sockets[i].fd, *fdrp);
863                         if (buffer_len(&sockets[i].output) > 0)
864                                 FD_SET(sockets[i].fd, *fdwp);
865                         break;
866                 default:
867                         break;
868                 }
869         }
870         return (1);
871 }
872
873 static void
874 after_select(fd_set *readset, fd_set *writeset)
875 {
876         struct sockaddr_un sunaddr;
877         socklen_t slen;
878         char buf[1024];
879         int len, sock;
880         u_int i;
881         uid_t euid;
882         gid_t egid;
883
884         for (i = 0; i < sockets_alloc; i++)
885                 switch (sockets[i].type) {
886                 case AUTH_UNUSED:
887                         break;
888                 case AUTH_SOCKET:
889                         if (FD_ISSET(sockets[i].fd, readset)) {
890                                 slen = sizeof(sunaddr);
891                                 sock = accept(sockets[i].fd,
892                                     (struct sockaddr *) &sunaddr, &slen);
893                                 if (sock < 0) {
894                                         error("accept from AUTH_SOCKET: %s",
895                                             strerror(errno));
896                                         break;
897                                 }
898                                 if (getpeereid(sock, &euid, &egid) < 0) {
899                                         error("getpeereid %d failed: %s",
900                                             sock, strerror(errno));
901                                         close(sock);
902                                         break;
903                                 }
904                                 if ((euid != 0) && (getuid() != euid)) {
905                                         error("uid mismatch: "
906                                             "peer euid %u != uid %u",
907                                             (u_int) euid, (u_int) getuid());
908                                         close(sock);
909                                         break;
910                                 }
911                                 new_socket(AUTH_CONNECTION, sock);
912                         }
913                         break;
914                 case AUTH_CONNECTION:
915                         if (buffer_len(&sockets[i].output) > 0 &&
916                             FD_ISSET(sockets[i].fd, writeset)) {
917                                 do {
918                                         len = write(sockets[i].fd,
919                                             buffer_ptr(&sockets[i].output),
920                                             buffer_len(&sockets[i].output));
921                                         if (len == -1 && (errno == EAGAIN ||
922                                             errno == EINTR))
923                                                 continue;
924                                         break;
925                                 } while (1);
926                                 if (len <= 0) {
927                                         close_socket(&sockets[i]);
928                                         break;
929                                 }
930                                 buffer_consume(&sockets[i].output, len);
931                         }
932                         if (FD_ISSET(sockets[i].fd, readset)) {
933                                 do {
934                                         len = read(sockets[i].fd, buf, sizeof(buf));
935                                         if (len == -1 && (errno == EAGAIN ||
936                                             errno == EINTR))
937                                                 continue;
938                                         break;
939                                 } while (1);
940                                 if (len <= 0) {
941                                         close_socket(&sockets[i]);
942                                         break;
943                                 }
944                                 buffer_append(&sockets[i].input, buf, len);
945                                 process_message(&sockets[i]);
946                         }
947                         break;
948                 default:
949                         fatal("Unknown type %d", sockets[i].type);
950                 }
951 }
952
953 static void
954 cleanup_socket(void)
955 {
956         if (socket_name[0])
957                 unlink(socket_name);
958         if (socket_dir[0])
959                 rmdir(socket_dir);
960 }
961
962 void
963 cleanup_exit(int i)
964 {
965         cleanup_socket();
966         _exit(i);
967 }
968
969 static void
970 cleanup_handler(int sig)
971 {
972         cleanup_socket();
973         _exit(2);
974 }
975
976 static void
977 check_parent_exists(int sig)
978 {
979         int save_errno = errno;
980
981         if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
982                 /* printf("Parent has died - Authentication agent exiting.\n"); */
983                 cleanup_handler(sig); /* safe */
984         }
985         mysignal(SIGALRM, check_parent_exists);
986         alarm(10);
987         errno = save_errno;
988 }
989
990 static void
991 usage(void)
992 {
993         fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
994             __progname);
995         fprintf(stderr, "Options:\n");
996         fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
997         fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
998         fprintf(stderr, "  -k          Kill the current agent.\n");
999         fprintf(stderr, "  -d          Debug mode.\n");
1000         fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
1001         fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
1002         exit(1);
1003 }
1004
1005 int
1006 main(int ac, char **av)
1007 {
1008         int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1009         int sock, fd,  ch, nalloc;
1010         char *shell, *format, *pidstr, *agentsocket = NULL;
1011         fd_set *readsetp = NULL, *writesetp = NULL;
1012         struct sockaddr_un sunaddr;
1013 #ifdef HAVE_SETRLIMIT
1014         struct rlimit rlim;
1015 #endif
1016 #ifdef HAVE_CYGWIN
1017         int prev_mask;
1018 #endif
1019         extern int optind;
1020         extern char *optarg;
1021         pid_t pid;
1022         char pidstrbuf[1 + 3 * sizeof pid];
1023
1024         /* drop */
1025         setegid(getgid());
1026         setgid(getgid());
1027
1028 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1029         /* Disable ptrace on Linux without sgid bit */
1030         prctl(PR_SET_DUMPABLE, 0);
1031 #endif
1032
1033         SSLeay_add_all_algorithms();
1034
1035         __progname = ssh_get_progname(av[0]);
1036         init_rng();
1037         seed_rng();
1038
1039         while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1040                 switch (ch) {
1041                 case 'c':
1042                         if (s_flag)
1043                                 usage();
1044                         c_flag++;
1045                         break;
1046                 case 'k':
1047                         k_flag++;
1048                         break;
1049                 case 's':
1050                         if (c_flag)
1051                                 usage();
1052                         s_flag++;
1053                         break;
1054                 case 'd':
1055                         if (d_flag)
1056                                 usage();
1057                         d_flag++;
1058                         break;
1059                 case 'a':
1060                         agentsocket = optarg;
1061                         break;
1062                 case 't':
1063                         if ((lifetime = convtime(optarg)) == -1) {
1064                                 fprintf(stderr, "Invalid lifetime\n");
1065                                 usage();
1066                         }
1067                         break;
1068                 default:
1069                         usage();
1070                 }
1071         }
1072         ac -= optind;
1073         av += optind;
1074
1075         if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1076                 usage();
1077
1078         if (ac == 0 && !c_flag && !s_flag) {
1079                 shell = getenv("SHELL");
1080                 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1081                         c_flag = 1;
1082         }
1083         if (k_flag) {
1084                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1085                 if (pidstr == NULL) {
1086                         fprintf(stderr, "%s not set, cannot kill agent\n",
1087                             SSH_AGENTPID_ENV_NAME);
1088                         exit(1);
1089                 }
1090                 pid = atoi(pidstr);
1091                 if (pid < 1) {
1092                         fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
1093                             SSH_AGENTPID_ENV_NAME, pidstr);
1094                         exit(1);
1095                 }
1096                 if (kill(pid, SIGTERM) == -1) {
1097                         perror("kill");
1098                         exit(1);
1099                 }
1100                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1101                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1102                 printf(format, SSH_AGENTPID_ENV_NAME);
1103                 printf("echo Agent pid %ld killed;\n", (long)pid);
1104                 exit(0);
1105         }
1106         parent_pid = getpid();
1107
1108         if (agentsocket == NULL) {
1109                 /* Create private directory for agent socket */
1110                 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1111                 if (mkdtemp(socket_dir) == NULL) {
1112                         perror("mkdtemp: private socket dir");
1113                         exit(1);
1114                 }
1115                 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1116                     (long)parent_pid);
1117         } else {
1118                 /* Try to use specified agent socket */
1119                 socket_dir[0] = '\0';
1120                 strlcpy(socket_name, agentsocket, sizeof socket_name);
1121         }
1122
1123         /*
1124          * Create socket early so it will exist before command gets run from
1125          * the parent.
1126          */
1127         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1128         if (sock < 0) {
1129                 perror("socket");
1130                 cleanup_exit(1);
1131         }
1132         memset(&sunaddr, 0, sizeof(sunaddr));
1133         sunaddr.sun_family = AF_UNIX;
1134         strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1135 #ifdef HAVE_CYGWIN
1136         prev_mask = umask(0177);
1137 #endif
1138         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
1139                 perror("bind");
1140 #ifdef HAVE_CYGWIN
1141                 umask(prev_mask);
1142 #endif
1143                 cleanup_exit(1);
1144         }
1145 #ifdef HAVE_CYGWIN
1146         umask(prev_mask);
1147 #endif
1148         if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1149                 perror("listen");
1150                 cleanup_exit(1);
1151         }
1152
1153         /*
1154          * Fork, and have the parent execute the command, if any, or present
1155          * the socket data.  The child continues as the authentication agent.
1156          */
1157         if (d_flag) {
1158                 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1159                 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1160                 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1161                     SSH_AUTHSOCKET_ENV_NAME);
1162                 printf("echo Agent pid %ld;\n", (long)parent_pid);
1163                 goto skip;
1164         }
1165         pid = fork();
1166         if (pid == -1) {
1167                 perror("fork");
1168                 cleanup_exit(1);
1169         }
1170         if (pid != 0) {         /* Parent - execute the given command. */
1171                 close(sock);
1172                 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1173                 if (ac == 0) {
1174                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1175                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1176                             SSH_AUTHSOCKET_ENV_NAME);
1177                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1178                             SSH_AGENTPID_ENV_NAME);
1179                         printf("echo Agent pid %ld;\n", (long)pid);
1180                         exit(0);
1181                 }
1182                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1183                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1184                         perror("setenv");
1185                         exit(1);
1186                 }
1187                 execvp(av[0], av);
1188                 perror(av[0]);
1189                 exit(1);
1190         }
1191         /* child */
1192         log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1193
1194         if (setsid() == -1) {
1195                 error("setsid: %s", strerror(errno));
1196                 cleanup_exit(1);
1197         }
1198
1199         (void)chdir("/");
1200         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1201                 /* XXX might close listen socket */
1202                 (void)dup2(fd, STDIN_FILENO);
1203                 (void)dup2(fd, STDOUT_FILENO);
1204                 (void)dup2(fd, STDERR_FILENO);
1205                 if (fd > 2)
1206                         close(fd);
1207         }
1208
1209 #ifdef HAVE_SETRLIMIT
1210         /* deny core dumps, since memory contains unencrypted private keys */
1211         rlim.rlim_cur = rlim.rlim_max = 0;
1212         if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1213                 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1214                 cleanup_exit(1);
1215         }
1216 #endif
1217
1218 skip:
1219         new_socket(AUTH_SOCKET, sock);
1220         if (ac > 0) {
1221                 mysignal(SIGALRM, check_parent_exists);
1222                 alarm(10);
1223         }
1224         idtab_init();
1225         if (!d_flag)
1226                 signal(SIGINT, SIG_IGN);
1227         signal(SIGPIPE, SIG_IGN);
1228         signal(SIGHUP, cleanup_handler);
1229         signal(SIGTERM, cleanup_handler);
1230         nalloc = 0;
1231
1232         while (1) {
1233                 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1234                 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1235                         if (errno == EINTR)
1236                                 continue;
1237                         fatal("select: %s", strerror(errno));
1238                 }
1239                 after_select(readsetp, writesetp);
1240         }
1241         /* NOTREACHED */
1242 }
This page took 0.302836 seconds and 5 git commands to generate.