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