1 /* $OpenBSD: ssh-agent.c,v 1.230 2018/04/10 00:10:49 djm 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/socket.h> 42 #include <sys/stat.h> 43 #include <sys/un.h> 44 45 #ifdef WITH_OPENSSL 46 #include <openssl/evp.h> 47 #endif 48 49 #include <errno.h> 50 #include <fcntl.h> 51 #include <paths.h> 52 #include <poll.h> 53 #include <signal.h> 54 #include <stdlib.h> 55 #include <stdio.h> 56 #include <string.h> 57 #include <limits.h> 58 #include <time.h> 59 #include <unistd.h> 60 #include <util.h> 61 62 #include "xmalloc.h" 63 #include "ssh.h" 64 #include "sshbuf.h" 65 #include "sshkey.h" 66 #include "authfd.h" 67 #include "compat.h" 68 #include "log.h" 69 #include "misc.h" 70 #include "digest.h" 71 #include "ssherr.h" 72 #include "match.h" 73 74 #ifdef ENABLE_PKCS11 75 #include "ssh-pkcs11.h" 76 #endif 77 78 #ifndef DEFAULT_PKCS11_WHITELIST 79 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*" 80 #endif 81 82 /* Maximum accepted message length */ 83 #define AGENT_MAX_LEN (256*1024) 84 85 typedef enum { 86 AUTH_UNUSED, 87 AUTH_SOCKET, 88 AUTH_CONNECTION 89 } sock_type; 90 91 typedef struct { 92 int fd; 93 sock_type type; 94 struct sshbuf *input; 95 struct sshbuf *output; 96 struct sshbuf *request; 97 } SocketEntry; 98 99 u_int sockets_alloc = 0; 100 SocketEntry *sockets = NULL; 101 102 typedef struct identity { 103 TAILQ_ENTRY(identity) next; 104 struct sshkey *key; 105 char *comment; 106 char *provider; 107 time_t death; 108 u_int confirm; 109 } Identity; 110 111 struct idtable { 112 int nentries; 113 TAILQ_HEAD(idqueue, identity) idlist; 114 }; 115 116 /* private key table */ 117 struct idtable *idtab; 118 119 int max_fd = 0; 120 121 /* pid of shell == parent of agent */ 122 pid_t parent_pid = -1; 123 time_t parent_alive_interval = 0; 124 125 /* pid of process for which cleanup_socket is applicable */ 126 pid_t cleanup_pid = 0; 127 128 /* pathname and directory for AUTH_SOCKET */ 129 char socket_name[PATH_MAX]; 130 char socket_dir[PATH_MAX]; 131 132 /* PKCS#11 path whitelist */ 133 static char *pkcs11_whitelist; 134 135 /* locking */ 136 #define LOCK_SIZE 32 137 #define LOCK_SALT_SIZE 16 138 #define LOCK_ROUNDS 1 139 int locked = 0; 140 u_char lock_pwhash[LOCK_SIZE]; 141 u_char lock_salt[LOCK_SALT_SIZE]; 142 143 extern char *__progname; 144 145 /* Default lifetime in seconds (0 == forever) */ 146 static long lifetime = 0; 147 148 static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 149 150 static void 151 close_socket(SocketEntry *e) 152 { 153 close(e->fd); 154 e->fd = -1; 155 e->type = AUTH_UNUSED; 156 sshbuf_free(e->input); 157 sshbuf_free(e->output); 158 sshbuf_free(e->request); 159 } 160 161 static void 162 idtab_init(void) 163 { 164 idtab = xcalloc(1, sizeof(*idtab)); 165 TAILQ_INIT(&idtab->idlist); 166 idtab->nentries = 0; 167 } 168 169 static void 170 free_identity(Identity *id) 171 { 172 sshkey_free(id->key); 173 free(id->provider); 174 free(id->comment); 175 free(id); 176 } 177 178 /* return matching private key for given public key */ 179 static Identity * 180 lookup_identity(struct sshkey *key) 181 { 182 Identity *id; 183 184 TAILQ_FOREACH(id, &idtab->idlist, next) { 185 if (sshkey_equal(key, id->key)) 186 return (id); 187 } 188 return (NULL); 189 } 190 191 /* Check confirmation of keysign request */ 192 static int 193 confirm_key(Identity *id) 194 { 195 char *p; 196 int ret = -1; 197 198 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT); 199 if (p != NULL && 200 ask_permission("Allow use of key %s?\nKey fingerprint %s.", 201 id->comment, p)) 202 ret = 0; 203 free(p); 204 205 return (ret); 206 } 207 208 static void 209 send_status(SocketEntry *e, int success) 210 { 211 int r; 212 213 if ((r = sshbuf_put_u32(e->output, 1)) != 0 || 214 (r = sshbuf_put_u8(e->output, success ? 215 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0) 216 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 217 } 218 219 /* send list of supported public keys to 'client' */ 220 static void 221 process_request_identities(SocketEntry *e) 222 { 223 Identity *id; 224 struct sshbuf *msg; 225 int r; 226 227 if ((msg = sshbuf_new()) == NULL) 228 fatal("%s: sshbuf_new failed", __func__); 229 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 230 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0) 231 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 232 TAILQ_FOREACH(id, &idtab->idlist, next) { 233 if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO)) 234 != 0 || 235 (r = sshbuf_put_cstring(msg, id->comment)) != 0) { 236 error("%s: put key/comment: %s", __func__, 237 ssh_err(r)); 238 continue; 239 } 240 } 241 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 242 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 243 sshbuf_free(msg); 244 } 245 246 247 static char * 248 agent_decode_alg(struct sshkey *key, u_int flags) 249 { 250 if (key->type == KEY_RSA) { 251 if (flags & SSH_AGENT_RSA_SHA2_256) 252 return "rsa-sha2-256"; 253 else if (flags & SSH_AGENT_RSA_SHA2_512) 254 return "rsa-sha2-512"; 255 } 256 return NULL; 257 } 258 259 /* ssh2 only */ 260 static void 261 process_sign_request2(SocketEntry *e) 262 { 263 const u_char *data; 264 u_char *signature = NULL; 265 size_t dlen, slen = 0; 266 u_int compat = 0, flags; 267 int r, ok = -1; 268 struct sshbuf *msg; 269 struct sshkey *key = NULL; 270 struct identity *id; 271 272 if ((msg = sshbuf_new()) == NULL) 273 fatal("%s: sshbuf_new failed", __func__); 274 if ((r = sshkey_froms(e->request, &key)) != 0 || 275 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 || 276 (r = sshbuf_get_u32(e->request, &flags)) != 0) { 277 error("%s: couldn't parse request: %s", __func__, ssh_err(r)); 278 goto send; 279 } 280 281 if ((id = lookup_identity(key)) == NULL) { 282 verbose("%s: %s key not found", __func__, sshkey_type(key)); 283 goto send; 284 } 285 if (id->confirm && confirm_key(id) != 0) { 286 verbose("%s: user refused key", __func__); 287 goto send; 288 } 289 if ((r = sshkey_sign(id->key, &signature, &slen, 290 data, dlen, agent_decode_alg(key, flags), compat)) != 0) { 291 error("%s: sshkey_sign: %s", __func__, ssh_err(r)); 292 goto send; 293 } 294 /* Success */ 295 ok = 0; 296 send: 297 sshkey_free(key); 298 if (ok == 0) { 299 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 || 300 (r = sshbuf_put_string(msg, signature, slen)) != 0) 301 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 302 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0) 303 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 304 305 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 306 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 307 308 sshbuf_free(msg); 309 free(signature); 310 } 311 312 /* shared */ 313 static void 314 process_remove_identity(SocketEntry *e) 315 { 316 int r, success = 0; 317 struct sshkey *key = NULL; 318 Identity *id; 319 320 if ((r = sshkey_froms(e->request, &key)) != 0) { 321 error("%s: get key: %s", __func__, ssh_err(r)); 322 goto done; 323 } 324 if ((id = lookup_identity(key)) == NULL) { 325 debug("%s: key not found", __func__); 326 goto done; 327 } 328 /* We have this key, free it. */ 329 if (idtab->nentries < 1) 330 fatal("%s: internal error: nentries %d", 331 __func__, idtab->nentries); 332 TAILQ_REMOVE(&idtab->idlist, id, next); 333 free_identity(id); 334 idtab->nentries--; 335 sshkey_free(key); 336 success = 1; 337 done: 338 send_status(e, success); 339 } 340 341 static void 342 process_remove_all_identities(SocketEntry *e) 343 { 344 Identity *id; 345 346 /* Loop over all identities and clear the keys. */ 347 for (id = TAILQ_FIRST(&idtab->idlist); id; 348 id = TAILQ_FIRST(&idtab->idlist)) { 349 TAILQ_REMOVE(&idtab->idlist, id, next); 350 free_identity(id); 351 } 352 353 /* Mark that there are no identities. */ 354 idtab->nentries = 0; 355 356 /* Send success. */ 357 send_status(e, 1); 358 } 359 360 /* removes expired keys and returns number of seconds until the next expiry */ 361 static time_t 362 reaper(void) 363 { 364 time_t deadline = 0, now = monotime(); 365 Identity *id, *nxt; 366 367 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 368 nxt = TAILQ_NEXT(id, next); 369 if (id->death == 0) 370 continue; 371 if (now >= id->death) { 372 debug("expiring key '%s'", id->comment); 373 TAILQ_REMOVE(&idtab->idlist, id, next); 374 free_identity(id); 375 idtab->nentries--; 376 } else 377 deadline = (deadline == 0) ? id->death : 378 MINIMUM(deadline, id->death); 379 } 380 if (deadline == 0 || deadline <= now) 381 return 0; 382 else 383 return (deadline - now); 384 } 385 386 static void 387 process_add_identity(SocketEntry *e) 388 { 389 Identity *id; 390 int success = 0, confirm = 0; 391 u_int seconds, maxsign; 392 char *comment = NULL; 393 time_t death = 0; 394 struct sshkey *k = NULL; 395 u_char ctype; 396 int r = SSH_ERR_INTERNAL_ERROR; 397 398 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 || 399 k == NULL || 400 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) { 401 error("%s: decode private key: %s", __func__, ssh_err(r)); 402 goto err; 403 } 404 405 while (sshbuf_len(e->request)) { 406 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) { 407 error("%s: buffer error: %s", __func__, ssh_err(r)); 408 goto err; 409 } 410 switch (ctype) { 411 case SSH_AGENT_CONSTRAIN_LIFETIME: 412 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) { 413 error("%s: bad lifetime constraint: %s", 414 __func__, ssh_err(r)); 415 goto err; 416 } 417 death = monotime() + seconds; 418 break; 419 case SSH_AGENT_CONSTRAIN_CONFIRM: 420 confirm = 1; 421 break; 422 case SSH_AGENT_CONSTRAIN_MAXSIGN: 423 if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) { 424 error("%s: bad maxsign constraint: %s", 425 __func__, ssh_err(r)); 426 goto err; 427 } 428 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) { 429 error("%s: cannot enable maxsign: %s", 430 __func__, ssh_err(r)); 431 goto err; 432 } 433 break; 434 default: 435 error("%s: Unknown constraint %d", __func__, ctype); 436 err: 437 sshbuf_reset(e->request); 438 free(comment); 439 sshkey_free(k); 440 goto send; 441 } 442 } 443 444 success = 1; 445 if (lifetime && !death) 446 death = monotime() + lifetime; 447 if ((id = lookup_identity(k)) == NULL) { 448 id = xcalloc(1, sizeof(Identity)); 449 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 450 /* Increment the number of identities. */ 451 idtab->nentries++; 452 } else { 453 /* key state might have been updated */ 454 sshkey_free(id->key); 455 free(id->comment); 456 } 457 id->key = k; 458 id->comment = comment; 459 id->death = death; 460 id->confirm = confirm; 461 send: 462 send_status(e, success); 463 } 464 465 /* XXX todo: encrypt sensitive data with passphrase */ 466 static void 467 process_lock_agent(SocketEntry *e, int lock) 468 { 469 int r, success = 0, delay; 470 char *passwd; 471 u_char passwdhash[LOCK_SIZE]; 472 static u_int fail_count = 0; 473 size_t pwlen; 474 475 /* 476 * This is deliberately fatal: the user has requested that we lock, 477 * but we can't parse their request properly. The only safe thing to 478 * do is abort. 479 */ 480 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0) 481 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 482 if (pwlen == 0) { 483 debug("empty password not supported"); 484 } else if (locked && !lock) { 485 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 486 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0) 487 fatal("bcrypt_pbkdf"); 488 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) { 489 debug("agent unlocked"); 490 locked = 0; 491 fail_count = 0; 492 explicit_bzero(lock_pwhash, sizeof(lock_pwhash)); 493 success = 1; 494 } else { 495 /* delay in 0.1s increments up to 10s */ 496 if (fail_count < 100) 497 fail_count++; 498 delay = 100000 * fail_count; 499 debug("unlock failed, delaying %0.1lf seconds", 500 (double)delay/1000000); 501 usleep(delay); 502 } 503 explicit_bzero(passwdhash, sizeof(passwdhash)); 504 } else if (!locked && lock) { 505 debug("agent locked"); 506 locked = 1; 507 arc4random_buf(lock_salt, sizeof(lock_salt)); 508 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 509 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0) 510 fatal("bcrypt_pbkdf"); 511 success = 1; 512 } 513 explicit_bzero(passwd, pwlen); 514 free(passwd); 515 send_status(e, success); 516 } 517 518 static void 519 no_identities(SocketEntry *e) 520 { 521 struct sshbuf *msg; 522 int r; 523 524 if ((msg = sshbuf_new()) == NULL) 525 fatal("%s: sshbuf_new failed", __func__); 526 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 527 (r = sshbuf_put_u32(msg, 0)) != 0 || 528 (r = sshbuf_put_stringb(e->output, msg)) != 0) 529 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 530 sshbuf_free(msg); 531 } 532 533 #ifdef ENABLE_PKCS11 534 static void 535 process_add_smartcard_key(SocketEntry *e) 536 { 537 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 538 int r, i, count = 0, success = 0, confirm = 0; 539 u_int seconds; 540 time_t death = 0; 541 u_char type; 542 struct sshkey **keys = NULL, *k; 543 Identity *id; 544 545 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 546 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 547 error("%s: buffer error: %s", __func__, ssh_err(r)); 548 goto send; 549 } 550 551 while (sshbuf_len(e->request)) { 552 if ((r = sshbuf_get_u8(e->request, &type)) != 0) { 553 error("%s: buffer error: %s", __func__, ssh_err(r)); 554 goto send; 555 } 556 switch (type) { 557 case SSH_AGENT_CONSTRAIN_LIFETIME: 558 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) { 559 error("%s: buffer error: %s", 560 __func__, ssh_err(r)); 561 goto send; 562 } 563 death = monotime() + seconds; 564 break; 565 case SSH_AGENT_CONSTRAIN_CONFIRM: 566 confirm = 1; 567 break; 568 default: 569 error("%s: Unknown constraint type %d", __func__, type); 570 goto send; 571 } 572 } 573 if (realpath(provider, canonical_provider) == NULL) { 574 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 575 provider, strerror(errno)); 576 goto send; 577 } 578 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) { 579 verbose("refusing PKCS#11 add of \"%.100s\": " 580 "provider not whitelisted", canonical_provider); 581 goto send; 582 } 583 debug("%s: add %.100s", __func__, canonical_provider); 584 if (lifetime && !death) 585 death = monotime() + lifetime; 586 587 count = pkcs11_add_provider(canonical_provider, pin, &keys); 588 for (i = 0; i < count; i++) { 589 k = keys[i]; 590 if (lookup_identity(k) == NULL) { 591 id = xcalloc(1, sizeof(Identity)); 592 id->key = k; 593 id->provider = xstrdup(canonical_provider); 594 id->comment = xstrdup(canonical_provider); /* XXX */ 595 id->death = death; 596 id->confirm = confirm; 597 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 598 idtab->nentries++; 599 success = 1; 600 } else { 601 sshkey_free(k); 602 } 603 keys[i] = NULL; 604 } 605 send: 606 free(pin); 607 free(provider); 608 free(keys); 609 send_status(e, success); 610 } 611 612 static void 613 process_remove_smartcard_key(SocketEntry *e) 614 { 615 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 616 int r, success = 0; 617 Identity *id, *nxt; 618 619 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 620 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 621 error("%s: buffer error: %s", __func__, ssh_err(r)); 622 goto send; 623 } 624 free(pin); 625 626 if (realpath(provider, canonical_provider) == NULL) { 627 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 628 provider, strerror(errno)); 629 goto send; 630 } 631 632 debug("%s: remove %.100s", __func__, canonical_provider); 633 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 634 nxt = TAILQ_NEXT(id, next); 635 /* Skip file--based keys */ 636 if (id->provider == NULL) 637 continue; 638 if (!strcmp(canonical_provider, id->provider)) { 639 TAILQ_REMOVE(&idtab->idlist, id, next); 640 free_identity(id); 641 idtab->nentries--; 642 } 643 } 644 if (pkcs11_del_provider(canonical_provider) == 0) 645 success = 1; 646 else 647 error("%s: pkcs11_del_provider failed", __func__); 648 send: 649 free(provider); 650 send_status(e, success); 651 } 652 #endif /* ENABLE_PKCS11 */ 653 654 /* dispatch incoming messages */ 655 656 static int 657 process_message(u_int socknum) 658 { 659 u_int msg_len; 660 u_char type; 661 const u_char *cp; 662 int r; 663 SocketEntry *e; 664 665 if (socknum >= sockets_alloc) { 666 fatal("%s: socket number %u >= allocated %u", 667 __func__, socknum, sockets_alloc); 668 } 669 e = &sockets[socknum]; 670 671 if (sshbuf_len(e->input) < 5) 672 return 0; /* Incomplete message header. */ 673 cp = sshbuf_ptr(e->input); 674 msg_len = PEEK_U32(cp); 675 if (msg_len > AGENT_MAX_LEN) { 676 debug("%s: socket %u (fd=%d) message too long %u > %u", 677 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN); 678 return -1; 679 } 680 if (sshbuf_len(e->input) < msg_len + 4) 681 return 0; /* Incomplete message body. */ 682 683 /* move the current input to e->request */ 684 sshbuf_reset(e->request); 685 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 || 686 (r = sshbuf_get_u8(e->request, &type)) != 0) { 687 if (r == SSH_ERR_MESSAGE_INCOMPLETE || 688 r == SSH_ERR_STRING_TOO_LARGE) { 689 debug("%s: buffer error: %s", __func__, ssh_err(r)); 690 return -1; 691 } 692 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 693 } 694 695 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type); 696 697 /* check whether agent is locked */ 698 if (locked && type != SSH_AGENTC_UNLOCK) { 699 sshbuf_reset(e->request); 700 switch (type) { 701 case SSH2_AGENTC_REQUEST_IDENTITIES: 702 /* send empty lists */ 703 no_identities(e); 704 break; 705 default: 706 /* send a fail message for all other request types */ 707 send_status(e, 0); 708 } 709 return 0; 710 } 711 712 switch (type) { 713 case SSH_AGENTC_LOCK: 714 case SSH_AGENTC_UNLOCK: 715 process_lock_agent(e, type == SSH_AGENTC_LOCK); 716 break; 717 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES: 718 process_remove_all_identities(e); /* safe for !WITH_SSH1 */ 719 break; 720 /* ssh2 */ 721 case SSH2_AGENTC_SIGN_REQUEST: 722 process_sign_request2(e); 723 break; 724 case SSH2_AGENTC_REQUEST_IDENTITIES: 725 process_request_identities(e); 726 break; 727 case SSH2_AGENTC_ADD_IDENTITY: 728 case SSH2_AGENTC_ADD_ID_CONSTRAINED: 729 process_add_identity(e); 730 break; 731 case SSH2_AGENTC_REMOVE_IDENTITY: 732 process_remove_identity(e); 733 break; 734 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: 735 process_remove_all_identities(e); 736 break; 737 #ifdef ENABLE_PKCS11 738 case SSH_AGENTC_ADD_SMARTCARD_KEY: 739 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED: 740 process_add_smartcard_key(e); 741 break; 742 case SSH_AGENTC_REMOVE_SMARTCARD_KEY: 743 process_remove_smartcard_key(e); 744 break; 745 #endif /* ENABLE_PKCS11 */ 746 default: 747 /* Unknown message. Respond with failure. */ 748 error("Unknown message %d", type); 749 sshbuf_reset(e->request); 750 send_status(e, 0); 751 break; 752 } 753 return 0; 754 } 755 756 static void 757 new_socket(sock_type type, int fd) 758 { 759 u_int i, old_alloc, new_alloc; 760 761 set_nonblock(fd); 762 763 if (fd > max_fd) 764 max_fd = fd; 765 766 for (i = 0; i < sockets_alloc; i++) 767 if (sockets[i].type == AUTH_UNUSED) { 768 sockets[i].fd = fd; 769 if ((sockets[i].input = sshbuf_new()) == NULL) 770 fatal("%s: sshbuf_new failed", __func__); 771 if ((sockets[i].output = sshbuf_new()) == NULL) 772 fatal("%s: sshbuf_new failed", __func__); 773 if ((sockets[i].request = sshbuf_new()) == NULL) 774 fatal("%s: sshbuf_new failed", __func__); 775 sockets[i].type = type; 776 return; 777 } 778 old_alloc = sockets_alloc; 779 new_alloc = sockets_alloc + 10; 780 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0])); 781 for (i = old_alloc; i < new_alloc; i++) 782 sockets[i].type = AUTH_UNUSED; 783 sockets_alloc = new_alloc; 784 sockets[old_alloc].fd = fd; 785 if ((sockets[old_alloc].input = sshbuf_new()) == NULL) 786 fatal("%s: sshbuf_new failed", __func__); 787 if ((sockets[old_alloc].output = sshbuf_new()) == NULL) 788 fatal("%s: sshbuf_new failed", __func__); 789 if ((sockets[old_alloc].request = sshbuf_new()) == NULL) 790 fatal("%s: sshbuf_new failed", __func__); 791 sockets[old_alloc].type = type; 792 } 793 794 static int 795 handle_socket_read(u_int socknum) 796 { 797 struct sockaddr_un sunaddr; 798 socklen_t slen; 799 uid_t euid; 800 gid_t egid; 801 int fd; 802 803 slen = sizeof(sunaddr); 804 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen); 805 if (fd < 0) { 806 error("accept from AUTH_SOCKET: %s", strerror(errno)); 807 return -1; 808 } 809 if (getpeereid(fd, &euid, &egid) < 0) { 810 error("getpeereid %d failed: %s", fd, strerror(errno)); 811 close(fd); 812 return -1; 813 } 814 if ((euid != 0) && (getuid() != euid)) { 815 error("uid mismatch: peer euid %u != uid %u", 816 (u_int) euid, (u_int) getuid()); 817 close(fd); 818 return -1; 819 } 820 new_socket(AUTH_CONNECTION, fd); 821 return 0; 822 } 823 824 static int 825 handle_conn_read(u_int socknum) 826 { 827 char buf[1024]; 828 ssize_t len; 829 int r; 830 831 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) { 832 if (len == -1) { 833 if (errno == EAGAIN || errno == EINTR) 834 return 0; 835 error("%s: read error on socket %u (fd %d): %s", 836 __func__, socknum, sockets[socknum].fd, 837 strerror(errno)); 838 } 839 return -1; 840 } 841 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0) 842 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 843 explicit_bzero(buf, sizeof(buf)); 844 process_message(socknum); 845 return 0; 846 } 847 848 static int 849 handle_conn_write(u_int socknum) 850 { 851 ssize_t len; 852 int r; 853 854 if (sshbuf_len(sockets[socknum].output) == 0) 855 return 0; /* shouldn't happen */ 856 if ((len = write(sockets[socknum].fd, 857 sshbuf_ptr(sockets[socknum].output), 858 sshbuf_len(sockets[socknum].output))) <= 0) { 859 if (len == -1) { 860 if (errno == EAGAIN || errno == EINTR) 861 return 0; 862 error("%s: read error on socket %u (fd %d): %s", 863 __func__, socknum, sockets[socknum].fd, 864 strerror(errno)); 865 } 866 return -1; 867 } 868 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0) 869 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 870 return 0; 871 } 872 873 static void 874 after_poll(struct pollfd *pfd, size_t npfd) 875 { 876 size_t i; 877 u_int socknum; 878 879 for (i = 0; i < npfd; i++) { 880 if (pfd[i].revents == 0) 881 continue; 882 /* Find sockets entry */ 883 for (socknum = 0; socknum < sockets_alloc; socknum++) { 884 if (sockets[socknum].type != AUTH_SOCKET && 885 sockets[socknum].type != AUTH_CONNECTION) 886 continue; 887 if (pfd[i].fd == sockets[socknum].fd) 888 break; 889 } 890 if (socknum >= sockets_alloc) { 891 error("%s: no socket for fd %d", __func__, pfd[i].fd); 892 continue; 893 } 894 /* Process events */ 895 switch (sockets[socknum].type) { 896 case AUTH_SOCKET: 897 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0) 898 handle_socket_read(socknum); 899 break; 900 case AUTH_CONNECTION: 901 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 && 902 handle_conn_read(socknum) != 0) { 903 close_socket(&sockets[socknum]); 904 break; 905 } 906 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 && 907 handle_conn_write(socknum) != 0) 908 close_socket(&sockets[socknum]); 909 break; 910 default: 911 break; 912 } 913 } 914 } 915 916 static int 917 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp) 918 { 919 struct pollfd *pfd = *pfdp; 920 size_t i, j, npfd = 0; 921 time_t deadline; 922 923 /* Count active sockets */ 924 for (i = 0; i < sockets_alloc; i++) { 925 switch (sockets[i].type) { 926 case AUTH_SOCKET: 927 case AUTH_CONNECTION: 928 npfd++; 929 break; 930 case AUTH_UNUSED: 931 break; 932 default: 933 fatal("Unknown socket type %d", sockets[i].type); 934 break; 935 } 936 } 937 if (npfd != *npfdp && 938 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL) 939 fatal("%s: recallocarray failed", __func__); 940 *pfdp = pfd; 941 *npfdp = npfd; 942 943 for (i = j = 0; i < sockets_alloc; i++) { 944 switch (sockets[i].type) { 945 case AUTH_SOCKET: 946 case AUTH_CONNECTION: 947 pfd[j].fd = sockets[i].fd; 948 pfd[j].revents = 0; 949 /* XXX backoff when input buffer full */ 950 pfd[j].events = POLLIN; 951 if (sshbuf_len(sockets[i].output) > 0) 952 pfd[j].events |= POLLOUT; 953 j++; 954 break; 955 default: 956 break; 957 } 958 } 959 deadline = reaper(); 960 if (parent_alive_interval != 0) 961 deadline = (deadline == 0) ? parent_alive_interval : 962 MINIMUM(deadline, parent_alive_interval); 963 if (deadline == 0) { 964 *timeoutp = -1; /* INFTIM */ 965 } else { 966 if (deadline > INT_MAX / 1000) 967 *timeoutp = INT_MAX / 1000; 968 else 969 *timeoutp = deadline * 1000; 970 } 971 return (1); 972 } 973 974 static void 975 cleanup_socket(void) 976 { 977 if (cleanup_pid != 0 && getpid() != cleanup_pid) 978 return; 979 debug("%s: cleanup", __func__); 980 if (socket_name[0]) 981 unlink(socket_name); 982 if (socket_dir[0]) 983 rmdir(socket_dir); 984 } 985 986 void 987 cleanup_exit(int i) 988 { 989 cleanup_socket(); 990 _exit(i); 991 } 992 993 /*ARGSUSED*/ 994 static void 995 cleanup_handler(int sig) 996 { 997 cleanup_socket(); 998 #ifdef ENABLE_PKCS11 999 pkcs11_terminate(); 1000 #endif 1001 _exit(2); 1002 } 1003 1004 static void 1005 check_parent_exists(void) 1006 { 1007 /* 1008 * If our parent has exited then getppid() will return (pid_t)1, 1009 * so testing for that should be safe. 1010 */ 1011 if (parent_pid != -1 && getppid() != parent_pid) { 1012 /* printf("Parent has died - Authentication agent exiting.\n"); */ 1013 cleanup_socket(); 1014 _exit(2); 1015 } 1016 } 1017 1018 static void 1019 usage(void) 1020 { 1021 fprintf(stderr, 1022 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" 1023 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n" 1024 " ssh-agent [-c | -s] -k\n"); 1025 exit(1); 1026 } 1027 1028 int 1029 main(int ac, char **av) 1030 { 1031 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0; 1032 int sock, fd, ch, result, saved_errno; 1033 char *shell, *format, *pidstr, *agentsocket = NULL; 1034 struct rlimit rlim; 1035 extern int optind; 1036 extern char *optarg; 1037 pid_t pid; 1038 char pidstrbuf[1 + 3 * sizeof pid]; 1039 size_t len; 1040 mode_t prev_mask; 1041 int timeout = -1; /* INFTIM */ 1042 struct pollfd *pfd = NULL; 1043 size_t npfd = 0; 1044 1045 ssh_malloc_init(); /* must be called before any mallocs */ 1046 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1047 sanitise_stdfd(); 1048 1049 /* drop */ 1050 setegid(getgid()); 1051 setgid(getgid()); 1052 1053 #ifdef WITH_OPENSSL 1054 OpenSSL_add_all_algorithms(); 1055 #endif 1056 1057 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) { 1058 switch (ch) { 1059 case 'E': 1060 fingerprint_hash = ssh_digest_alg_by_name(optarg); 1061 if (fingerprint_hash == -1) 1062 fatal("Invalid hash algorithm \"%s\"", optarg); 1063 break; 1064 case 'c': 1065 if (s_flag) 1066 usage(); 1067 c_flag++; 1068 break; 1069 case 'k': 1070 k_flag++; 1071 break; 1072 case 'P': 1073 if (pkcs11_whitelist != NULL) 1074 fatal("-P option already specified"); 1075 pkcs11_whitelist = xstrdup(optarg); 1076 break; 1077 case 's': 1078 if (c_flag) 1079 usage(); 1080 s_flag++; 1081 break; 1082 case 'd': 1083 if (d_flag || D_flag) 1084 usage(); 1085 d_flag++; 1086 break; 1087 case 'D': 1088 if (d_flag || D_flag) 1089 usage(); 1090 D_flag++; 1091 break; 1092 case 'a': 1093 agentsocket = optarg; 1094 break; 1095 case 't': 1096 if ((lifetime = convtime(optarg)) == -1) { 1097 fprintf(stderr, "Invalid lifetime\n"); 1098 usage(); 1099 } 1100 break; 1101 default: 1102 usage(); 1103 } 1104 } 1105 ac -= optind; 1106 av += optind; 1107 1108 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag)) 1109 usage(); 1110 1111 if (pkcs11_whitelist == NULL) 1112 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST); 1113 1114 if (ac == 0 && !c_flag && !s_flag) { 1115 shell = getenv("SHELL"); 1116 if (shell != NULL && (len = strlen(shell)) > 2 && 1117 strncmp(shell + len - 3, "csh", 3) == 0) 1118 c_flag = 1; 1119 } 1120 if (k_flag) { 1121 const char *errstr = NULL; 1122 1123 pidstr = getenv(SSH_AGENTPID_ENV_NAME); 1124 if (pidstr == NULL) { 1125 fprintf(stderr, "%s not set, cannot kill agent\n", 1126 SSH_AGENTPID_ENV_NAME); 1127 exit(1); 1128 } 1129 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr); 1130 if (errstr) { 1131 fprintf(stderr, 1132 "%s=\"%s\", which is not a good PID: %s\n", 1133 SSH_AGENTPID_ENV_NAME, pidstr, errstr); 1134 exit(1); 1135 } 1136 if (kill(pid, SIGTERM) == -1) { 1137 perror("kill"); 1138 exit(1); 1139 } 1140 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n"; 1141 printf(format, SSH_AUTHSOCKET_ENV_NAME); 1142 printf(format, SSH_AGENTPID_ENV_NAME); 1143 printf("echo Agent pid %ld killed;\n", (long)pid); 1144 exit(0); 1145 } 1146 parent_pid = getpid(); 1147 1148 if (agentsocket == NULL) { 1149 /* Create private directory for agent socket */ 1150 mktemp_proto(socket_dir, sizeof(socket_dir)); 1151 if (mkdtemp(socket_dir) == NULL) { 1152 perror("mkdtemp: private socket dir"); 1153 exit(1); 1154 } 1155 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir, 1156 (long)parent_pid); 1157 } else { 1158 /* Try to use specified agent socket */ 1159 socket_dir[0] = '\0'; 1160 strlcpy(socket_name, agentsocket, sizeof socket_name); 1161 } 1162 1163 /* 1164 * Create socket early so it will exist before command gets run from 1165 * the parent. 1166 */ 1167 prev_mask = umask(0177); 1168 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0); 1169 if (sock < 0) { 1170 /* XXX - unix_listener() calls error() not perror() */ 1171 *socket_name = '\0'; /* Don't unlink any existing file */ 1172 cleanup_exit(1); 1173 } 1174 umask(prev_mask); 1175 1176 /* 1177 * Fork, and have the parent execute the command, if any, or present 1178 * the socket data. The child continues as the authentication agent. 1179 */ 1180 if (D_flag || d_flag) { 1181 log_init(__progname, 1182 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 1183 SYSLOG_FACILITY_AUTH, 1); 1184 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 1185 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 1186 SSH_AUTHSOCKET_ENV_NAME); 1187 printf("echo Agent pid %ld;\n", (long)parent_pid); 1188 fflush(stdout); 1189 goto skip; 1190 } 1191 pid = fork(); 1192 if (pid == -1) { 1193 perror("fork"); 1194 cleanup_exit(1); 1195 } 1196 if (pid != 0) { /* Parent - execute the given command. */ 1197 close(sock); 1198 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid); 1199 if (ac == 0) { 1200 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 1201 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 1202 SSH_AUTHSOCKET_ENV_NAME); 1203 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf, 1204 SSH_AGENTPID_ENV_NAME); 1205 printf("echo Agent pid %ld;\n", (long)pid); 1206 exit(0); 1207 } 1208 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 || 1209 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) { 1210 perror("setenv"); 1211 exit(1); 1212 } 1213 execvp(av[0], av); 1214 perror(av[0]); 1215 exit(1); 1216 } 1217 /* child */ 1218 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0); 1219 1220 if (setsid() == -1) { 1221 error("setsid: %s", strerror(errno)); 1222 cleanup_exit(1); 1223 } 1224 1225 (void)chdir("/"); 1226 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 1227 /* XXX might close listen socket */ 1228 (void)dup2(fd, STDIN_FILENO); 1229 (void)dup2(fd, STDOUT_FILENO); 1230 (void)dup2(fd, STDERR_FILENO); 1231 if (fd > 2) 1232 close(fd); 1233 } 1234 1235 /* deny core dumps, since memory contains unencrypted private keys */ 1236 rlim.rlim_cur = rlim.rlim_max = 0; 1237 if (setrlimit(RLIMIT_CORE, &rlim) < 0) { 1238 error("setrlimit RLIMIT_CORE: %s", strerror(errno)); 1239 cleanup_exit(1); 1240 } 1241 1242 skip: 1243 1244 cleanup_pid = getpid(); 1245 1246 #ifdef ENABLE_PKCS11 1247 pkcs11_init(0); 1248 #endif 1249 new_socket(AUTH_SOCKET, sock); 1250 if (ac > 0) 1251 parent_alive_interval = 10; 1252 idtab_init(); 1253 signal(SIGPIPE, SIG_IGN); 1254 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN); 1255 signal(SIGHUP, cleanup_handler); 1256 signal(SIGTERM, cleanup_handler); 1257 1258 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1) 1259 fatal("%s: pledge: %s", __progname, strerror(errno)); 1260 1261 while (1) { 1262 prepare_poll(&pfd, &npfd, &timeout); 1263 result = poll(pfd, npfd, timeout); 1264 saved_errno = errno; 1265 if (parent_alive_interval != 0) 1266 check_parent_exists(); 1267 (void) reaper(); /* remove expired keys */ 1268 if (result < 0) { 1269 if (saved_errno == EINTR) 1270 continue; 1271 fatal("poll: %s", strerror(saved_errno)); 1272 } else if (result > 0) 1273 after_poll(pfd, npfd); 1274 } 1275 /* NOTREACHED */ 1276 } 1277