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