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