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