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