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