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