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