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