1 /* $OpenBSD: ssh-agent.c,v 1.231 2018/05/11 03:38:51 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, u_int maxfds) 875 { 876 size_t i; 877 u_int socknum, activefds = npfd; 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 break; 899 if (npfd > maxfds) { 900 debug3("out of fds (active %u >= limit %u); " 901 "skipping accept", activefds, maxfds); 902 break; 903 } 904 if (handle_socket_read(socknum) == 0) 905 activefds++; 906 break; 907 case AUTH_CONNECTION: 908 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 && 909 handle_conn_read(socknum) != 0) { 910 goto close_sock; 911 } 912 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 && 913 handle_conn_write(socknum) != 0) { 914 close_sock: 915 if (activefds == 0) 916 fatal("activefds == 0 at close_sock"); 917 close_socket(&sockets[socknum]); 918 activefds--; 919 break; 920 } 921 break; 922 default: 923 break; 924 } 925 } 926 } 927 928 static int 929 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds) 930 { 931 struct pollfd *pfd = *pfdp; 932 size_t i, j, npfd = 0; 933 time_t deadline; 934 935 /* Count active sockets */ 936 for (i = 0; i < sockets_alloc; i++) { 937 switch (sockets[i].type) { 938 case AUTH_SOCKET: 939 case AUTH_CONNECTION: 940 npfd++; 941 break; 942 case AUTH_UNUSED: 943 break; 944 default: 945 fatal("Unknown socket type %d", sockets[i].type); 946 break; 947 } 948 } 949 if (npfd != *npfdp && 950 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL) 951 fatal("%s: recallocarray failed", __func__); 952 *pfdp = pfd; 953 *npfdp = npfd; 954 955 for (i = j = 0; i < sockets_alloc; i++) { 956 switch (sockets[i].type) { 957 case AUTH_SOCKET: 958 if (npfd > maxfds) { 959 debug3("out of fds (active %zu >= limit %u); " 960 "skipping arming listener", npfd, maxfds); 961 break; 962 } 963 pfd[j].fd = sockets[i].fd; 964 pfd[j].revents = 0; 965 pfd[j].events = POLLIN; 966 j++; 967 break; 968 case AUTH_CONNECTION: 969 pfd[j].fd = sockets[i].fd; 970 pfd[j].revents = 0; 971 /* XXX backoff when input buffer full */ 972 pfd[j].events = POLLIN; 973 if (sshbuf_len(sockets[i].output) > 0) 974 pfd[j].events |= POLLOUT; 975 j++; 976 break; 977 default: 978 break; 979 } 980 } 981 deadline = reaper(); 982 if (parent_alive_interval != 0) 983 deadline = (deadline == 0) ? parent_alive_interval : 984 MINIMUM(deadline, parent_alive_interval); 985 if (deadline == 0) { 986 *timeoutp = -1; /* INFTIM */ 987 } else { 988 if (deadline > INT_MAX / 1000) 989 *timeoutp = INT_MAX / 1000; 990 else 991 *timeoutp = deadline * 1000; 992 } 993 return (1); 994 } 995 996 static void 997 cleanup_socket(void) 998 { 999 if (cleanup_pid != 0 && getpid() != cleanup_pid) 1000 return; 1001 debug("%s: cleanup", __func__); 1002 if (socket_name[0]) 1003 unlink(socket_name); 1004 if (socket_dir[0]) 1005 rmdir(socket_dir); 1006 } 1007 1008 void 1009 cleanup_exit(int i) 1010 { 1011 cleanup_socket(); 1012 _exit(i); 1013 } 1014 1015 /*ARGSUSED*/ 1016 static void 1017 cleanup_handler(int sig) 1018 { 1019 cleanup_socket(); 1020 #ifdef ENABLE_PKCS11 1021 pkcs11_terminate(); 1022 #endif 1023 _exit(2); 1024 } 1025 1026 static void 1027 check_parent_exists(void) 1028 { 1029 /* 1030 * If our parent has exited then getppid() will return (pid_t)1, 1031 * so testing for that should be safe. 1032 */ 1033 if (parent_pid != -1 && getppid() != parent_pid) { 1034 /* printf("Parent has died - Authentication agent exiting.\n"); */ 1035 cleanup_socket(); 1036 _exit(2); 1037 } 1038 } 1039 1040 static void 1041 usage(void) 1042 { 1043 fprintf(stderr, 1044 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" 1045 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n" 1046 " ssh-agent [-c | -s] -k\n"); 1047 exit(1); 1048 } 1049 1050 int 1051 main(int ac, char **av) 1052 { 1053 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0; 1054 int sock, fd, ch, result, saved_errno; 1055 char *shell, *format, *pidstr, *agentsocket = NULL; 1056 struct rlimit rlim; 1057 extern int optind; 1058 extern char *optarg; 1059 pid_t pid; 1060 char pidstrbuf[1 + 3 * sizeof pid]; 1061 size_t len; 1062 mode_t prev_mask; 1063 int timeout = -1; /* INFTIM */ 1064 struct pollfd *pfd = NULL; 1065 size_t npfd = 0; 1066 u_int maxfds; 1067 1068 ssh_malloc_init(); /* must be called before any mallocs */ 1069 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1070 sanitise_stdfd(); 1071 1072 /* drop */ 1073 setegid(getgid()); 1074 setgid(getgid()); 1075 1076 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) 1077 fatal("%s: getrlimit: %s", __progname, strerror(errno)); 1078 1079 #ifdef WITH_OPENSSL 1080 OpenSSL_add_all_algorithms(); 1081 #endif 1082 1083 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) { 1084 switch (ch) { 1085 case 'E': 1086 fingerprint_hash = ssh_digest_alg_by_name(optarg); 1087 if (fingerprint_hash == -1) 1088 fatal("Invalid hash algorithm \"%s\"", optarg); 1089 break; 1090 case 'c': 1091 if (s_flag) 1092 usage(); 1093 c_flag++; 1094 break; 1095 case 'k': 1096 k_flag++; 1097 break; 1098 case 'P': 1099 if (pkcs11_whitelist != NULL) 1100 fatal("-P option already specified"); 1101 pkcs11_whitelist = xstrdup(optarg); 1102 break; 1103 case 's': 1104 if (c_flag) 1105 usage(); 1106 s_flag++; 1107 break; 1108 case 'd': 1109 if (d_flag || D_flag) 1110 usage(); 1111 d_flag++; 1112 break; 1113 case 'D': 1114 if (d_flag || D_flag) 1115 usage(); 1116 D_flag++; 1117 break; 1118 case 'a': 1119 agentsocket = optarg; 1120 break; 1121 case 't': 1122 if ((lifetime = convtime(optarg)) == -1) { 1123 fprintf(stderr, "Invalid lifetime\n"); 1124 usage(); 1125 } 1126 break; 1127 default: 1128 usage(); 1129 } 1130 } 1131 ac -= optind; 1132 av += optind; 1133 1134 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag)) 1135 usage(); 1136 1137 if (pkcs11_whitelist == NULL) 1138 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST); 1139 1140 if (ac == 0 && !c_flag && !s_flag) { 1141 shell = getenv("SHELL"); 1142 if (shell != NULL && (len = strlen(shell)) > 2 && 1143 strncmp(shell + len - 3, "csh", 3) == 0) 1144 c_flag = 1; 1145 } 1146 if (k_flag) { 1147 const char *errstr = NULL; 1148 1149 pidstr = getenv(SSH_AGENTPID_ENV_NAME); 1150 if (pidstr == NULL) { 1151 fprintf(stderr, "%s not set, cannot kill agent\n", 1152 SSH_AGENTPID_ENV_NAME); 1153 exit(1); 1154 } 1155 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr); 1156 if (errstr) { 1157 fprintf(stderr, 1158 "%s=\"%s\", which is not a good PID: %s\n", 1159 SSH_AGENTPID_ENV_NAME, pidstr, errstr); 1160 exit(1); 1161 } 1162 if (kill(pid, SIGTERM) == -1) { 1163 perror("kill"); 1164 exit(1); 1165 } 1166 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n"; 1167 printf(format, SSH_AUTHSOCKET_ENV_NAME); 1168 printf(format, SSH_AGENTPID_ENV_NAME); 1169 printf("echo Agent pid %ld killed;\n", (long)pid); 1170 exit(0); 1171 } 1172 1173 /* 1174 * Minimum file descriptors: 1175 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) + 1176 * a few spare for libc / stack protectors / sanitisers, etc. 1177 */ 1178 #define SSH_AGENT_MIN_FDS (3+1+1+1+4) 1179 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS) 1180 fatal("%s: file descriptior rlimit %lld too low (minimum %u)", 1181 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS); 1182 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS; 1183 1184 parent_pid = getpid(); 1185 1186 if (agentsocket == NULL) { 1187 /* Create private directory for agent socket */ 1188 mktemp_proto(socket_dir, sizeof(socket_dir)); 1189 if (mkdtemp(socket_dir) == NULL) { 1190 perror("mkdtemp: private socket dir"); 1191 exit(1); 1192 } 1193 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir, 1194 (long)parent_pid); 1195 } else { 1196 /* Try to use specified agent socket */ 1197 socket_dir[0] = '\0'; 1198 strlcpy(socket_name, agentsocket, sizeof socket_name); 1199 } 1200 1201 /* 1202 * Create socket early so it will exist before command gets run from 1203 * the parent. 1204 */ 1205 prev_mask = umask(0177); 1206 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0); 1207 if (sock < 0) { 1208 /* XXX - unix_listener() calls error() not perror() */ 1209 *socket_name = '\0'; /* Don't unlink any existing file */ 1210 cleanup_exit(1); 1211 } 1212 umask(prev_mask); 1213 1214 /* 1215 * Fork, and have the parent execute the command, if any, or present 1216 * the socket data. The child continues as the authentication agent. 1217 */ 1218 if (D_flag || d_flag) { 1219 log_init(__progname, 1220 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 1221 SYSLOG_FACILITY_AUTH, 1); 1222 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 1223 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 1224 SSH_AUTHSOCKET_ENV_NAME); 1225 printf("echo Agent pid %ld;\n", (long)parent_pid); 1226 fflush(stdout); 1227 goto skip; 1228 } 1229 pid = fork(); 1230 if (pid == -1) { 1231 perror("fork"); 1232 cleanup_exit(1); 1233 } 1234 if (pid != 0) { /* Parent - execute the given command. */ 1235 close(sock); 1236 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid); 1237 if (ac == 0) { 1238 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 1239 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 1240 SSH_AUTHSOCKET_ENV_NAME); 1241 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf, 1242 SSH_AGENTPID_ENV_NAME); 1243 printf("echo Agent pid %ld;\n", (long)pid); 1244 exit(0); 1245 } 1246 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 || 1247 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) { 1248 perror("setenv"); 1249 exit(1); 1250 } 1251 execvp(av[0], av); 1252 perror(av[0]); 1253 exit(1); 1254 } 1255 /* child */ 1256 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0); 1257 1258 if (setsid() == -1) { 1259 error("setsid: %s", strerror(errno)); 1260 cleanup_exit(1); 1261 } 1262 1263 (void)chdir("/"); 1264 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 1265 /* XXX might close listen socket */ 1266 (void)dup2(fd, STDIN_FILENO); 1267 (void)dup2(fd, STDOUT_FILENO); 1268 (void)dup2(fd, STDERR_FILENO); 1269 if (fd > 2) 1270 close(fd); 1271 } 1272 1273 /* deny core dumps, since memory contains unencrypted private keys */ 1274 rlim.rlim_cur = rlim.rlim_max = 0; 1275 if (setrlimit(RLIMIT_CORE, &rlim) < 0) { 1276 error("setrlimit RLIMIT_CORE: %s", strerror(errno)); 1277 cleanup_exit(1); 1278 } 1279 1280 skip: 1281 1282 cleanup_pid = getpid(); 1283 1284 #ifdef ENABLE_PKCS11 1285 pkcs11_init(0); 1286 #endif 1287 new_socket(AUTH_SOCKET, sock); 1288 if (ac > 0) 1289 parent_alive_interval = 10; 1290 idtab_init(); 1291 signal(SIGPIPE, SIG_IGN); 1292 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN); 1293 signal(SIGHUP, cleanup_handler); 1294 signal(SIGTERM, cleanup_handler); 1295 1296 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1) 1297 fatal("%s: pledge: %s", __progname, strerror(errno)); 1298 1299 while (1) { 1300 prepare_poll(&pfd, &npfd, &timeout, maxfds); 1301 result = poll(pfd, npfd, timeout); 1302 saved_errno = errno; 1303 if (parent_alive_interval != 0) 1304 check_parent_exists(); 1305 (void) reaper(); /* remove expired keys */ 1306 if (result < 0) { 1307 if (saved_errno == EINTR) 1308 continue; 1309 fatal("poll: %s", strerror(saved_errno)); 1310 } else if (result > 0) 1311 after_poll(pfd, npfd, maxfds); 1312 } 1313 /* NOTREACHED */ 1314 } 1315