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