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