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