]> andersk Git - openssh.git/blob - ssh-agent.c
- markus@cvs.openbsd.org 2001/06/25 08:25:41
[openssh.git] / ssh-agent.c
1 /*      $OpenBSD: ssh-agent.c,v 1.56 2001/06/25 08:25:40 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"
39 RCSID("$OpenBSD: ssh-agent.c,v 1.56 2001/06/25 08:25:40 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 typedef struct {
60         int fd;
61         enum {
62                 AUTH_UNUSED, AUTH_SOCKET, AUTH_CONNECTION
63         } type;
64         Buffer input;
65         Buffer output;
66 } SocketEntry;
67
68 u_int sockets_alloc = 0;
69 SocketEntry *sockets = NULL;
70
71 typedef struct {
72         Key *key;
73         char *comment;
74 } Identity;
75
76 typedef struct {
77         int nentries;
78         Identity *identities;
79 } Idtab;
80
81 /* private key table, one per protocol version */
82 Idtab idtable[3];
83
84 int max_fd = 0;
85
86 /* pid of shell == parent of agent */
87 pid_t parent_pid = -1;
88
89 /* pathname and directory for AUTH_SOCKET */
90 char socket_name[1024];
91 char socket_dir[1024];
92
93 #ifdef HAVE___PROGNAME
94 extern char *__progname;
95 #else
96 char *__progname;
97 #endif
98
99 static void
100 idtab_init(void)
101 {
102         int i;
103         for (i = 0; i <=2; i++){
104                 idtable[i].identities = NULL;
105                 idtable[i].nentries = 0;
106         }
107 }
108
109 /* return private key table for requested protocol version */
110 static Idtab *
111 idtab_lookup(int version)
112 {
113         if (version < 1 || version > 2)
114                 fatal("internal error, bad protocol version %d", version);
115         return &idtable[version];
116 }
117
118 /* return matching private key for given public key */
119 static Key *
120 lookup_private_key(Key *key, int *idx, int version)
121 {
122         int i;
123         Idtab *tab = idtab_lookup(version);
124         for (i = 0; i < tab->nentries; i++) {
125                 if (key_equal(key, tab->identities[i].key)) {
126                         if (idx != NULL)
127                                 *idx = i;
128                         return tab->identities[i].key;
129                 }
130         }
131         return NULL;
132 }
133
134 /* send list of supported public keys to 'client' */
135 static void
136 process_request_identities(SocketEntry *e, int version)
137 {
138         Idtab *tab = idtab_lookup(version);
139         Buffer msg;
140         int i;
141
142         buffer_init(&msg);
143         buffer_put_char(&msg, (version == 1) ?
144             SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
145         buffer_put_int(&msg, tab->nentries);
146         for (i = 0; i < tab->nentries; i++) {
147                 Identity *id = &tab->identities[i];
148                 if (id->key->type == KEY_RSA1) {
149                         buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
150                         buffer_put_bignum(&msg, id->key->rsa->e);
151                         buffer_put_bignum(&msg, id->key->rsa->n);
152                 } else {
153                         u_char *blob;
154                         u_int blen;
155                         key_to_blob(id->key, &blob, &blen);
156                         buffer_put_string(&msg, blob, blen);
157                         xfree(blob);
158                 }
159                 buffer_put_cstring(&msg, id->comment);
160         }
161         buffer_put_int(&e->output, buffer_len(&msg));
162         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
163         buffer_free(&msg);
164 }
165
166 /* ssh1 only */
167 static void
168 process_authentication_challenge1(SocketEntry *e)
169 {
170         Key *key, *private;
171         BIGNUM *challenge;
172         int i, len;
173         Buffer msg;
174         MD5_CTX md;
175         u_char buf[32], mdbuf[16], session_id[16];
176         u_int response_type;
177
178         buffer_init(&msg);
179         key = key_new(KEY_RSA1);
180         challenge = BN_new();
181
182         buffer_get_int(&e->input);                              /* ignored */
183         buffer_get_bignum(&e->input, key->rsa->e);
184         buffer_get_bignum(&e->input, key->rsa->n);
185         buffer_get_bignum(&e->input, challenge);
186
187         /* Only protocol 1.1 is supported */
188         if (buffer_len(&e->input) == 0)
189                 goto failure;
190         buffer_get(&e->input, (char *) session_id, 16);
191         response_type = buffer_get_int(&e->input);
192         if (response_type != 1)
193                 goto failure;
194
195         private = lookup_private_key(key, NULL, 1);
196         if (private != NULL) {
197                 /* Decrypt the challenge using the private key. */
198                 if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
199                         goto failure;
200
201                 /* The response is MD5 of decrypted challenge plus session id. */
202                 len = BN_num_bytes(challenge);
203                 if (len <= 0 || len > 32) {
204                         log("process_authentication_challenge: bad challenge length %d", len);
205                         goto failure;
206                 }
207                 memset(buf, 0, 32);
208                 BN_bn2bin(challenge, buf + 32 - len);
209                 MD5_Init(&md);
210                 MD5_Update(&md, buf, 32);
211                 MD5_Update(&md, session_id, 16);
212                 MD5_Final(mdbuf, &md);
213
214                 /* Send the response. */
215                 buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
216                 for (i = 0; i < 16; i++)
217                         buffer_put_char(&msg, mdbuf[i]);
218                 goto send;
219         }
220
221 failure:
222         /* Unknown identity or protocol error.  Send failure. */
223         buffer_put_char(&msg, SSH_AGENT_FAILURE);
224 send:
225         buffer_put_int(&e->output, buffer_len(&msg));
226         buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
227         key_free(key);
228         BN_clear_free(challenge);
229         buffer_free(&msg);
230 }
231
232 /* ssh2 only */
233 static void
234 process_sign_request2(SocketEntry *e)
235 {
236         extern int datafellows;
237         Key *key, *private;
238         u_char *blob, *data, *signature = NULL;
239         u_int blen, dlen, slen = 0;
240         int flags;
241         Buffer msg;
242         int ok = -1;
243
244         datafellows = 0;
245
246         blob = buffer_get_string(&e->input, &blen);
247         data = buffer_get_string(&e->input, &dlen);
248
249         flags = buffer_get_int(&e->input);
250         if (flags & SSH_AGENT_OLD_SIGNATURE)
251                 datafellows = SSH_BUG_SIGBLOB;
252
253         key = key_from_blob(blob, blen);
254         if (key != NULL) {
255                 private = lookup_private_key(key, NULL, 2);
256                 if (private != NULL)
257                         ok = key_sign(private, &signature, &slen, data, dlen);
258         }
259         key_free(key);
260         buffer_init(&msg);
261         if (ok == 0) {
262                 buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
263                 buffer_put_string(&msg, signature, slen);
264         } else {
265                 buffer_put_char(&msg, SSH_AGENT_FAILURE);
266         }
267         buffer_put_int(&e->output, buffer_len(&msg));
268         buffer_append(&e->output, buffer_ptr(&msg),
269             buffer_len(&msg));
270         buffer_free(&msg);
271         xfree(data);
272         xfree(blob);
273         if (signature != NULL)
274                 xfree(signature);
275 }
276
277 /* shared */
278 static void
279 process_remove_identity(SocketEntry *e, int version)
280 {
281         Key *key = NULL, *private;
282         u_char *blob;
283         u_int blen;
284         u_int bits;
285         int success = 0;
286
287         switch(version){
288         case 1:
289                 key = key_new(KEY_RSA1);
290                 bits = buffer_get_int(&e->input);
291                 buffer_get_bignum(&e->input, key->rsa->e);
292                 buffer_get_bignum(&e->input, key->rsa->n);
293
294                 if (bits != key_size(key))
295                         log("Warning: identity keysize mismatch: actual %d, announced %d",
296                             key_size(key), bits);
297                 break;
298         case 2:
299                 blob = buffer_get_string(&e->input, &blen);
300                 key = key_from_blob(blob, blen);
301                 xfree(blob);
302                 break;
303         }
304         if (key != NULL) {
305                 int idx;
306                 private = lookup_private_key(key, &idx, version);
307                 if (private != NULL) {
308                         /*
309                          * We have this key.  Free the old key.  Since we
310                          * don\'t want to leave empty slots in the middle of
311                          * the array, we actually free the key there and move
312                          * all the entries between the empty slot and the end
313                          * of the array.
314                          */
315                         Idtab *tab = idtab_lookup(version);
316                         key_free(tab->identities[idx].key);
317                         xfree(tab->identities[idx].comment);
318                         if (tab->nentries < 1)
319                                 fatal("process_remove_identity: "
320                                     "internal error: tab->nentries %d",
321                                     tab->nentries);
322                         if (idx != tab->nentries - 1) {
323                                 int i;
324                                 for (i = idx; i < tab->nentries - 1; i++)
325                                         tab->identities[i] = tab->identities[i+1];
326                         }
327                         tab->identities[tab->nentries - 1].key = NULL;
328                         tab->identities[tab->nentries - 1].comment = NULL;
329                         tab->nentries--;
330                         success = 1;
331                 }
332                 key_free(key);
333         }
334         buffer_put_int(&e->output, 1);
335         buffer_put_char(&e->output,
336             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
337 }
338
339 static void
340 process_remove_all_identities(SocketEntry *e, int version)
341 {
342         u_int i;
343         Idtab *tab = idtab_lookup(version);
344
345         /* Loop over all identities and clear the keys. */
346         for (i = 0; i < tab->nentries; i++) {
347                 key_free(tab->identities[i].key);
348                 xfree(tab->identities[i].comment);
349         }
350
351         /* Mark that there are no identities. */
352         tab->nentries = 0;
353
354         /* Send success. */
355         buffer_put_int(&e->output, 1);
356         buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
357         return;
358 }
359
360 static void
361 process_add_identity(SocketEntry *e, int version)
362 {
363         Key *k = NULL;
364         char *type_name;
365         char *comment;
366         int type, success = 0;
367         Idtab *tab = idtab_lookup(version);
368
369         switch (version) {
370         case 1:
371                 k = key_new_private(KEY_RSA1);
372                 buffer_get_int(&e->input);                      /* ignored */
373                 buffer_get_bignum(&e->input, k->rsa->n);
374                 buffer_get_bignum(&e->input, k->rsa->e);
375                 buffer_get_bignum(&e->input, k->rsa->d);
376                 buffer_get_bignum(&e->input, k->rsa->iqmp);
377
378                 /* SSH and SSL have p and q swapped */
379                 buffer_get_bignum(&e->input, k->rsa->q);        /* p */
380                 buffer_get_bignum(&e->input, k->rsa->p);        /* q */
381
382                 /* Generate additional parameters */
383                 generate_additional_parameters(k->rsa);
384                 break;
385         case 2:
386                 type_name = buffer_get_string(&e->input, NULL);
387                 type = key_type_from_name(type_name);
388                 xfree(type_name);
389                 switch(type) {
390                 case KEY_DSA:
391                         k = key_new_private(type);
392                         buffer_get_bignum2(&e->input, k->dsa->p);
393                         buffer_get_bignum2(&e->input, k->dsa->q);
394                         buffer_get_bignum2(&e->input, k->dsa->g);
395                         buffer_get_bignum2(&e->input, k->dsa->pub_key);
396                         buffer_get_bignum2(&e->input, k->dsa->priv_key);
397                         break;
398                 case KEY_RSA:
399                         k = key_new_private(type);
400                         buffer_get_bignum2(&e->input, k->rsa->n);
401                         buffer_get_bignum2(&e->input, k->rsa->e);
402                         buffer_get_bignum2(&e->input, k->rsa->d);
403                         buffer_get_bignum2(&e->input, k->rsa->iqmp);
404                         buffer_get_bignum2(&e->input, k->rsa->p);
405                         buffer_get_bignum2(&e->input, k->rsa->q);
406
407                         /* Generate additional parameters */
408                         generate_additional_parameters(k->rsa);
409                         break;
410                 default:
411                         buffer_clear(&e->input);
412                         goto send;
413                 }
414                 break;
415         }
416         comment = buffer_get_string(&e->input, NULL);
417         if (k == NULL) {
418                 xfree(comment);
419                 goto send;
420         }
421         success = 1;
422         if (lookup_private_key(k, NULL, version) == NULL) {
423                 if (tab->nentries == 0)
424                         tab->identities = xmalloc(sizeof(Identity));
425                 else
426                         tab->identities = xrealloc(tab->identities,
427                             (tab->nentries + 1) * sizeof(Identity));
428                 tab->identities[tab->nentries].key = k;
429                 tab->identities[tab->nentries].comment = comment;
430                 /* Increment the number of identities. */
431                 tab->nentries++;
432         } else {
433                 key_free(k);
434                 xfree(comment);
435         }
436 send:
437         buffer_put_int(&e->output, 1);
438         buffer_put_char(&e->output,
439             success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
440 }
441
442 /* dispatch incoming messages */
443
444 static void
445 process_message(SocketEntry *e)
446 {
447         u_int msg_len;
448         u_int type;
449         u_char *cp;
450         if (buffer_len(&e->input) < 5)
451                 return;         /* Incomplete message. */
452         cp = (u_char *) buffer_ptr(&e->input);
453         msg_len = GET_32BIT(cp);
454         if (msg_len > 256 * 1024) {
455                 shutdown(e->fd, SHUT_RDWR);
456                 close(e->fd);
457                 e->type = AUTH_UNUSED;
458                 return;
459         }
460         if (buffer_len(&e->input) < msg_len + 4)
461                 return;
462         buffer_consume(&e->input, 4);
463         type = buffer_get_char(&e->input);
464
465         switch (type) {
466         /* ssh1 */
467         case SSH_AGENTC_RSA_CHALLENGE:
468                 process_authentication_challenge1(e);
469                 break;
470         case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
471                 process_request_identities(e, 1);
472                 break;
473         case SSH_AGENTC_ADD_RSA_IDENTITY:
474                 process_add_identity(e, 1);
475                 break;
476         case SSH_AGENTC_REMOVE_RSA_IDENTITY:
477                 process_remove_identity(e, 1);
478                 break;
479         case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
480                 process_remove_all_identities(e, 1);
481                 break;
482         /* ssh2 */
483         case SSH2_AGENTC_SIGN_REQUEST:
484                 process_sign_request2(e);
485                 break;
486         case SSH2_AGENTC_REQUEST_IDENTITIES:
487                 process_request_identities(e, 2);
488                 break;
489         case SSH2_AGENTC_ADD_IDENTITY:
490                 process_add_identity(e, 2);
491                 break;
492         case SSH2_AGENTC_REMOVE_IDENTITY:
493                 process_remove_identity(e, 2);
494                 break;
495         case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
496                 process_remove_all_identities(e, 2);
497                 break;
498         default:
499                 /* Unknown message.  Respond with failure. */
500                 error("Unknown message %d", type);
501                 buffer_clear(&e->input);
502                 buffer_put_int(&e->output, 1);
503                 buffer_put_char(&e->output, SSH_AGENT_FAILURE);
504                 break;
505         }
506 }
507
508 static void
509 new_socket(int type, int fd)
510 {
511         u_int i, old_alloc;
512         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
513                 error("fcntl O_NONBLOCK: %s", strerror(errno));
514
515         if (fd > max_fd)
516                 max_fd = fd;
517
518         for (i = 0; i < sockets_alloc; i++)
519                 if (sockets[i].type == AUTH_UNUSED) {
520                         sockets[i].fd = fd;
521                         sockets[i].type = type;
522                         buffer_init(&sockets[i].input);
523                         buffer_init(&sockets[i].output);
524                         return;
525                 }
526         old_alloc = sockets_alloc;
527         sockets_alloc += 10;
528         if (sockets)
529                 sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
530         else
531                 sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
532         for (i = old_alloc; i < sockets_alloc; i++)
533                 sockets[i].type = AUTH_UNUSED;
534         sockets[old_alloc].type = type;
535         sockets[old_alloc].fd = fd;
536         buffer_init(&sockets[old_alloc].input);
537         buffer_init(&sockets[old_alloc].output);
538 }
539
540 static int
541 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl)
542 {
543         u_int i, sz;
544         int n = 0;
545
546         for (i = 0; i < sockets_alloc; i++) {
547                 switch (sockets[i].type) {
548                 case AUTH_SOCKET:
549                 case AUTH_CONNECTION:
550                         n = MAX(n, sockets[i].fd);
551                         break;
552                 case AUTH_UNUSED:
553                         break;
554                 default:
555                         fatal("Unknown socket type %d", sockets[i].type);
556                         break;
557                 }
558         }
559
560         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
561         if (*fdrp == NULL || n > *fdl) {
562                 if (*fdrp)
563                         xfree(*fdrp);
564                 if (*fdwp)
565                         xfree(*fdwp);
566                 *fdrp = xmalloc(sz);
567                 *fdwp = xmalloc(sz);
568                 *fdl = n;
569         }
570         memset(*fdrp, 0, sz);
571         memset(*fdwp, 0, sz);
572
573         for (i = 0; i < sockets_alloc; i++) {
574                 switch (sockets[i].type) {
575                 case AUTH_SOCKET:
576                 case AUTH_CONNECTION:
577                         FD_SET(sockets[i].fd, *fdrp);
578                         if (buffer_len(&sockets[i].output) > 0)
579                                 FD_SET(sockets[i].fd, *fdwp);
580                         break;
581                 default:
582                         break;
583                 }
584         }
585         return (1);
586 }
587
588 static void
589 after_select(fd_set *readset, fd_set *writeset)
590 {
591         u_int i;
592         int len, sock;
593         socklen_t slen;
594         char buf[1024];
595         struct sockaddr_un sunaddr;
596
597         for (i = 0; i < sockets_alloc; i++)
598                 switch (sockets[i].type) {
599                 case AUTH_UNUSED:
600                         break;
601                 case AUTH_SOCKET:
602                         if (FD_ISSET(sockets[i].fd, readset)) {
603                                 slen = sizeof(sunaddr);
604                                 sock = accept(sockets[i].fd,
605                                     (struct sockaddr *) &sunaddr, &slen);
606                                 if (sock < 0) {
607                                         perror("accept from AUTH_SOCKET");
608                                         break;
609                                 }
610                                 new_socket(AUTH_CONNECTION, sock);
611                         }
612                         break;
613                 case AUTH_CONNECTION:
614                         if (buffer_len(&sockets[i].output) > 0 &&
615                             FD_ISSET(sockets[i].fd, writeset)) {
616                                 do {
617                                         len = write(sockets[i].fd,
618                                             buffer_ptr(&sockets[i].output),
619                                             buffer_len(&sockets[i].output));
620                                         if (len == -1 && (errno == EAGAIN ||
621                                             errno == EINTR))
622                                                 continue;
623                                         break;
624                                 } while (1);
625                                 if (len <= 0) {
626                                         shutdown(sockets[i].fd, SHUT_RDWR);
627                                         close(sockets[i].fd);
628                                         sockets[i].type = AUTH_UNUSED;
629                                         buffer_free(&sockets[i].input);
630                                         buffer_free(&sockets[i].output);
631                                         break;
632                                 }
633                                 buffer_consume(&sockets[i].output, len);
634                         }
635                         if (FD_ISSET(sockets[i].fd, readset)) {
636                                 do {
637                                         len = read(sockets[i].fd, buf, sizeof(buf));
638                                         if (len == -1 && (errno == EAGAIN ||
639                                             errno == EINTR))
640                                                 continue;
641                                         break;
642                                 } while (1);
643                                 if (len <= 0) {
644                                         shutdown(sockets[i].fd, SHUT_RDWR);
645                                         close(sockets[i].fd);
646                                         sockets[i].type = AUTH_UNUSED;
647                                         buffer_free(&sockets[i].input);
648                                         buffer_free(&sockets[i].output);
649                                         break;
650                                 }
651                                 buffer_append(&sockets[i].input, buf, len);
652                                 process_message(&sockets[i]);
653                         }
654                         break;
655                 default:
656                         fatal("Unknown type %d", sockets[i].type);
657                 }
658 }
659
660 static void
661 check_parent_exists(int sig)
662 {
663         int save_errno = errno;
664
665         if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
666                 /* printf("Parent has died - Authentication agent exiting.\n"); */
667                 exit(1);
668         }
669         signal(SIGALRM, check_parent_exists);
670         alarm(10);
671         errno = save_errno;
672 }
673
674 static void
675 cleanup_socket(void)
676 {
677         if (socket_name[0])
678                 unlink(socket_name);
679         if (socket_dir[0])
680                 rmdir(socket_dir);
681 }
682
683 static void
684 cleanup_exit(int i)
685 {
686         cleanup_socket();
687         exit(i);
688 }
689
690 static void
691 cleanup_handler(int sig)
692 {
693         cleanup_socket();
694         _exit(2);
695 }
696
697 static void
698 usage(void)
699 {
700         fprintf(stderr, "ssh-agent version %s\n", SSH_VERSION);
701         fprintf(stderr, "Usage: %s [-c | -s] [-k] [command {args...]]\n",
702             __progname);
703         exit(1);
704 }
705
706 int
707 main(int ac, char **av)
708 {
709         int sock, c_flag = 0, k_flag = 0, s_flag = 0, ch;
710         struct sockaddr_un sunaddr;
711 #ifdef HAVE_SETRLIMIT
712         struct rlimit rlim;
713 #endif
714 #ifdef HAVE_CYGWIN
715         int prev_mask;
716 #endif
717         pid_t pid;
718         char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
719         extern int optind;
720         fd_set *readsetp = NULL, *writesetp = NULL;
721
722         SSLeay_add_all_algorithms();
723
724         __progname = get_progname(av[0]);
725         init_rng();
726         seed_rng();
727
728 #ifdef __GNU_LIBRARY__
729         while ((ch = getopt(ac, av, "+cks")) != -1) {
730 #else /* __GNU_LIBRARY__ */
731         while ((ch = getopt(ac, av, "cks")) != -1) {
732 #endif /* __GNU_LIBRARY__ */
733                 switch (ch) {
734                 case 'c':
735                         if (s_flag)
736                                 usage();
737                         c_flag++;
738                         break;
739                 case 'k':
740                         k_flag++;
741                         break;
742                 case 's':
743                         if (c_flag)
744                                 usage();
745                         s_flag++;
746                         break;
747                 default:
748                         usage();
749                 }
750         }
751         ac -= optind;
752         av += optind;
753
754         if (ac > 0 && (c_flag || k_flag || s_flag))
755                 usage();
756
757         if (ac == 0 && !c_flag && !k_flag && !s_flag) {
758                 shell = getenv("SHELL");
759                 if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
760                         c_flag = 1;
761         }
762         if (k_flag) {
763                 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
764                 if (pidstr == NULL) {
765                         fprintf(stderr, "%s not set, cannot kill agent\n",
766                             SSH_AGENTPID_ENV_NAME);
767                         exit(1);
768                 }
769                 pid = atoi(pidstr);
770                 if (pid < 1) {
771                         fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
772                             SSH_AGENTPID_ENV_NAME, pidstr);
773                         exit(1);
774                 }
775                 if (kill(pid, SIGTERM) == -1) {
776                         perror("kill");
777                         exit(1);
778                 }
779                 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
780                 printf(format, SSH_AUTHSOCKET_ENV_NAME);
781                 printf(format, SSH_AGENTPID_ENV_NAME);
782                 printf("echo Agent pid %d killed;\n", pid);
783                 exit(0);
784         }
785         parent_pid = getpid();
786
787         /* Create private directory for agent socket */
788         strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
789         if (mkdtemp(socket_dir) == NULL) {
790                 perror("mkdtemp: private socket dir");
791                 exit(1);
792         }
793         snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
794             parent_pid);
795
796         /*
797          * Create socket early so it will exist before command gets run from
798          * the parent.
799          */
800         sock = socket(AF_UNIX, SOCK_STREAM, 0);
801         if (sock < 0) {
802                 perror("socket");
803                 cleanup_exit(1);
804         }
805         memset(&sunaddr, 0, sizeof(sunaddr));
806         sunaddr.sun_family = AF_UNIX;
807         strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
808 #ifdef HAVE_CYGWIN
809         prev_mask = umask(0177);
810 #endif
811         if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
812                 perror("bind");
813 #ifdef HAVE_CYGWIN
814                 umask(prev_mask);
815 #endif
816                 cleanup_exit(1);
817         }
818 #ifdef HAVE_CYGWIN
819         umask(prev_mask);
820 #endif
821         if (listen(sock, 5) < 0) {
822                 perror("listen");
823                 cleanup_exit(1);
824         }
825
826         /*
827          * Fork, and have the parent execute the command, if any, or present
828          * the socket data.  The child continues as the authentication agent.
829          */
830         pid = fork();
831         if (pid == -1) {
832                 perror("fork");
833                 exit(1);
834         }
835         if (pid != 0) {         /* Parent - execute the given command. */
836                 close(sock);
837                 snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
838                 if (ac == 0) {
839                         format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
840                         printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
841                             SSH_AUTHSOCKET_ENV_NAME);
842                         printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
843                             SSH_AGENTPID_ENV_NAME);
844                         printf("echo Agent pid %d;\n", pid);
845                         exit(0);
846                 }
847                 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
848                     setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
849                         perror("setenv");
850                         exit(1);
851                 }
852                 execvp(av[0], av);
853                 perror(av[0]);
854                 exit(1);
855         }
856         close(0);
857         close(1);
858         close(2);
859
860 #ifdef HAVE_SETRLIMIT
861         /* deny core dumps, since memory contains unencrypted private keys */
862         rlim.rlim_cur = rlim.rlim_max = 0;
863         if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
864                 perror("setrlimit rlimit_core failed");
865                 cleanup_exit(1);
866         }
867 #endif
868         if (setsid() == -1) {
869                 perror("setsid");
870                 cleanup_exit(1);
871         }
872         if (atexit(cleanup_socket) < 0) {
873                 perror("atexit");
874                 cleanup_exit(1);
875         }
876         new_socket(AUTH_SOCKET, sock);
877         if (ac > 0) {
878                 signal(SIGALRM, check_parent_exists);
879                 alarm(10);
880         }
881         idtab_init();
882         signal(SIGINT, SIG_IGN);
883         signal(SIGPIPE, SIG_IGN);
884         signal(SIGHUP, cleanup_handler);
885         signal(SIGTERM, cleanup_handler);
886         while (1) {
887                 prepare_select(&readsetp, &writesetp, &max_fd);
888                 if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
889                         if (errno == EINTR)
890                                 continue;
891                         exit(1);
892                 }
893                 after_select(readsetp, writesetp);
894         }
895         /* NOTREACHED */
896 }
This page took 0.415263 seconds and 5 git commands to generate.