1 /* $NetBSD: ssh-agent.c,v 1.17 2016/03/11 01:55:00 christos Exp $ */ 2 /* $OpenBSD: ssh-agent.c,v 1.212 2016/02/15 09:47:49 dtucker Exp $ */ 3 4 /* 5 * Author: Tatu Ylonen <ylo@cs.hut.fi> 6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 7 * All rights reserved 8 * The authentication agent program. 9 * 10 * As far as I am concerned, the code I have written for this software 11 * can be used freely for any purpose. Any derived versions of this 12 * software must be clearly marked as such, and if the derived work is 13 * incompatible with the protocol description in the RFC file, it must be 14 * called by a name other than "ssh" or "Secure Shell". 15 * 16 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 */ 38 39 #include "includes.h" 40 __RCSID("$NetBSD: ssh-agent.c,v 1.17 2016/03/11 01:55:00 christos Exp $"); 41 #include <sys/param.h> /* MIN MAX */ 42 #include <sys/types.h> 43 #include <sys/time.h> 44 #include <sys/queue.h> 45 #include <sys/resource.h> 46 #include <sys/socket.h> 47 #include <sys/stat.h> 48 #include <sys/un.h> 49 50 #ifdef WITH_OPENSSL 51 #include <openssl/evp.h> 52 #endif 53 54 #include <errno.h> 55 #include <fcntl.h> 56 #include <paths.h> 57 #include <signal.h> 58 #include <stdlib.h> 59 #include <stdio.h> 60 #include <string.h> 61 #include <limits.h> 62 #include <time.h> 63 #include <unistd.h> 64 #include <util.h> 65 66 #include "xmalloc.h" 67 #include "ssh.h" 68 #include "rsa.h" 69 #include "sshbuf.h" 70 #include "sshkey.h" 71 #include "authfd.h" 72 #include "compat.h" 73 #include "log.h" 74 #include "misc.h" 75 #include "getpeereid.h" 76 #include "digest.h" 77 #include "ssherr.h" 78 79 #ifdef ENABLE_PKCS11 80 #include "ssh-pkcs11.h" 81 #endif 82 83 typedef enum { 84 AUTH_UNUSED, 85 AUTH_SOCKET, 86 AUTH_CONNECTION 87 } sock_type; 88 89 typedef struct { 90 int fd; 91 sock_type type; 92 struct sshbuf *input; 93 struct sshbuf *output; 94 struct sshbuf *request; 95 } SocketEntry; 96 97 u_int sockets_alloc = 0; 98 SocketEntry *sockets = NULL; 99 100 typedef struct identity { 101 TAILQ_ENTRY(identity) next; 102 struct sshkey *key; 103 char *comment; 104 char *provider; 105 time_t death; 106 u_int confirm; 107 } Identity; 108 109 typedef struct { 110 int nentries; 111 TAILQ_HEAD(idqueue, identity) idlist; 112 } Idtab; 113 114 /* private key table, one per protocol version */ 115 Idtab idtable[3]; 116 117 int max_fd = 0; 118 119 /* pid of shell == parent of agent */ 120 pid_t parent_pid = -1; 121 time_t parent_alive_interval = 0; 122 123 /* pid of process for which cleanup_socket is applicable */ 124 pid_t cleanup_pid = 0; 125 126 /* pathname and directory for AUTH_SOCKET */ 127 char socket_name[PATH_MAX]; 128 char socket_dir[PATH_MAX]; 129 130 /* locking */ 131 #define LOCK_SIZE 32 132 #define LOCK_SALT_SIZE 16 133 #define LOCK_ROUNDS 1 134 int locked = 0; 135 char lock_passwd[LOCK_SIZE]; 136 char lock_salt[LOCK_SALT_SIZE]; 137 138 extern char *__progname; 139 140 /* Default lifetime in seconds (0 == forever) */ 141 static long lifetime = 0; 142 143 static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 144 145 static void 146 close_socket(SocketEntry *e) 147 { 148 close(e->fd); 149 e->fd = -1; 150 e->type = AUTH_UNUSED; 151 sshbuf_free(e->input); 152 sshbuf_free(e->output); 153 sshbuf_free(e->request); 154 } 155 156 static void 157 idtab_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 */ 168 static Idtab * 169 idtab_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 176 static void 177 free_identity(Identity *id) 178 { 179 sshkey_free(id->key); 180 free(id->provider); 181 free(id->comment); 182 free(id); 183 } 184 185 /* return matching private key for given public key */ 186 static Identity * 187 lookup_identity(struct sshkey *key, int version) 188 { 189 Identity *id; 190 191 Idtab *tab = idtab_lookup(version); 192 TAILQ_FOREACH(id, &tab->idlist, next) { 193 if (sshkey_equal(key, id->key)) 194 return (id); 195 } 196 return (NULL); 197 } 198 199 /* Check confirmation of keysign request */ 200 static int 201 confirm_key(Identity *id) 202 { 203 char *p; 204 int ret = -1; 205 206 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT); 207 if (p != NULL && 208 ask_permission("Allow use of key %s?\nKey fingerprint %s.", 209 id->comment, p)) 210 ret = 0; 211 free(p); 212 213 return (ret); 214 } 215 216 static void 217 send_status(SocketEntry *e, int success) 218 { 219 int r; 220 221 if ((r = sshbuf_put_u32(e->output, 1)) != 0 || 222 (r = sshbuf_put_u8(e->output, success ? 223 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0) 224 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 225 } 226 227 /* send list of supported public keys to 'client' */ 228 static void 229 process_request_identities(SocketEntry *e, int version) 230 { 231 Idtab *tab = idtab_lookup(version); 232 Identity *id; 233 struct sshbuf *msg; 234 int r; 235 236 if ((msg = sshbuf_new()) == NULL) 237 fatal("%s: sshbuf_new failed", __func__); 238 if ((r = sshbuf_put_u8(msg, (version == 1) ? 239 SSH_AGENT_RSA_IDENTITIES_ANSWER : 240 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 241 (r = sshbuf_put_u32(msg, tab->nentries)) != 0) 242 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 243 TAILQ_FOREACH(id, &tab->idlist, next) { 244 if (id->key->type == KEY_RSA1) { 245 #ifdef WITH_SSH1 246 if ((r = sshbuf_put_u32(msg, 247 BN_num_bits(id->key->rsa->n))) != 0 || 248 (r = sshbuf_put_bignum1(msg, 249 id->key->rsa->e)) != 0 || 250 (r = sshbuf_put_bignum1(msg, 251 id->key->rsa->n)) != 0) 252 fatal("%s: buffer error: %s", 253 __func__, ssh_err(r)); 254 #endif 255 } else { 256 u_char *blob; 257 size_t blen; 258 259 if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) { 260 error("%s: sshkey_to_blob: %s", __func__, 261 ssh_err(r)); 262 continue; 263 } 264 if ((r = sshbuf_put_string(msg, blob, blen)) != 0) 265 fatal("%s: buffer error: %s", 266 __func__, ssh_err(r)); 267 free(blob); 268 } 269 if ((r = sshbuf_put_cstring(msg, id->comment)) != 0) 270 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 271 } 272 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 273 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 274 sshbuf_free(msg); 275 } 276 277 #ifdef WITH_SSH1 278 /* ssh1 only */ 279 static void 280 process_authentication_challenge1(SocketEntry *e) 281 { 282 u_char buf[32], mdbuf[16], session_id[16]; 283 u_int response_type; 284 BIGNUM *challenge; 285 Identity *id; 286 int r, len; 287 struct sshbuf *msg; 288 struct ssh_digest_ctx *md; 289 struct sshkey *key; 290 291 if ((msg = sshbuf_new()) == NULL) 292 fatal("%s: sshbuf_new failed", __func__); 293 if ((key = sshkey_new(KEY_RSA1)) == NULL) 294 fatal("%s: sshkey_new failed", __func__); 295 if ((challenge = BN_new()) == NULL) 296 fatal("%s: BN_new failed", __func__); 297 298 if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */ 299 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 || 300 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 || 301 (r = sshbuf_get_bignum1(e->request, challenge))) 302 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 303 304 /* Only protocol 1.1 is supported */ 305 if (sshbuf_len(e->request) == 0) 306 goto failure; 307 if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 || 308 (r = sshbuf_get_u32(e->request, &response_type)) != 0) 309 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 310 if (response_type != 1) 311 goto failure; 312 313 id = lookup_identity(key, 1); 314 if (id != NULL && (!id->confirm || confirm_key(id) == 0)) { 315 struct sshkey *private = id->key; 316 /* Decrypt the challenge using the private key. */ 317 if ((r = rsa_private_decrypt(challenge, challenge, 318 private->rsa) != 0)) { 319 fatal("%s: rsa_public_encrypt: %s", __func__, 320 ssh_err(r)); 321 goto failure; /* XXX ? */ 322 } 323 324 /* The response is MD5 of decrypted challenge plus session id */ 325 len = BN_num_bytes(challenge); 326 if (len <= 0 || len > 32) { 327 logit("%s: bad challenge length %d", __func__, len); 328 goto failure; 329 } 330 memset(buf, 0, 32); 331 BN_bn2bin(challenge, buf + 32 - len); 332 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL || 333 ssh_digest_update(md, buf, 32) < 0 || 334 ssh_digest_update(md, session_id, 16) < 0 || 335 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0) 336 fatal("%s: md5 failed", __func__); 337 ssh_digest_free(md); 338 339 /* Send the response. */ 340 if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 || 341 (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0) 342 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 343 goto send; 344 } 345 346 failure: 347 /* Unknown identity or protocol error. Send failure. */ 348 if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0) 349 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 350 send: 351 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 352 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 353 sshkey_free(key); 354 BN_clear_free(challenge); 355 sshbuf_free(msg); 356 } 357 #endif 358 359 static const char * 360 agent_decode_alg(struct sshkey *key, u_int flags) 361 { 362 if (key->type == KEY_RSA) { 363 if (flags & SSH_AGENT_RSA_SHA2_256) 364 return "rsa-sha2-256"; 365 else if (flags & SSH_AGENT_RSA_SHA2_512) 366 return "rsa-sha2-512"; 367 } 368 return NULL; 369 } 370 371 /* ssh2 only */ 372 static void 373 process_sign_request2(SocketEntry *e) 374 { 375 u_char *blob, *data, *signature = NULL; 376 size_t blen, dlen, slen = 0; 377 u_int compat = 0, flags; 378 int r, ok = -1; 379 struct sshbuf *msg; 380 struct sshkey *key; 381 struct identity *id; 382 383 if ((msg = sshbuf_new()) == NULL) 384 fatal("%s: sshbuf_new failed", __func__); 385 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 || 386 (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 || 387 (r = sshbuf_get_u32(e->request, &flags)) != 0) 388 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 389 if (flags & SSH_AGENT_OLD_SIGNATURE) 390 compat = SSH_BUG_SIGBLOB; 391 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) { 392 error("%s: cannot parse key blob: %s", __func__, ssh_err(r)); 393 goto send; 394 } 395 if ((id = lookup_identity(key, 2)) == NULL) { 396 verbose("%s: %s key not found", __func__, sshkey_type(key)); 397 goto send; 398 } 399 if (id->confirm && confirm_key(id) != 0) { 400 verbose("%s: user refused key", __func__); 401 goto send; 402 } 403 if ((r = sshkey_sign(id->key, &signature, &slen, 404 data, dlen, agent_decode_alg(key, flags), compat)) != 0) { 405 error("%s: sshkey_sign: %s", __func__, ssh_err(r)); 406 goto send; 407 } 408 /* Success */ 409 ok = 0; 410 send: 411 sshkey_free(key); 412 if (ok == 0) { 413 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 || 414 (r = sshbuf_put_string(msg, signature, slen)) != 0) 415 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 416 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0) 417 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 418 419 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 420 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 421 422 sshbuf_free(msg); 423 free(data); 424 free(blob); 425 free(signature); 426 } 427 428 /* shared */ 429 static void 430 process_remove_identity(SocketEntry *e, int version) 431 { 432 size_t blen; 433 int r, success = 0; 434 struct sshkey *key = NULL; 435 u_char *blob; 436 #ifdef WITH_SSH1 437 u_int bits; 438 #endif /* WITH_SSH1 */ 439 440 switch (version) { 441 #ifdef WITH_SSH1 442 case 1: 443 if ((key = sshkey_new(KEY_RSA1)) == NULL) { 444 error("%s: sshkey_new failed", __func__); 445 return; 446 } 447 if ((r = sshbuf_get_u32(e->request, &bits)) != 0 || 448 (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 || 449 (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0) 450 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 451 452 if (bits != sshkey_size(key)) 453 logit("Warning: identity keysize mismatch: " 454 "actual %u, announced %u", 455 sshkey_size(key), bits); 456 break; 457 #endif /* WITH_SSH1 */ 458 case 2: 459 if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0) 460 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 461 if ((r = sshkey_from_blob(blob, blen, &key)) != 0) 462 error("%s: sshkey_from_blob failed: %s", 463 __func__, ssh_err(r)); 464 free(blob); 465 break; 466 } 467 if (key != NULL) { 468 Identity *id = lookup_identity(key, version); 469 if (id != NULL) { 470 /* 471 * We have this key. Free the old key. Since we 472 * don't want to leave empty slots in the middle of 473 * the array, we actually free the key there and move 474 * all the entries between the empty slot and the end 475 * of the array. 476 */ 477 Idtab *tab = idtab_lookup(version); 478 if (tab->nentries < 1) 479 fatal("process_remove_identity: " 480 "internal error: tab->nentries %d", 481 tab->nentries); 482 TAILQ_REMOVE(&tab->idlist, id, next); 483 free_identity(id); 484 tab->nentries--; 485 success = 1; 486 } 487 sshkey_free(key); 488 } 489 send_status(e, success); 490 } 491 492 static void 493 process_remove_all_identities(SocketEntry *e, int version) 494 { 495 Idtab *tab = idtab_lookup(version); 496 Identity *id; 497 498 /* Loop over all identities and clear the keys. */ 499 while ((id = TAILQ_FIRST(&tab->idlist)) != NULL) { 500 TAILQ_REMOVE(&tab->idlist, id, next); 501 free_identity(id); 502 } 503 504 /* Mark that there are no identities. */ 505 tab->nentries = 0; 506 507 /* Send success. */ 508 send_status(e, 1); 509 } 510 511 /* removes expired keys and returns number of seconds until the next expiry */ 512 static time_t 513 reaper(void) 514 { 515 time_t deadline = 0, now = monotime(); 516 Identity *id, *nxt; 517 int version; 518 Idtab *tab; 519 520 for (version = 1; version < 3; version++) { 521 tab = idtab_lookup(version); 522 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) { 523 nxt = TAILQ_NEXT(id, next); 524 if (id->death == 0) 525 continue; 526 if (now >= id->death) { 527 debug("expiring key '%s'", id->comment); 528 TAILQ_REMOVE(&tab->idlist, id, next); 529 free_identity(id); 530 tab->nentries--; 531 } else 532 deadline = (deadline == 0) ? id->death : 533 MIN(deadline, id->death); 534 } 535 } 536 if (deadline == 0 || deadline <= now) 537 return 0; 538 else 539 return (deadline - now); 540 } 541 542 /* 543 * XXX this and the corresponding serialisation function probably belongs 544 * in key.c 545 */ 546 #ifdef WITH_SSH1 547 static int 548 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp) 549 { 550 struct sshkey *k = NULL; 551 int r = SSH_ERR_INTERNAL_ERROR; 552 553 *kp = NULL; 554 if ((k = sshkey_new_private(KEY_RSA1)) == NULL) 555 return SSH_ERR_ALLOC_FAIL; 556 557 if ((r = sshbuf_get_u32(m, NULL)) != 0 || /* ignored */ 558 (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 || 559 (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 || 560 (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 || 561 (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 || 562 /* SSH1 and SSL have p and q swapped */ 563 (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 || /* p */ 564 (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) /* q */ 565 goto out; 566 567 /* Generate additional parameters */ 568 if ((r = rsa_generate_additional_parameters(k->rsa)) != 0) 569 goto out; 570 /* enable blinding */ 571 if (RSA_blinding_on(k->rsa, NULL) != 1) { 572 r = SSH_ERR_LIBCRYPTO_ERROR; 573 goto out; 574 } 575 576 r = 0; /* success */ 577 out: 578 if (r == 0) 579 *kp = k; 580 else 581 sshkey_free(k); 582 return r; 583 } 584 #endif /* WITH_SSH1 */ 585 586 static void 587 process_add_identity(SocketEntry *e, int version) 588 { 589 Idtab *tab = idtab_lookup(version); 590 Identity *id; 591 int success = 0, confirm = 0; 592 u_int seconds; 593 char *comment = NULL; 594 time_t death = 0; 595 struct sshkey *k = NULL; 596 u_char ctype; 597 int r = SSH_ERR_INTERNAL_ERROR; 598 599 switch (version) { 600 #ifdef WITH_SSH1 601 case 1: 602 r = agent_decode_rsa1(e->request, &k); 603 break; 604 #endif /* WITH_SSH1 */ 605 case 2: 606 r = sshkey_private_deserialize(e->request, &k); 607 break; 608 } 609 if (r != 0 || k == NULL || 610 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) { 611 error("%s: decode private key: %s", __func__, ssh_err(r)); 612 goto err; 613 } 614 615 while (sshbuf_len(e->request)) { 616 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) { 617 error("%s: buffer error: %s", __func__, ssh_err(r)); 618 goto err; 619 } 620 switch (ctype) { 621 case SSH_AGENT_CONSTRAIN_LIFETIME: 622 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) { 623 error("%s: bad lifetime constraint: %s", 624 __func__, ssh_err(r)); 625 goto err; 626 } 627 death = monotime() + seconds; 628 break; 629 case SSH_AGENT_CONSTRAIN_CONFIRM: 630 confirm = 1; 631 break; 632 default: 633 error("%s: Unknown constraint %d", __func__, ctype); 634 err: 635 sshbuf_reset(e->request); 636 free(comment); 637 sshkey_free(k); 638 goto send; 639 } 640 } 641 642 success = 1; 643 if (lifetime && !death) 644 death = monotime() + lifetime; 645 if ((id = lookup_identity(k, version)) == NULL) { 646 id = xcalloc(1, sizeof(Identity)); 647 id->key = k; 648 TAILQ_INSERT_TAIL(&tab->idlist, id, next); 649 /* Increment the number of identities. */ 650 tab->nentries++; 651 } else { 652 sshkey_free(k); 653 free(id->comment); 654 } 655 id->comment = comment; 656 id->death = death; 657 id->confirm = confirm; 658 send: 659 send_status(e, success); 660 } 661 662 /* XXX todo: encrypt sensitive data with passphrase */ 663 static void 664 process_lock_agent(SocketEntry *e, int lock) 665 { 666 int r, success = 0, delay; 667 char *passwd, passwdhash[LOCK_SIZE]; 668 static u_int fail_count = 0; 669 size_t pwlen; 670 671 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0) 672 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 673 if (pwlen == 0) { 674 debug("empty password not supported"); 675 } else if (locked && !lock) { 676 if (bcrypt_pbkdf(passwd, pwlen, (uint8_t *)lock_salt, sizeof(lock_salt), 677 (uint8_t *)passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0) 678 fatal("bcrypt_pbkdf"); 679 if (timingsafe_bcmp(passwdhash, lock_passwd, LOCK_SIZE) == 0) { 680 debug("agent unlocked"); 681 locked = 0; 682 fail_count = 0; 683 explicit_bzero(lock_passwd, sizeof(lock_passwd)); 684 success = 1; 685 } else { 686 /* delay in 0.1s increments up to 10s */ 687 if (fail_count < 100) 688 fail_count++; 689 delay = 100000 * fail_count; 690 debug("unlock failed, delaying %0.1lf seconds", 691 (double)delay/1000000); 692 usleep(delay); 693 } 694 explicit_bzero(passwdhash, sizeof(passwdhash)); 695 } else if (!locked && lock) { 696 debug("agent locked"); 697 locked = 1; 698 arc4random_buf(lock_salt, sizeof(lock_salt)); 699 if (bcrypt_pbkdf(passwd, pwlen, (uint8_t *)lock_salt, sizeof(lock_salt), 700 (uint8_t *)lock_passwd, sizeof(lock_passwd), 701 LOCK_ROUNDS) < 0) 702 fatal("bcrypt_pbkdf"); 703 success = 1; 704 } 705 explicit_bzero(passwd, pwlen); 706 free(passwd); 707 send_status(e, success); 708 } 709 710 static void 711 no_identities(SocketEntry *e, u_int type) 712 { 713 struct sshbuf *msg; 714 int r; 715 716 if ((msg = sshbuf_new()) == NULL) 717 fatal("%s: sshbuf_new failed", __func__); 718 if ((r = sshbuf_put_u8(msg, 719 (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ? 720 SSH_AGENT_RSA_IDENTITIES_ANSWER : 721 SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 722 (r = sshbuf_put_u32(msg, 0)) != 0 || 723 (r = sshbuf_put_stringb(e->output, msg)) != 0) 724 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 725 sshbuf_free(msg); 726 } 727 728 #ifdef ENABLE_PKCS11 729 static void 730 process_add_smartcard_key(SocketEntry *e) 731 { 732 char *provider = NULL, *pin; 733 int r, i, version, count = 0, success = 0, confirm = 0; 734 u_int seconds; 735 time_t death = 0; 736 u_char type; 737 struct sshkey **keys = NULL, *k; 738 Identity *id; 739 Idtab *tab; 740 741 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 742 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) 743 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 744 745 while (sshbuf_len(e->request)) { 746 if ((r = sshbuf_get_u8(e->request, &type)) != 0) 747 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 748 switch (type) { 749 case SSH_AGENT_CONSTRAIN_LIFETIME: 750 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) 751 fatal("%s: buffer error: %s", 752 __func__, ssh_err(r)); 753 death = monotime() + seconds; 754 break; 755 case SSH_AGENT_CONSTRAIN_CONFIRM: 756 confirm = 1; 757 break; 758 default: 759 error("process_add_smartcard_key: " 760 "Unknown constraint type %d", type); 761 goto send; 762 } 763 } 764 if (lifetime && !death) 765 death = monotime() + lifetime; 766 767 count = pkcs11_add_provider(provider, pin, &keys); 768 for (i = 0; i < count; i++) { 769 k = keys[i]; 770 version = k->type == KEY_RSA1 ? 1 : 2; 771 tab = idtab_lookup(version); 772 if (lookup_identity(k, version) == NULL) { 773 id = xcalloc(1, sizeof(Identity)); 774 id->key = k; 775 id->provider = xstrdup(provider); 776 id->comment = xstrdup(provider); /* XXX */ 777 id->death = death; 778 id->confirm = confirm; 779 TAILQ_INSERT_TAIL(&tab->idlist, id, next); 780 tab->nentries++; 781 success = 1; 782 } else { 783 sshkey_free(k); 784 } 785 keys[i] = NULL; 786 } 787 send: 788 free(pin); 789 free(provider); 790 free(keys); 791 send_status(e, success); 792 } 793 794 static void 795 process_remove_smartcard_key(SocketEntry *e) 796 { 797 char *provider = NULL, *pin = NULL; 798 int r, version, success = 0; 799 Identity *id, *nxt; 800 Idtab *tab; 801 802 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 803 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) 804 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 805 free(pin); 806 807 for (version = 1; version < 3; version++) { 808 tab = idtab_lookup(version); 809 for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) { 810 nxt = TAILQ_NEXT(id, next); 811 /* Skip file--based keys */ 812 if (id->provider == NULL) 813 continue; 814 if (!strcmp(provider, id->provider)) { 815 TAILQ_REMOVE(&tab->idlist, id, next); 816 free_identity(id); 817 tab->nentries--; 818 } 819 } 820 } 821 if (pkcs11_del_provider(provider) == 0) 822 success = 1; 823 else 824 error("process_remove_smartcard_key:" 825 " pkcs11_del_provider failed"); 826 free(provider); 827 send_status(e, success); 828 } 829 #endif /* ENABLE_PKCS11 */ 830 831 /* dispatch incoming messages */ 832 833 static void 834 process_message(SocketEntry *e) 835 { 836 u_int msg_len; 837 u_char type; 838 const u_char *cp; 839 int r; 840 841 if (sshbuf_len(e->input) < 5) 842 return; /* Incomplete message. */ 843 cp = sshbuf_ptr(e->input); 844 msg_len = PEEK_U32(cp); 845 if (msg_len > 256 * 1024) { 846 close_socket(e); 847 return; 848 } 849 if (sshbuf_len(e->input) < msg_len + 4) 850 return; 851 852 /* move the current input to e->request */ 853 sshbuf_reset(e->request); 854 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 || 855 (r = sshbuf_get_u8(e->request, &type)) != 0) 856 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 857 858 /* check wheter agent is locked */ 859 if (locked && type != SSH_AGENTC_UNLOCK) { 860 sshbuf_reset(e->request); 861 switch (type) { 862 case SSH_AGENTC_REQUEST_RSA_IDENTITIES: 863 case SSH2_AGENTC_REQUEST_IDENTITIES: 864 /* send empty lists */ 865 no_identities(e, type); 866 break; 867 default: 868 /* send a fail message for all other request types */ 869 send_status(e, 0); 870 } 871 return; 872 } 873 874 debug("type %d", type); 875 switch (type) { 876 case SSH_AGENTC_LOCK: 877 case SSH_AGENTC_UNLOCK: 878 process_lock_agent(e, type == SSH_AGENTC_LOCK); 879 break; 880 #ifdef WITH_SSH1 881 /* ssh1 */ 882 case SSH_AGENTC_RSA_CHALLENGE: 883 process_authentication_challenge1(e); 884 break; 885 case SSH_AGENTC_REQUEST_RSA_IDENTITIES: 886 process_request_identities(e, 1); 887 break; 888 case SSH_AGENTC_ADD_RSA_IDENTITY: 889 case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED: 890 process_add_identity(e, 1); 891 break; 892 case SSH_AGENTC_REMOVE_RSA_IDENTITY: 893 process_remove_identity(e, 1); 894 break; 895 #endif 896 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES: 897 process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */ 898 break; 899 /* ssh2 */ 900 case SSH2_AGENTC_SIGN_REQUEST: 901 process_sign_request2(e); 902 break; 903 case SSH2_AGENTC_REQUEST_IDENTITIES: 904 process_request_identities(e, 2); 905 break; 906 case SSH2_AGENTC_ADD_IDENTITY: 907 case SSH2_AGENTC_ADD_ID_CONSTRAINED: 908 process_add_identity(e, 2); 909 break; 910 case SSH2_AGENTC_REMOVE_IDENTITY: 911 process_remove_identity(e, 2); 912 break; 913 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: 914 process_remove_all_identities(e, 2); 915 break; 916 #ifdef ENABLE_PKCS11 917 case SSH_AGENTC_ADD_SMARTCARD_KEY: 918 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED: 919 process_add_smartcard_key(e); 920 break; 921 case SSH_AGENTC_REMOVE_SMARTCARD_KEY: 922 process_remove_smartcard_key(e); 923 break; 924 #endif /* ENABLE_PKCS11 */ 925 default: 926 /* Unknown message. Respond with failure. */ 927 error("Unknown message %d", type); 928 sshbuf_reset(e->request); 929 send_status(e, 0); 930 break; 931 } 932 } 933 934 static void 935 new_socket(sock_type type, int fd) 936 { 937 u_int i, old_alloc, new_alloc; 938 939 set_nonblock(fd); 940 941 if (fd > max_fd) 942 max_fd = fd; 943 944 for (i = 0; i < sockets_alloc; i++) 945 if (sockets[i].type == AUTH_UNUSED) { 946 sockets[i].fd = fd; 947 if ((sockets[i].input = sshbuf_new()) == NULL) 948 fatal("%s: sshbuf_new failed", __func__); 949 if ((sockets[i].output = sshbuf_new()) == NULL) 950 fatal("%s: sshbuf_new failed", __func__); 951 if ((sockets[i].request = sshbuf_new()) == NULL) 952 fatal("%s: sshbuf_new failed", __func__); 953 sockets[i].type = type; 954 return; 955 } 956 old_alloc = sockets_alloc; 957 new_alloc = sockets_alloc + 10; 958 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0])); 959 for (i = old_alloc; i < new_alloc; i++) 960 sockets[i].type = AUTH_UNUSED; 961 sockets_alloc = new_alloc; 962 sockets[old_alloc].fd = fd; 963 if ((sockets[old_alloc].input = sshbuf_new()) == NULL) 964 fatal("%s: sshbuf_new failed", __func__); 965 if ((sockets[old_alloc].output = sshbuf_new()) == NULL) 966 fatal("%s: sshbuf_new failed", __func__); 967 if ((sockets[old_alloc].request = sshbuf_new()) == NULL) 968 fatal("%s: sshbuf_new failed", __func__); 969 sockets[old_alloc].type = type; 970 } 971 972 static int 973 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp, 974 struct timeval **tvpp) 975 { 976 u_int i, sz; 977 int n = 0; 978 static struct timeval tv; 979 time_t deadline; 980 981 for (i = 0; i < sockets_alloc; i++) { 982 switch (sockets[i].type) { 983 case AUTH_SOCKET: 984 case AUTH_CONNECTION: 985 n = MAX(n, sockets[i].fd); 986 break; 987 case AUTH_UNUSED: 988 break; 989 default: 990 fatal("Unknown socket type %d", sockets[i].type); 991 break; 992 } 993 } 994 995 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask); 996 if (*fdrp == NULL || sz > *nallocp) { 997 free(*fdrp); 998 free(*fdwp); 999 *fdrp = xmalloc(sz); 1000 *fdwp = xmalloc(sz); 1001 *nallocp = sz; 1002 } 1003 if (n < *fdl) 1004 debug("XXX shrink: %d < %d", n, *fdl); 1005 *fdl = n; 1006 memset(*fdrp, 0, sz); 1007 memset(*fdwp, 0, sz); 1008 1009 for (i = 0; i < sockets_alloc; i++) { 1010 switch (sockets[i].type) { 1011 case AUTH_SOCKET: 1012 case AUTH_CONNECTION: 1013 FD_SET(sockets[i].fd, *fdrp); 1014 if (sshbuf_len(sockets[i].output) > 0) 1015 FD_SET(sockets[i].fd, *fdwp); 1016 break; 1017 default: 1018 break; 1019 } 1020 } 1021 deadline = reaper(); 1022 if (parent_alive_interval != 0) 1023 deadline = (deadline == 0) ? parent_alive_interval : 1024 MIN(deadline, parent_alive_interval); 1025 if (deadline == 0) { 1026 *tvpp = NULL; 1027 } else { 1028 tv.tv_sec = deadline; 1029 tv.tv_usec = 0; 1030 *tvpp = &tv; 1031 } 1032 return (1); 1033 } 1034 1035 static void 1036 after_select(fd_set *readset, fd_set *writeset) 1037 { 1038 struct sockaddr_un sunaddr; 1039 socklen_t slen; 1040 char buf[1024]; 1041 int len, sock, r; 1042 u_int i, orig_alloc; 1043 uid_t euid; 1044 gid_t egid; 1045 1046 for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++) 1047 switch (sockets[i].type) { 1048 case AUTH_UNUSED: 1049 break; 1050 case AUTH_SOCKET: 1051 if (FD_ISSET(sockets[i].fd, readset)) { 1052 slen = sizeof(sunaddr); 1053 sock = accept(sockets[i].fd, 1054 (struct sockaddr *)&sunaddr, &slen); 1055 if (sock < 0) { 1056 error("accept from AUTH_SOCKET: %s", 1057 strerror(errno)); 1058 break; 1059 } 1060 if (getpeereid(sock, &euid, &egid) < 0) { 1061 error("getpeereid %d failed: %s", 1062 sock, strerror(errno)); 1063 close(sock); 1064 break; 1065 } 1066 if ((euid != 0) && (getuid() != euid)) { 1067 error("uid mismatch: " 1068 "peer euid %u != uid %u", 1069 (u_int) euid, (u_int) getuid()); 1070 close(sock); 1071 break; 1072 } 1073 new_socket(AUTH_CONNECTION, sock); 1074 } 1075 break; 1076 case AUTH_CONNECTION: 1077 if (sshbuf_len(sockets[i].output) > 0 && 1078 FD_ISSET(sockets[i].fd, writeset)) { 1079 len = write(sockets[i].fd, 1080 sshbuf_ptr(sockets[i].output), 1081 sshbuf_len(sockets[i].output)); 1082 if (len == -1 && (errno == EAGAIN || 1083 errno == EINTR)) 1084 continue; 1085 if (len <= 0) { 1086 close_socket(&sockets[i]); 1087 break; 1088 } 1089 if ((r = sshbuf_consume(sockets[i].output, 1090 len)) != 0) 1091 fatal("%s: buffer error: %s", 1092 __func__, ssh_err(r)); 1093 } 1094 if (FD_ISSET(sockets[i].fd, readset)) { 1095 len = read(sockets[i].fd, buf, sizeof(buf)); 1096 if (len == -1 && (errno == EAGAIN || 1097 errno == EINTR)) 1098 continue; 1099 if (len <= 0) { 1100 close_socket(&sockets[i]); 1101 break; 1102 } 1103 if ((r = sshbuf_put(sockets[i].input, 1104 buf, len)) != 0) 1105 fatal("%s: buffer error: %s", 1106 __func__, ssh_err(r)); 1107 explicit_bzero(buf, sizeof(buf)); 1108 process_message(&sockets[i]); 1109 } 1110 break; 1111 default: 1112 fatal("Unknown type %d", sockets[i].type); 1113 } 1114 } 1115 1116 static void 1117 cleanup_socket(void) 1118 { 1119 if (cleanup_pid != 0 && getpid() != cleanup_pid) 1120 return; 1121 debug("%s: cleanup", __func__); 1122 if (socket_name[0]) 1123 unlink(socket_name); 1124 if (socket_dir[0]) 1125 rmdir(socket_dir); 1126 } 1127 1128 void 1129 cleanup_exit(int i) 1130 { 1131 cleanup_socket(); 1132 _exit(i); 1133 } 1134 1135 /*ARGSUSED*/ 1136 __dead static void 1137 cleanup_handler(int sig) 1138 { 1139 cleanup_socket(); 1140 #ifdef ENABLE_PKCS11 1141 pkcs11_terminate(); 1142 #endif 1143 _exit(2); 1144 } 1145 1146 static void 1147 check_parent_exists(void) 1148 { 1149 /* 1150 * If our parent has exited then getppid() will return (pid_t)1, 1151 * so testing for that should be safe. 1152 */ 1153 if (parent_pid != -1 && getppid() != parent_pid) { 1154 /* printf("Parent has died - Authentication agent exiting.\n"); */ 1155 cleanup_socket(); 1156 _exit(2); 1157 } 1158 } 1159 1160 __dead static void 1161 usage(void) 1162 { 1163 fprintf(stderr, 1164 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" 1165 " [-t life] [command [arg ...]]\n" 1166 " ssh-agent [-c | -s] -k\n"); 1167 exit(1); 1168 } 1169 1170 static void 1171 csh_setenv(const char *name, const char *value) 1172 { 1173 printf("setenv %s %s;\n", name, value); 1174 } 1175 1176 static void 1177 csh_unsetenv(const char *name) 1178 { 1179 printf("unsetenv %s;\n", name); 1180 } 1181 1182 static void 1183 sh_setenv(const char *name, const char *value) 1184 { 1185 printf("%s=%s; export %s;\n", name, value, name); 1186 } 1187 1188 static void 1189 sh_unsetenv(const char *name) 1190 { 1191 printf("unset %s;\n", name); 1192 } 1193 int 1194 main(int ac, char **av) 1195 { 1196 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0; 1197 int sock, fd, ch, result, saved_errno; 1198 u_int nalloc; 1199 char *shell, *pidstr, *agentsocket = NULL; 1200 fd_set *readsetp = NULL, *writesetp = NULL; 1201 struct rlimit rlim; 1202 extern int optind; 1203 extern char *optarg; 1204 pid_t pid; 1205 char pidstrbuf[1 + 3 * sizeof pid]; 1206 struct timeval *tvp = NULL; 1207 size_t len; 1208 mode_t prev_mask; 1209 void (*f_setenv)(const char *, const char *); 1210 void (*f_unsetenv)(const char *); 1211 1212 ssh_malloc_init(); /* must be called before any mallocs */ 1213 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1214 sanitise_stdfd(); 1215 1216 /* drop */ 1217 setegid(getgid()); 1218 setgid(getgid()); 1219 1220 #ifdef WITH_OPENSSL 1221 OpenSSL_add_all_algorithms(); 1222 #endif 1223 1224 while ((ch = getopt(ac, av, "cDdksE:a:t:")) != -1) { 1225 switch (ch) { 1226 case 'E': 1227 fingerprint_hash = ssh_digest_alg_by_name(optarg); 1228 if (fingerprint_hash == -1) 1229 fatal("Invalid hash algorithm \"%s\"", optarg); 1230 break; 1231 case 'c': 1232 if (s_flag) 1233 usage(); 1234 c_flag++; 1235 break; 1236 case 'k': 1237 k_flag++; 1238 break; 1239 case 's': 1240 if (c_flag) 1241 usage(); 1242 s_flag++; 1243 break; 1244 case 'd': 1245 if (d_flag || D_flag) 1246 usage(); 1247 d_flag++; 1248 break; 1249 case 'D': 1250 if (d_flag || D_flag) 1251 usage(); 1252 D_flag++; 1253 break; 1254 case 'a': 1255 agentsocket = optarg; 1256 break; 1257 case 't': 1258 if ((lifetime = convtime(optarg)) == -1) { 1259 fprintf(stderr, "Invalid lifetime\n"); 1260 usage(); 1261 } 1262 break; 1263 default: 1264 usage(); 1265 } 1266 } 1267 ac -= optind; 1268 av += optind; 1269 1270 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag)) 1271 usage(); 1272 1273 if (ac == 0 && !c_flag && !s_flag) { 1274 shell = getenv("SHELL"); 1275 if (shell != NULL && (len = strlen(shell)) > 2 && 1276 strncmp(shell + len - 3, "csh", 3) == 0) 1277 c_flag = 1; 1278 } 1279 if (c_flag) { 1280 f_setenv = csh_setenv; 1281 f_unsetenv = csh_unsetenv; 1282 } else { 1283 f_setenv = sh_setenv; 1284 f_unsetenv = sh_unsetenv; 1285 } 1286 if (k_flag) { 1287 const char *errstr = NULL; 1288 1289 pidstr = getenv(SSH_AGENTPID_ENV_NAME); 1290 if (pidstr == NULL) { 1291 fprintf(stderr, "%s not set, cannot kill agent\n", 1292 SSH_AGENTPID_ENV_NAME); 1293 exit(1); 1294 } 1295 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr); 1296 if (errstr) { 1297 fprintf(stderr, 1298 "%s=\"%s\", which is not a good PID: %s\n", 1299 SSH_AGENTPID_ENV_NAME, pidstr, errstr); 1300 exit(1); 1301 } 1302 if (kill(pid, SIGTERM) == -1) { 1303 perror("kill"); 1304 exit(1); 1305 } 1306 (*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME); 1307 (*f_unsetenv)(SSH_AGENTPID_ENV_NAME); 1308 printf("echo Agent pid %ld killed;\n", (long)pid); 1309 exit(0); 1310 } 1311 parent_pid = getpid(); 1312 1313 if (agentsocket == NULL) { 1314 /* Create private directory for agent socket */ 1315 mktemp_proto(socket_dir, sizeof(socket_dir)); 1316 if (mkdtemp(socket_dir) == NULL) { 1317 perror("mkdtemp: private socket dir"); 1318 exit(1); 1319 } 1320 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir, 1321 (long)parent_pid); 1322 } else { 1323 /* Try to use specified agent socket */ 1324 socket_dir[0] = '\0'; 1325 strlcpy(socket_name, agentsocket, sizeof socket_name); 1326 } 1327 1328 /* 1329 * Create socket early so it will exist before command gets run from 1330 * the parent. 1331 */ 1332 prev_mask = umask(0177); 1333 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0); 1334 if (sock < 0) { 1335 /* XXX - unix_listener() calls error() not perror() */ 1336 *socket_name = '\0'; /* Don't unlink any existing file */ 1337 cleanup_exit(1); 1338 } 1339 umask(prev_mask); 1340 1341 /* 1342 * Fork, and have the parent execute the command, if any, or present 1343 * the socket data. The child continues as the authentication agent. 1344 */ 1345 if (D_flag || d_flag) { 1346 log_init(__progname, 1347 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 1348 SYSLOG_FACILITY_AUTH, 1); 1349 if (c_flag) 1350 printf("setenv %s %s;\n", 1351 SSH_AUTHSOCKET_ENV_NAME, socket_name); 1352 else 1353 printf("%s=%s; export %s;\n", 1354 SSH_AUTHSOCKET_ENV_NAME, socket_name, 1355 SSH_AUTHSOCKET_ENV_NAME); 1356 printf("echo Agent pid %ld;\n", (long)parent_pid); 1357 fflush(stdout); 1358 goto skip; 1359 } 1360 pid = fork(); 1361 if (pid == -1) { 1362 perror("fork"); 1363 cleanup_exit(1); 1364 } 1365 if (pid != 0) { /* Parent - execute the given command. */ 1366 close(sock); 1367 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid); 1368 if (ac == 0) { 1369 (*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name); 1370 (*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf); 1371 printf("echo Agent pid %ld;\n", (long)pid); 1372 exit(0); 1373 } 1374 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 || 1375 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) { 1376 perror("setenv"); 1377 exit(1); 1378 } 1379 execvp(av[0], av); 1380 perror(av[0]); 1381 exit(1); 1382 } 1383 /* child */ 1384 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0); 1385 1386 if (setsid() == -1) { 1387 error("setsid: %s", strerror(errno)); 1388 cleanup_exit(1); 1389 } 1390 1391 (void)chdir("/"); 1392 1393 if (sock != STDERR_FILENO + 1) { 1394 if (dup2(sock, STDERR_FILENO + 1) == -1) { 1395 error("dup2: %s", strerror(errno)); 1396 cleanup_exit(1); 1397 } 1398 close(sock); 1399 sock = STDERR_FILENO + 1; 1400 } 1401 #if defined(F_CLOSEM) 1402 if (fcntl(sock + 1, F_CLOSEM, 0) == -1) { 1403 error("fcntl F_CLOSEM: %s", strerror(errno)); 1404 cleanup_exit(1); 1405 } 1406 #else 1407 { 1408 int nfiles; 1409 #if defined(_SC_OPEN_MAX) 1410 nfiles = sysconf(_SC_OPEN_MAX); 1411 #elif defined(RLIMIT_NOFILE) 1412 if (getrlimit(RLIMIT_CORE, &rlim) < 0) { 1413 error("getrlimit RLIMIT_NOFILE: %s", strerror(errno)); 1414 cleanup_exit(1); 1415 } 1416 nfiles = rlim.rlim_cur; 1417 #elif defined(OPEN_MAX) 1418 nfiles = OPEN_MAX; 1419 #elif defined(NOFILE) 1420 nfiles = NOFILE; 1421 #else 1422 nfiles = 1024; 1423 #endif 1424 for (fd = sock + 1; fd < nfiles; fd++) 1425 close(fd); 1426 } 1427 #endif 1428 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 1429 if (dup2(fd, STDIN_FILENO) == -1 || 1430 dup2(fd, STDOUT_FILENO) == -1 || 1431 dup2(fd, STDERR_FILENO) == -1) { 1432 error("dup2: %s", strerror(errno)); 1433 cleanup_exit(1); 1434 } 1435 if (fd > STDERR_FILENO) 1436 close(fd); 1437 } 1438 1439 /* deny core dumps, since memory contains unencrypted private keys */ 1440 rlim.rlim_cur = rlim.rlim_max = 0; 1441 if (setrlimit(RLIMIT_CORE, &rlim) < 0) { 1442 error("setrlimit RLIMIT_CORE: %s", strerror(errno)); 1443 cleanup_exit(1); 1444 } 1445 1446 skip: 1447 1448 cleanup_pid = getpid(); 1449 1450 #ifdef ENABLE_PKCS11 1451 pkcs11_init(0); 1452 #endif 1453 new_socket(AUTH_SOCKET, sock); 1454 if (ac > 0) 1455 parent_alive_interval = 10; 1456 idtab_init(); 1457 signal(SIGPIPE, SIG_IGN); 1458 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN); 1459 signal(SIGHUP, cleanup_handler); 1460 signal(SIGTERM, cleanup_handler); 1461 nalloc = 0; 1462 1463 #ifdef __OpenBSD__ 1464 if (pledge("stdio cpath unix id proc exec", NULL) == -1) 1465 fatal("%s: pledge: %s", __progname, strerror(errno)); 1466 #endif 1467 1468 while (1) { 1469 prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp); 1470 result = select(max_fd + 1, readsetp, writesetp, NULL, tvp); 1471 saved_errno = errno; 1472 if (parent_alive_interval != 0) 1473 check_parent_exists(); 1474 (void) reaper(); /* remove expired keys */ 1475 if (result < 0) { 1476 if (saved_errno == EINTR) 1477 continue; 1478 fatal("select: %s", strerror(saved_errno)); 1479 } else if (result > 0) 1480 after_select(readsetp, writesetp); 1481 } 1482 /* NOTREACHED */ 1483 } 1484