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