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