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