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