- dtucker@cvs.openbsd.org 2006/07/19 08:56:41
[openssh-git.git] / ssh-agent.c
blob621b09771685828cd3e786569ea1c5d7e59f934f
1 /* $OpenBSD: ssh-agent.c,v 1.144 2006/07/17 01:31:10 stevesk Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * The authentication agent program.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 #include "includes.h"
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #ifdef HAVE_SYS_UN_H
43 # include <sys/un.h>
44 #endif
45 #include "openbsd-compat/sys-queue.h"
46 #include <sys/resource.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #ifdef HAVE_PATHS_H
51 # include <paths.h>
52 #endif
53 #include <signal.h>
54 #include <unistd.h>
56 #include <openssl/evp.h>
57 #include <openssl/md5.h>
59 #include "ssh.h"
60 #include "rsa.h"
61 #include "buffer.h"
62 #include "bufaux.h"
63 #include "xmalloc.h"
64 #include "key.h"
65 #include "authfd.h"
66 #include "compat.h"
67 #include "log.h"
68 #include "misc.h"
70 #ifdef SMARTCARD
71 #include "scard.h"
72 #endif
74 #if defined(HAVE_SYS_PRCTL_H)
75 #include <sys/prctl.h> /* For prctl() and PR_SET_DUMPABLE */
76 #endif
78 typedef enum {
79 AUTH_UNUSED,
80 AUTH_SOCKET,
81 AUTH_CONNECTION
82 } sock_type;
84 typedef struct {
85 int fd;
86 sock_type type;
87 Buffer input;
88 Buffer output;
89 Buffer request;
90 } SocketEntry;
92 u_int sockets_alloc = 0;
93 SocketEntry *sockets = NULL;
95 typedef struct identity {
96 TAILQ_ENTRY(identity) next;
97 Key *key;
98 char *comment;
99 u_int death;
100 u_int confirm;
101 } Identity;
103 typedef struct {
104 int nentries;
105 TAILQ_HEAD(idqueue, identity) idlist;
106 } Idtab;
108 /* private key table, one per protocol version */
109 Idtab idtable[3];
111 int max_fd = 0;
113 /* pid of shell == parent of agent */
114 pid_t parent_pid = -1;
116 /* pathname and directory for AUTH_SOCKET */
117 char socket_name[MAXPATHLEN];
118 char socket_dir[MAXPATHLEN];
120 /* locking */
121 int locked = 0;
122 char *lock_passwd = NULL;
124 extern char *__progname;
126 /* Default lifetime (0 == forever) */
127 static int lifetime = 0;
129 static void
130 close_socket(SocketEntry *e)
132 close(e->fd);
133 e->fd = -1;
134 e->type = AUTH_UNUSED;
135 buffer_free(&e->input);
136 buffer_free(&e->output);
137 buffer_free(&e->request);
140 static void
141 idtab_init(void)
143 int i;
145 for (i = 0; i <=2; i++) {
146 TAILQ_INIT(&idtable[i].idlist);
147 idtable[i].nentries = 0;
151 /* return private key table for requested protocol version */
152 static Idtab *
153 idtab_lookup(int version)
155 if (version < 1 || version > 2)
156 fatal("internal error, bad protocol version %d", version);
157 return &idtable[version];
160 static void
161 free_identity(Identity *id)
163 key_free(id->key);
164 xfree(id->comment);
165 xfree(id);
168 /* return matching private key for given public key */
169 static Identity *
170 lookup_identity(Key *key, int version)
172 Identity *id;
174 Idtab *tab = idtab_lookup(version);
175 TAILQ_FOREACH(id, &tab->idlist, next) {
176 if (key_equal(key, id->key))
177 return (id);
179 return (NULL);
182 /* Check confirmation of keysign request */
183 static int
184 confirm_key(Identity *id)
186 char *p;
187 int ret = -1;
189 p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
190 if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
191 id->comment, p))
192 ret = 0;
193 xfree(p);
195 return (ret);
198 /* send list of supported public keys to 'client' */
199 static void
200 process_request_identities(SocketEntry *e, int version)
202 Idtab *tab = idtab_lookup(version);
203 Identity *id;
204 Buffer msg;
206 buffer_init(&msg);
207 buffer_put_char(&msg, (version == 1) ?
208 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
209 buffer_put_int(&msg, tab->nentries);
210 TAILQ_FOREACH(id, &tab->idlist, next) {
211 if (id->key->type == KEY_RSA1) {
212 buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
213 buffer_put_bignum(&msg, id->key->rsa->e);
214 buffer_put_bignum(&msg, id->key->rsa->n);
215 } else {
216 u_char *blob;
217 u_int blen;
218 key_to_blob(id->key, &blob, &blen);
219 buffer_put_string(&msg, blob, blen);
220 xfree(blob);
222 buffer_put_cstring(&msg, id->comment);
224 buffer_put_int(&e->output, buffer_len(&msg));
225 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
226 buffer_free(&msg);
229 /* ssh1 only */
230 static void
231 process_authentication_challenge1(SocketEntry *e)
233 u_char buf[32], mdbuf[16], session_id[16];
234 u_int response_type;
235 BIGNUM *challenge;
236 Identity *id;
237 int i, len;
238 Buffer msg;
239 MD5_CTX md;
240 Key *key;
242 buffer_init(&msg);
243 key = key_new(KEY_RSA1);
244 if ((challenge = BN_new()) == NULL)
245 fatal("process_authentication_challenge1: BN_new failed");
247 (void) buffer_get_int(&e->request); /* ignored */
248 buffer_get_bignum(&e->request, key->rsa->e);
249 buffer_get_bignum(&e->request, key->rsa->n);
250 buffer_get_bignum(&e->request, challenge);
252 /* Only protocol 1.1 is supported */
253 if (buffer_len(&e->request) == 0)
254 goto failure;
255 buffer_get(&e->request, session_id, 16);
256 response_type = buffer_get_int(&e->request);
257 if (response_type != 1)
258 goto failure;
260 id = lookup_identity(key, 1);
261 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
262 Key *private = id->key;
263 /* Decrypt the challenge using the private key. */
264 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
265 goto failure;
267 /* The response is MD5 of decrypted challenge plus session id. */
268 len = BN_num_bytes(challenge);
269 if (len <= 0 || len > 32) {
270 logit("process_authentication_challenge: bad challenge length %d", len);
271 goto failure;
273 memset(buf, 0, 32);
274 BN_bn2bin(challenge, buf + 32 - len);
275 MD5_Init(&md);
276 MD5_Update(&md, buf, 32);
277 MD5_Update(&md, session_id, 16);
278 MD5_Final(mdbuf, &md);
280 /* Send the response. */
281 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
282 for (i = 0; i < 16; i++)
283 buffer_put_char(&msg, mdbuf[i]);
284 goto send;
287 failure:
288 /* Unknown identity or protocol error. Send failure. */
289 buffer_put_char(&msg, SSH_AGENT_FAILURE);
290 send:
291 buffer_put_int(&e->output, buffer_len(&msg));
292 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
293 key_free(key);
294 BN_clear_free(challenge);
295 buffer_free(&msg);
298 /* ssh2 only */
299 static void
300 process_sign_request2(SocketEntry *e)
302 u_char *blob, *data, *signature = NULL;
303 u_int blen, dlen, slen = 0;
304 extern int datafellows;
305 int ok = -1, flags;
306 Buffer msg;
307 Key *key;
309 datafellows = 0;
311 blob = buffer_get_string(&e->request, &blen);
312 data = buffer_get_string(&e->request, &dlen);
314 flags = buffer_get_int(&e->request);
315 if (flags & SSH_AGENT_OLD_SIGNATURE)
316 datafellows = SSH_BUG_SIGBLOB;
318 key = key_from_blob(blob, blen);
319 if (key != NULL) {
320 Identity *id = lookup_identity(key, 2);
321 if (id != NULL && (!id->confirm || confirm_key(id) == 0))
322 ok = key_sign(id->key, &signature, &slen, data, dlen);
323 key_free(key);
325 buffer_init(&msg);
326 if (ok == 0) {
327 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
328 buffer_put_string(&msg, signature, slen);
329 } else {
330 buffer_put_char(&msg, SSH_AGENT_FAILURE);
332 buffer_put_int(&e->output, buffer_len(&msg));
333 buffer_append(&e->output, buffer_ptr(&msg),
334 buffer_len(&msg));
335 buffer_free(&msg);
336 xfree(data);
337 xfree(blob);
338 if (signature != NULL)
339 xfree(signature);
342 /* shared */
343 static void
344 process_remove_identity(SocketEntry *e, int version)
346 u_int blen, bits;
347 int success = 0;
348 Key *key = NULL;
349 u_char *blob;
351 switch (version) {
352 case 1:
353 key = key_new(KEY_RSA1);
354 bits = buffer_get_int(&e->request);
355 buffer_get_bignum(&e->request, key->rsa->e);
356 buffer_get_bignum(&e->request, key->rsa->n);
358 if (bits != key_size(key))
359 logit("Warning: identity keysize mismatch: actual %u, announced %u",
360 key_size(key), bits);
361 break;
362 case 2:
363 blob = buffer_get_string(&e->request, &blen);
364 key = key_from_blob(blob, blen);
365 xfree(blob);
366 break;
368 if (key != NULL) {
369 Identity *id = lookup_identity(key, version);
370 if (id != NULL) {
372 * We have this key. Free the old key. Since we
373 * don't want to leave empty slots in the middle of
374 * the array, we actually free the key there and move
375 * all the entries between the empty slot and the end
376 * of the array.
378 Idtab *tab = idtab_lookup(version);
379 if (tab->nentries < 1)
380 fatal("process_remove_identity: "
381 "internal error: tab->nentries %d",
382 tab->nentries);
383 TAILQ_REMOVE(&tab->idlist, id, next);
384 free_identity(id);
385 tab->nentries--;
386 success = 1;
388 key_free(key);
390 buffer_put_int(&e->output, 1);
391 buffer_put_char(&e->output,
392 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
395 static void
396 process_remove_all_identities(SocketEntry *e, int version)
398 Idtab *tab = idtab_lookup(version);
399 Identity *id;
401 /* Loop over all identities and clear the keys. */
402 for (id = TAILQ_FIRST(&tab->idlist); id;
403 id = TAILQ_FIRST(&tab->idlist)) {
404 TAILQ_REMOVE(&tab->idlist, id, next);
405 free_identity(id);
408 /* Mark that there are no identities. */
409 tab->nentries = 0;
411 /* Send success. */
412 buffer_put_int(&e->output, 1);
413 buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
416 static void
417 reaper(void)
419 u_int now = time(NULL);
420 Identity *id, *nxt;
421 int version;
422 Idtab *tab;
424 for (version = 1; version < 3; version++) {
425 tab = idtab_lookup(version);
426 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
427 nxt = TAILQ_NEXT(id, next);
428 if (id->death != 0 && now >= id->death) {
429 TAILQ_REMOVE(&tab->idlist, id, next);
430 free_identity(id);
431 tab->nentries--;
437 static void
438 process_add_identity(SocketEntry *e, int version)
440 Idtab *tab = idtab_lookup(version);
441 int type, success = 0, death = 0, confirm = 0;
442 char *type_name, *comment;
443 Key *k = NULL;
445 switch (version) {
446 case 1:
447 k = key_new_private(KEY_RSA1);
448 (void) buffer_get_int(&e->request); /* ignored */
449 buffer_get_bignum(&e->request, k->rsa->n);
450 buffer_get_bignum(&e->request, k->rsa->e);
451 buffer_get_bignum(&e->request, k->rsa->d);
452 buffer_get_bignum(&e->request, k->rsa->iqmp);
454 /* SSH and SSL have p and q swapped */
455 buffer_get_bignum(&e->request, k->rsa->q); /* p */
456 buffer_get_bignum(&e->request, k->rsa->p); /* q */
458 /* Generate additional parameters */
459 rsa_generate_additional_parameters(k->rsa);
460 break;
461 case 2:
462 type_name = buffer_get_string(&e->request, NULL);
463 type = key_type_from_name(type_name);
464 xfree(type_name);
465 switch (type) {
466 case KEY_DSA:
467 k = key_new_private(type);
468 buffer_get_bignum2(&e->request, k->dsa->p);
469 buffer_get_bignum2(&e->request, k->dsa->q);
470 buffer_get_bignum2(&e->request, k->dsa->g);
471 buffer_get_bignum2(&e->request, k->dsa->pub_key);
472 buffer_get_bignum2(&e->request, k->dsa->priv_key);
473 break;
474 case KEY_RSA:
475 k = key_new_private(type);
476 buffer_get_bignum2(&e->request, k->rsa->n);
477 buffer_get_bignum2(&e->request, k->rsa->e);
478 buffer_get_bignum2(&e->request, k->rsa->d);
479 buffer_get_bignum2(&e->request, k->rsa->iqmp);
480 buffer_get_bignum2(&e->request, k->rsa->p);
481 buffer_get_bignum2(&e->request, k->rsa->q);
483 /* Generate additional parameters */
484 rsa_generate_additional_parameters(k->rsa);
485 break;
486 default:
487 buffer_clear(&e->request);
488 goto send;
490 break;
492 /* enable blinding */
493 switch (k->type) {
494 case KEY_RSA:
495 case KEY_RSA1:
496 if (RSA_blinding_on(k->rsa, NULL) != 1) {
497 error("process_add_identity: RSA_blinding_on failed");
498 key_free(k);
499 goto send;
501 break;
503 comment = buffer_get_string(&e->request, NULL);
504 if (k == NULL) {
505 xfree(comment);
506 goto send;
508 success = 1;
509 while (buffer_len(&e->request)) {
510 switch (buffer_get_char(&e->request)) {
511 case SSH_AGENT_CONSTRAIN_LIFETIME:
512 death = time(NULL) + buffer_get_int(&e->request);
513 break;
514 case SSH_AGENT_CONSTRAIN_CONFIRM:
515 confirm = 1;
516 break;
517 default:
518 break;
521 if (lifetime && !death)
522 death = time(NULL) + lifetime;
523 if (lookup_identity(k, version) == NULL) {
524 Identity *id = xmalloc(sizeof(Identity));
525 id->key = k;
526 id->comment = comment;
527 id->death = death;
528 id->confirm = confirm;
529 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
530 /* Increment the number of identities. */
531 tab->nentries++;
532 } else {
533 key_free(k);
534 xfree(comment);
536 send:
537 buffer_put_int(&e->output, 1);
538 buffer_put_char(&e->output,
539 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
542 /* XXX todo: encrypt sensitive data with passphrase */
543 static void
544 process_lock_agent(SocketEntry *e, int lock)
546 int success = 0;
547 char *passwd;
549 passwd = buffer_get_string(&e->request, NULL);
550 if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
551 locked = 0;
552 memset(lock_passwd, 0, strlen(lock_passwd));
553 xfree(lock_passwd);
554 lock_passwd = NULL;
555 success = 1;
556 } else if (!locked && lock) {
557 locked = 1;
558 lock_passwd = xstrdup(passwd);
559 success = 1;
561 memset(passwd, 0, strlen(passwd));
562 xfree(passwd);
564 buffer_put_int(&e->output, 1);
565 buffer_put_char(&e->output,
566 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
569 static void
570 no_identities(SocketEntry *e, u_int type)
572 Buffer msg;
574 buffer_init(&msg);
575 buffer_put_char(&msg,
576 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
577 SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
578 buffer_put_int(&msg, 0);
579 buffer_put_int(&e->output, buffer_len(&msg));
580 buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
581 buffer_free(&msg);
584 #ifdef SMARTCARD
585 static void
586 process_add_smartcard_key (SocketEntry *e)
588 char *sc_reader_id = NULL, *pin;
589 int i, version, success = 0, death = 0, confirm = 0;
590 Key **keys, *k;
591 Identity *id;
592 Idtab *tab;
594 sc_reader_id = buffer_get_string(&e->request, NULL);
595 pin = buffer_get_string(&e->request, NULL);
597 while (buffer_len(&e->request)) {
598 switch (buffer_get_char(&e->request)) {
599 case SSH_AGENT_CONSTRAIN_LIFETIME:
600 death = time(NULL) + buffer_get_int(&e->request);
601 break;
602 case SSH_AGENT_CONSTRAIN_CONFIRM:
603 confirm = 1;
604 break;
605 default:
606 break;
609 if (lifetime && !death)
610 death = time(NULL) + lifetime;
612 keys = sc_get_keys(sc_reader_id, pin);
613 xfree(sc_reader_id);
614 xfree(pin);
616 if (keys == NULL || keys[0] == NULL) {
617 error("sc_get_keys failed");
618 goto send;
620 for (i = 0; keys[i] != NULL; i++) {
621 k = keys[i];
622 version = k->type == KEY_RSA1 ? 1 : 2;
623 tab = idtab_lookup(version);
624 if (lookup_identity(k, version) == NULL) {
625 id = xmalloc(sizeof(Identity));
626 id->key = k;
627 id->comment = sc_get_key_label(k);
628 id->death = death;
629 id->confirm = confirm;
630 TAILQ_INSERT_TAIL(&tab->idlist, id, next);
631 tab->nentries++;
632 success = 1;
633 } else {
634 key_free(k);
636 keys[i] = NULL;
638 xfree(keys);
639 send:
640 buffer_put_int(&e->output, 1);
641 buffer_put_char(&e->output,
642 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
645 static void
646 process_remove_smartcard_key(SocketEntry *e)
648 char *sc_reader_id = NULL, *pin;
649 int i, version, success = 0;
650 Key **keys, *k = NULL;
651 Identity *id;
652 Idtab *tab;
654 sc_reader_id = buffer_get_string(&e->request, NULL);
655 pin = buffer_get_string(&e->request, NULL);
656 keys = sc_get_keys(sc_reader_id, pin);
657 xfree(sc_reader_id);
658 xfree(pin);
660 if (keys == NULL || keys[0] == NULL) {
661 error("sc_get_keys failed");
662 goto send;
664 for (i = 0; keys[i] != NULL; i++) {
665 k = keys[i];
666 version = k->type == KEY_RSA1 ? 1 : 2;
667 if ((id = lookup_identity(k, version)) != NULL) {
668 tab = idtab_lookup(version);
669 TAILQ_REMOVE(&tab->idlist, id, next);
670 tab->nentries--;
671 free_identity(id);
672 success = 1;
674 key_free(k);
675 keys[i] = NULL;
677 xfree(keys);
678 send:
679 buffer_put_int(&e->output, 1);
680 buffer_put_char(&e->output,
681 success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
683 #endif /* SMARTCARD */
685 /* dispatch incoming messages */
687 static void
688 process_message(SocketEntry *e)
690 u_int msg_len, type;
691 u_char *cp;
693 /* kill dead keys */
694 reaper();
696 if (buffer_len(&e->input) < 5)
697 return; /* Incomplete message. */
698 cp = buffer_ptr(&e->input);
699 msg_len = get_u32(cp);
700 if (msg_len > 256 * 1024) {
701 close_socket(e);
702 return;
704 if (buffer_len(&e->input) < msg_len + 4)
705 return;
707 /* move the current input to e->request */
708 buffer_consume(&e->input, 4);
709 buffer_clear(&e->request);
710 buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
711 buffer_consume(&e->input, msg_len);
712 type = buffer_get_char(&e->request);
714 /* check wheter agent is locked */
715 if (locked && type != SSH_AGENTC_UNLOCK) {
716 buffer_clear(&e->request);
717 switch (type) {
718 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
719 case SSH2_AGENTC_REQUEST_IDENTITIES:
720 /* send empty lists */
721 no_identities(e, type);
722 break;
723 default:
724 /* send a fail message for all other request types */
725 buffer_put_int(&e->output, 1);
726 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
728 return;
731 debug("type %d", type);
732 switch (type) {
733 case SSH_AGENTC_LOCK:
734 case SSH_AGENTC_UNLOCK:
735 process_lock_agent(e, type == SSH_AGENTC_LOCK);
736 break;
737 /* ssh1 */
738 case SSH_AGENTC_RSA_CHALLENGE:
739 process_authentication_challenge1(e);
740 break;
741 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
742 process_request_identities(e, 1);
743 break;
744 case SSH_AGENTC_ADD_RSA_IDENTITY:
745 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
746 process_add_identity(e, 1);
747 break;
748 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
749 process_remove_identity(e, 1);
750 break;
751 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
752 process_remove_all_identities(e, 1);
753 break;
754 /* ssh2 */
755 case SSH2_AGENTC_SIGN_REQUEST:
756 process_sign_request2(e);
757 break;
758 case SSH2_AGENTC_REQUEST_IDENTITIES:
759 process_request_identities(e, 2);
760 break;
761 case SSH2_AGENTC_ADD_IDENTITY:
762 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
763 process_add_identity(e, 2);
764 break;
765 case SSH2_AGENTC_REMOVE_IDENTITY:
766 process_remove_identity(e, 2);
767 break;
768 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
769 process_remove_all_identities(e, 2);
770 break;
771 #ifdef SMARTCARD
772 case SSH_AGENTC_ADD_SMARTCARD_KEY:
773 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
774 process_add_smartcard_key(e);
775 break;
776 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
777 process_remove_smartcard_key(e);
778 break;
779 #endif /* SMARTCARD */
780 default:
781 /* Unknown message. Respond with failure. */
782 error("Unknown message %d", type);
783 buffer_clear(&e->request);
784 buffer_put_int(&e->output, 1);
785 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
786 break;
790 static void
791 new_socket(sock_type type, int fd)
793 u_int i, old_alloc, new_alloc;
795 set_nonblock(fd);
797 if (fd > max_fd)
798 max_fd = fd;
800 for (i = 0; i < sockets_alloc; i++)
801 if (sockets[i].type == AUTH_UNUSED) {
802 sockets[i].fd = fd;
803 buffer_init(&sockets[i].input);
804 buffer_init(&sockets[i].output);
805 buffer_init(&sockets[i].request);
806 sockets[i].type = type;
807 return;
809 old_alloc = sockets_alloc;
810 new_alloc = sockets_alloc + 10;
811 sockets = xrealloc(sockets, 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;
822 static int
823 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp)
825 u_int i, sz;
826 int n = 0;
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;
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;
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);
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;
870 return (1);
873 static void
874 after_select(fd_set *readset, fd_set *writeset)
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;
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;
898 if (getpeereid(sock, &euid, &egid) < 0) {
899 error("getpeereid %d failed: %s",
900 sock, strerror(errno));
901 close(sock);
902 break;
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;
911 new_socket(AUTH_CONNECTION, sock);
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;
930 buffer_consume(&sockets[i].output, len);
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;
944 buffer_append(&sockets[i].input, buf, len);
945 process_message(&sockets[i]);
947 break;
948 default:
949 fatal("Unknown type %d", sockets[i].type);
953 static void
954 cleanup_socket(void)
956 if (socket_name[0])
957 unlink(socket_name);
958 if (socket_dir[0])
959 rmdir(socket_dir);
962 void
963 cleanup_exit(int i)
965 cleanup_socket();
966 _exit(i);
969 /*ARGSUSED*/
970 static void
971 cleanup_handler(int sig)
973 cleanup_socket();
974 _exit(2);
977 /*ARGSUSED*/
978 static void
979 check_parent_exists(int sig)
981 int save_errno = errno;
983 if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
984 /* printf("Parent has died - Authentication agent exiting.\n"); */
985 cleanup_handler(sig); /* safe */
987 mysignal(SIGALRM, check_parent_exists);
988 alarm(10);
989 errno = save_errno;
992 static void
993 usage(void)
995 fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
996 __progname);
997 fprintf(stderr, "Options:\n");
998 fprintf(stderr, " -c Generate C-shell commands on stdout.\n");
999 fprintf(stderr, " -s Generate Bourne shell commands on stdout.\n");
1000 fprintf(stderr, " -k Kill the current agent.\n");
1001 fprintf(stderr, " -d Debug mode.\n");
1002 fprintf(stderr, " -a socket Bind agent socket to given name.\n");
1003 fprintf(stderr, " -t life Default identity lifetime (seconds).\n");
1004 exit(1);
1008 main(int ac, char **av)
1010 int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
1011 int sock, fd, ch;
1012 u_int nalloc;
1013 char *shell, *format, *pidstr, *agentsocket = NULL;
1014 fd_set *readsetp = NULL, *writesetp = NULL;
1015 struct sockaddr_un sunaddr;
1016 #ifdef HAVE_SETRLIMIT
1017 struct rlimit rlim;
1018 #endif
1019 int prev_mask;
1020 extern int optind;
1021 extern char *optarg;
1022 pid_t pid;
1023 char pidstrbuf[1 + 3 * sizeof pid];
1025 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1026 sanitise_stdfd();
1028 /* drop */
1029 setegid(getgid());
1030 setgid(getgid());
1032 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
1033 /* Disable ptrace on Linux without sgid bit */
1034 prctl(PR_SET_DUMPABLE, 0);
1035 #endif
1037 SSLeay_add_all_algorithms();
1039 __progname = ssh_get_progname(av[0]);
1040 init_rng();
1041 seed_rng();
1043 while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1044 switch (ch) {
1045 case 'c':
1046 if (s_flag)
1047 usage();
1048 c_flag++;
1049 break;
1050 case 'k':
1051 k_flag++;
1052 break;
1053 case 's':
1054 if (c_flag)
1055 usage();
1056 s_flag++;
1057 break;
1058 case 'd':
1059 if (d_flag)
1060 usage();
1061 d_flag++;
1062 break;
1063 case 'a':
1064 agentsocket = optarg;
1065 break;
1066 case 't':
1067 if ((lifetime = convtime(optarg)) == -1) {
1068 fprintf(stderr, "Invalid lifetime\n");
1069 usage();
1071 break;
1072 default:
1073 usage();
1076 ac -= optind;
1077 av += optind;
1079 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1080 usage();
1082 if (ac == 0 && !c_flag && !s_flag) {
1083 shell = getenv("SHELL");
1084 if (shell != NULL &&
1085 strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1086 c_flag = 1;
1088 if (k_flag) {
1089 const char *errstr = NULL;
1091 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1092 if (pidstr == NULL) {
1093 fprintf(stderr, "%s not set, cannot kill agent\n",
1094 SSH_AGENTPID_ENV_NAME);
1095 exit(1);
1097 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1098 if (errstr) {
1099 fprintf(stderr,
1100 "%s=\"%s\", which is not a good PID: %s\n",
1101 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1102 exit(1);
1104 if (kill(pid, SIGTERM) == -1) {
1105 perror("kill");
1106 exit(1);
1108 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1109 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1110 printf(format, SSH_AGENTPID_ENV_NAME);
1111 printf("echo Agent pid %ld killed;\n", (long)pid);
1112 exit(0);
1114 parent_pid = getpid();
1116 if (agentsocket == NULL) {
1117 /* Create private directory for agent socket */
1118 strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1119 if (mkdtemp(socket_dir) == NULL) {
1120 perror("mkdtemp: private socket dir");
1121 exit(1);
1123 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1124 (long)parent_pid);
1125 } else {
1126 /* Try to use specified agent socket */
1127 socket_dir[0] = '\0';
1128 strlcpy(socket_name, agentsocket, sizeof socket_name);
1132 * Create socket early so it will exist before command gets run from
1133 * the parent.
1135 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1136 if (sock < 0) {
1137 perror("socket");
1138 *socket_name = '\0'; /* Don't unlink any existing file */
1139 cleanup_exit(1);
1141 memset(&sunaddr, 0, sizeof(sunaddr));
1142 sunaddr.sun_family = AF_UNIX;
1143 strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1144 prev_mask = umask(0177);
1145 if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
1146 perror("bind");
1147 *socket_name = '\0'; /* Don't unlink any existing file */
1148 umask(prev_mask);
1149 cleanup_exit(1);
1151 umask(prev_mask);
1152 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1153 perror("listen");
1154 cleanup_exit(1);
1158 * Fork, and have the parent execute the command, if any, or present
1159 * the socket data. The child continues as the authentication agent.
1161 if (d_flag) {
1162 log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1163 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1164 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1165 SSH_AUTHSOCKET_ENV_NAME);
1166 printf("echo Agent pid %ld;\n", (long)parent_pid);
1167 goto skip;
1169 pid = fork();
1170 if (pid == -1) {
1171 perror("fork");
1172 cleanup_exit(1);
1174 if (pid != 0) { /* Parent - execute the given command. */
1175 close(sock);
1176 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1177 if (ac == 0) {
1178 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1179 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1180 SSH_AUTHSOCKET_ENV_NAME);
1181 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1182 SSH_AGENTPID_ENV_NAME);
1183 printf("echo Agent pid %ld;\n", (long)pid);
1184 exit(0);
1186 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1187 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1188 perror("setenv");
1189 exit(1);
1191 execvp(av[0], av);
1192 perror(av[0]);
1193 exit(1);
1195 /* child */
1196 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1198 if (setsid() == -1) {
1199 error("setsid: %s", strerror(errno));
1200 cleanup_exit(1);
1203 (void)chdir("/");
1204 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1205 /* XXX might close listen socket */
1206 (void)dup2(fd, STDIN_FILENO);
1207 (void)dup2(fd, STDOUT_FILENO);
1208 (void)dup2(fd, STDERR_FILENO);
1209 if (fd > 2)
1210 close(fd);
1213 #ifdef HAVE_SETRLIMIT
1214 /* deny core dumps, since memory contains unencrypted private keys */
1215 rlim.rlim_cur = rlim.rlim_max = 0;
1216 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1217 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1218 cleanup_exit(1);
1220 #endif
1222 skip:
1223 new_socket(AUTH_SOCKET, sock);
1224 if (ac > 0) {
1225 mysignal(SIGALRM, check_parent_exists);
1226 alarm(10);
1228 idtab_init();
1229 if (!d_flag)
1230 signal(SIGINT, SIG_IGN);
1231 signal(SIGPIPE, SIG_IGN);
1232 signal(SIGHUP, cleanup_handler);
1233 signal(SIGTERM, cleanup_handler);
1234 nalloc = 0;
1236 while (1) {
1237 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1238 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1239 if (errno == EINTR)
1240 continue;
1241 fatal("select: %s", strerror(errno));
1243 after_select(readsetp, writesetp);
1245 /* NOTREACHED */