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