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