1 /* $OpenBSD: ssh-agent.c,v 1.309 2024/11/06 22:51:26 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 #include <sys/wait.h> 45 46 #ifdef WITH_OPENSSL 47 #include <openssl/evp.h> 48 #endif 49 50 #include <errno.h> 51 #include <fcntl.h> 52 #include <paths.h> 53 #include <poll.h> 54 #include <signal.h> 55 #include <stdlib.h> 56 #include <stdio.h> 57 #include <string.h> 58 #include <stdarg.h> 59 #include <limits.h> 60 #include <time.h> 61 #include <unistd.h> 62 #include <util.h> 63 64 #include "xmalloc.h" 65 #include "ssh.h" 66 #include "ssh2.h" 67 #include "sshbuf.h" 68 #include "sshkey.h" 69 #include "authfd.h" 70 #include "log.h" 71 #include "misc.h" 72 #include "digest.h" 73 #include "ssherr.h" 74 #include "match.h" 75 #include "msg.h" 76 #include "pathnames.h" 77 #include "ssh-pkcs11.h" 78 #include "sk-api.h" 79 #include "myproposal.h" 80 81 #ifndef DEFAULT_ALLOWED_PROVIDERS 82 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*" 83 #endif 84 #ifndef DEFAULT_WEBSAFE_ALLOWLIST 85 # define DEFAULT_WEBSAFE_ALLOWLIST "ssh:*" 86 #endif 87 88 /* Maximum accepted message length */ 89 #define AGENT_MAX_LEN (256*1024) 90 /* Maximum bytes to read from client socket */ 91 #define AGENT_RBUF_LEN (4096) 92 /* Maximum number of recorded session IDs/hostkeys per connection */ 93 #define AGENT_MAX_SESSION_IDS 16 94 /* Maximum size of session ID */ 95 #define AGENT_MAX_SID_LEN 128 96 /* Maximum number of destination constraints to accept on a key */ 97 #define AGENT_MAX_DEST_CONSTRAINTS 1024 98 /* Maximum number of associated certificate constraints to accept on a key */ 99 #define AGENT_MAX_EXT_CERTS 1024 100 101 /* XXX store hostkey_sid in a refcounted tree */ 102 103 typedef enum { 104 AUTH_UNUSED = 0, 105 AUTH_SOCKET = 1, 106 AUTH_CONNECTION = 2, 107 } sock_type; 108 109 struct hostkey_sid { 110 struct sshkey *key; 111 struct sshbuf *sid; 112 int forwarded; 113 }; 114 115 typedef struct socket_entry { 116 int fd; 117 sock_type type; 118 struct sshbuf *input; 119 struct sshbuf *output; 120 struct sshbuf *request; 121 size_t nsession_ids; 122 struct hostkey_sid *session_ids; 123 int session_bind_attempted; 124 } SocketEntry; 125 126 u_int sockets_alloc = 0; 127 SocketEntry *sockets = NULL; 128 129 typedef struct identity { 130 TAILQ_ENTRY(identity) next; 131 struct sshkey *key; 132 char *comment; 133 char *provider; 134 time_t death; 135 u_int confirm; 136 char *sk_provider; 137 struct dest_constraint *dest_constraints; 138 size_t ndest_constraints; 139 } Identity; 140 141 struct idtable { 142 int nentries; 143 TAILQ_HEAD(idqueue, identity) idlist; 144 }; 145 146 /* private key table */ 147 struct idtable *idtab; 148 149 int max_fd = 0; 150 151 /* pid of shell == parent of agent */ 152 pid_t parent_pid = -1; 153 time_t parent_alive_interval = 0; 154 155 static sig_atomic_t signalled_exit; 156 static sig_atomic_t signalled_keydrop; 157 158 /* pid of process for which cleanup_socket is applicable */ 159 pid_t cleanup_pid = 0; 160 161 /* pathname and directory for AUTH_SOCKET */ 162 char socket_name[PATH_MAX]; 163 char socket_dir[PATH_MAX]; 164 165 /* Pattern-list of allowed PKCS#11/Security key paths */ 166 static char *allowed_providers; 167 168 /* 169 * Allows PKCS11 providers or SK keys that use non-internal providers to 170 * be added over a remote connection (identified by session-bind@openssh.com). 171 */ 172 static int remote_add_provider; 173 174 /* locking */ 175 #define LOCK_SIZE 32 176 #define LOCK_SALT_SIZE 16 177 #define LOCK_ROUNDS 1 178 int locked = 0; 179 u_char lock_pwhash[LOCK_SIZE]; 180 u_char lock_salt[LOCK_SALT_SIZE]; 181 182 extern char *__progname; 183 184 /* Default lifetime in seconds (0 == forever) */ 185 static int lifetime = 0; 186 187 static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 188 189 /* Refuse signing of non-SSH messages for web-origin FIDO keys */ 190 static int restrict_websafe = 1; 191 static char *websafe_allowlist; 192 193 static void 194 close_socket(SocketEntry *e) 195 { 196 size_t i; 197 198 close(e->fd); 199 sshbuf_free(e->input); 200 sshbuf_free(e->output); 201 sshbuf_free(e->request); 202 for (i = 0; i < e->nsession_ids; i++) { 203 sshkey_free(e->session_ids[i].key); 204 sshbuf_free(e->session_ids[i].sid); 205 } 206 free(e->session_ids); 207 memset(e, '\0', sizeof(*e)); 208 e->fd = -1; 209 e->type = AUTH_UNUSED; 210 } 211 212 static void 213 idtab_init(void) 214 { 215 idtab = xcalloc(1, sizeof(*idtab)); 216 TAILQ_INIT(&idtab->idlist); 217 idtab->nentries = 0; 218 } 219 220 static void 221 free_dest_constraint_hop(struct dest_constraint_hop *dch) 222 { 223 u_int i; 224 225 if (dch == NULL) 226 return; 227 free(dch->user); 228 free(dch->hostname); 229 for (i = 0; i < dch->nkeys; i++) 230 sshkey_free(dch->keys[i]); 231 free(dch->keys); 232 free(dch->key_is_ca); 233 } 234 235 static void 236 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs) 237 { 238 size_t i; 239 240 for (i = 0; i < ndcs; i++) { 241 free_dest_constraint_hop(&dcs[i].from); 242 free_dest_constraint_hop(&dcs[i].to); 243 } 244 free(dcs); 245 } 246 247 #ifdef ENABLE_PKCS11 248 static void 249 dup_dest_constraint_hop(const struct dest_constraint_hop *dch, 250 struct dest_constraint_hop *out) 251 { 252 u_int i; 253 int r; 254 255 out->user = dch->user == NULL ? NULL : xstrdup(dch->user); 256 out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname); 257 out->is_ca = dch->is_ca; 258 out->nkeys = dch->nkeys; 259 out->keys = out->nkeys == 0 ? NULL : 260 xcalloc(out->nkeys, sizeof(*out->keys)); 261 out->key_is_ca = out->nkeys == 0 ? NULL : 262 xcalloc(out->nkeys, sizeof(*out->key_is_ca)); 263 for (i = 0; i < dch->nkeys; i++) { 264 if (dch->keys[i] != NULL && 265 (r = sshkey_from_private(dch->keys[i], 266 &(out->keys[i]))) != 0) 267 fatal_fr(r, "copy key"); 268 out->key_is_ca[i] = dch->key_is_ca[i]; 269 } 270 } 271 272 static struct dest_constraint * 273 dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs) 274 { 275 size_t i; 276 struct dest_constraint *ret; 277 278 if (ndcs == 0) 279 return NULL; 280 ret = xcalloc(ndcs, sizeof(*ret)); 281 for (i = 0; i < ndcs; i++) { 282 dup_dest_constraint_hop(&dcs[i].from, &ret[i].from); 283 dup_dest_constraint_hop(&dcs[i].to, &ret[i].to); 284 } 285 return ret; 286 } 287 #endif /* ENABLE_PKCS11 */ 288 289 #ifdef DEBUG_CONSTRAINTS 290 static void 291 dump_dest_constraint_hop(const struct dest_constraint_hop *dch) 292 { 293 u_int i; 294 char *fp; 295 296 debug_f("user %s hostname %s is_ca %d nkeys %u", 297 dch->user == NULL ? "(null)" : dch->user, 298 dch->hostname == NULL ? "(null)" : dch->hostname, 299 dch->is_ca, dch->nkeys); 300 for (i = 0; i < dch->nkeys; i++) { 301 fp = NULL; 302 if (dch->keys[i] != NULL && 303 (fp = sshkey_fingerprint(dch->keys[i], 304 SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL) 305 fatal_f("fingerprint failed"); 306 debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys, 307 dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]), 308 dch->keys[i] == NULL ? "" : " ", 309 dch->keys[i] == NULL ? "none" : fp, 310 dch->key_is_ca[i]); 311 free(fp); 312 } 313 } 314 #endif /* DEBUG_CONSTRAINTS */ 315 316 static void 317 dump_dest_constraints(const char *context, 318 const struct dest_constraint *dcs, size_t ndcs) 319 { 320 #ifdef DEBUG_CONSTRAINTS 321 size_t i; 322 323 debug_f("%s: %zu constraints", context, ndcs); 324 for (i = 0; i < ndcs; i++) { 325 debug_f("constraint %zu / %zu: from: ", i, ndcs); 326 dump_dest_constraint_hop(&dcs[i].from); 327 debug_f("constraint %zu / %zu: to: ", i, ndcs); 328 dump_dest_constraint_hop(&dcs[i].to); 329 } 330 debug_f("done for %s", context); 331 #endif /* DEBUG_CONSTRAINTS */ 332 } 333 334 static void 335 free_identity(Identity *id) 336 { 337 sshkey_free(id->key); 338 free(id->provider); 339 free(id->comment); 340 free(id->sk_provider); 341 free_dest_constraints(id->dest_constraints, id->ndest_constraints); 342 free(id); 343 } 344 345 /* 346 * Match 'key' against the key/CA list in a destination constraint hop 347 * Returns 0 on success or -1 otherwise. 348 */ 349 static int 350 match_key_hop(const char *tag, const struct sshkey *key, 351 const struct dest_constraint_hop *dch) 352 { 353 const char *reason = NULL; 354 const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)"; 355 u_int i; 356 char *fp; 357 358 if (key == NULL) 359 return -1; 360 /* XXX logspam */ 361 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT, 362 SSH_FP_DEFAULT)) == NULL) 363 fatal_f("fingerprint failed"); 364 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail", 365 tag, hostname, sshkey_type(key), fp, dch->nkeys); 366 free(fp); 367 for (i = 0; i < dch->nkeys; i++) { 368 if (dch->keys[i] == NULL) 369 return -1; 370 /* XXX logspam */ 371 if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT, 372 SSH_FP_DEFAULT)) == NULL) 373 fatal_f("fingerprint failed"); 374 debug3_f("%s: key %u: %s%s %s", tag, i, 375 dch->key_is_ca[i] ? "CA " : "", 376 sshkey_type(dch->keys[i]), fp); 377 free(fp); 378 if (!sshkey_is_cert(key)) { 379 /* plain key */ 380 if (dch->key_is_ca[i] || 381 !sshkey_equal(key, dch->keys[i])) 382 continue; 383 return 0; 384 } 385 /* certificate */ 386 if (!dch->key_is_ca[i]) 387 continue; 388 if (key->cert == NULL || key->cert->signature_key == NULL) 389 return -1; /* shouldn't happen */ 390 if (!sshkey_equal(key->cert->signature_key, dch->keys[i])) 391 continue; 392 if (sshkey_cert_check_host(key, hostname, 1, 393 SSH_ALLOWED_CA_SIGALGS, &reason) != 0) { 394 debug_f("cert %s / hostname %s rejected: %s", 395 key->cert->key_id, hostname, reason); 396 continue; 397 } 398 return 0; 399 } 400 return -1; 401 } 402 403 /* Check destination constraints on an identity against the hostkey/user */ 404 static int 405 permitted_by_dest_constraints(const struct sshkey *fromkey, 406 const struct sshkey *tokey, Identity *id, const char *user, 407 const char **hostnamep) 408 { 409 size_t i; 410 struct dest_constraint *d; 411 412 if (hostnamep != NULL) 413 *hostnamep = NULL; 414 for (i = 0; i < id->ndest_constraints; i++) { 415 d = id->dest_constraints + i; 416 /* XXX remove logspam */ 417 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)", 418 i, d->from.user ? d->from.user : "", 419 d->from.user ? "@" : "", 420 d->from.hostname ? d->from.hostname : "(ORIGIN)", 421 d->from.nkeys, 422 d->to.user ? d->to.user : "", d->to.user ? "@" : "", 423 d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys); 424 425 /* Match 'from' key */ 426 if (fromkey == NULL) { 427 /* We are matching the first hop */ 428 if (d->from.hostname != NULL || d->from.nkeys != 0) 429 continue; 430 } else if (match_key_hop("from", fromkey, &d->from) != 0) 431 continue; 432 433 /* Match 'to' key */ 434 if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0) 435 continue; 436 437 /* Match user if specified */ 438 if (d->to.user != NULL && user != NULL && 439 !match_pattern(user, d->to.user)) 440 continue; 441 442 /* successfully matched this constraint */ 443 if (hostnamep != NULL) 444 *hostnamep = d->to.hostname; 445 debug2_f("allowed for hostname %s", 446 d->to.hostname == NULL ? "*" : d->to.hostname); 447 return 0; 448 } 449 /* no match */ 450 debug2_f("%s identity \"%s\" not permitted for this destination", 451 sshkey_type(id->key), id->comment); 452 return -1; 453 } 454 455 /* 456 * Check whether hostkeys on a SocketEntry and the optionally specified user 457 * are permitted by the destination constraints on the Identity. 458 * Returns 0 on success or -1 otherwise. 459 */ 460 static int 461 identity_permitted(Identity *id, SocketEntry *e, char *user, 462 const char **forward_hostnamep, const char **last_hostnamep) 463 { 464 size_t i; 465 const char **hp; 466 struct hostkey_sid *hks; 467 const struct sshkey *fromkey = NULL; 468 const char *test_user; 469 char *fp1, *fp2; 470 471 /* XXX remove logspam */ 472 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, " 473 "%zu constraints", sshkey_type(id->key), id->comment, 474 e->nsession_ids, id->ndest_constraints); 475 if (id->ndest_constraints == 0) 476 return 0; /* unconstrained */ 477 if (e->session_bind_attempted && e->nsession_ids == 0) { 478 error_f("previous session bind failed on socket"); 479 return -1; 480 } 481 if (e->nsession_ids == 0) 482 return 0; /* local use */ 483 /* 484 * Walk through the hops recorded by session_id and try to find a 485 * constraint that satisfies each. 486 */ 487 for (i = 0; i < e->nsession_ids; i++) { 488 hks = e->session_ids + i; 489 if (hks->key == NULL) 490 fatal_f("internal error: no bound key"); 491 /* XXX remove logspam */ 492 fp1 = fp2 = NULL; 493 if (fromkey != NULL && 494 (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT, 495 SSH_FP_DEFAULT)) == NULL) 496 fatal_f("fingerprint failed"); 497 if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT, 498 SSH_FP_DEFAULT)) == NULL) 499 fatal_f("fingerprint failed"); 500 debug3_f("socketentry fd=%d, entry %zu %s, " 501 "from hostkey %s %s to user %s hostkey %s %s", 502 e->fd, i, hks->forwarded ? "FORWARD" : "AUTH", 503 fromkey ? sshkey_type(fromkey) : "(ORIGIN)", 504 fromkey ? fp1 : "", user ? user : "(ANY)", 505 sshkey_type(hks->key), fp2); 506 free(fp1); 507 free(fp2); 508 /* 509 * Record the hostnames for the initial forwarding and 510 * the final destination. 511 */ 512 hp = NULL; 513 if (i == e->nsession_ids - 1) 514 hp = last_hostnamep; 515 else if (i == 0) 516 hp = forward_hostnamep; 517 /* Special handling for final recorded binding */ 518 test_user = NULL; 519 if (i == e->nsession_ids - 1) { 520 /* Can only check user at final hop */ 521 test_user = user; 522 /* 523 * user is only presented for signature requests. 524 * If this is the case, make sure last binding is not 525 * for a forwarding. 526 */ 527 if (hks->forwarded && user != NULL) { 528 error_f("tried to sign on forwarding hop"); 529 return -1; 530 } 531 } else if (!hks->forwarded) { 532 error_f("tried to forward though signing bind"); 533 return -1; 534 } 535 if (permitted_by_dest_constraints(fromkey, hks->key, id, 536 test_user, hp) != 0) 537 return -1; 538 fromkey = hks->key; 539 } 540 /* 541 * Another special case: if the last bound session ID was for a 542 * forwarding, and this function is not being called to check a sign 543 * request (i.e. no 'user' supplied), then only permit the key if 544 * there is a permission that would allow it to be used at another 545 * destination. This hides keys that are allowed to be used to 546 * authenticate *to* a host but not permitted for *use* beyond it. 547 */ 548 hks = &e->session_ids[e->nsession_ids - 1]; 549 if (hks->forwarded && user == NULL && 550 permitted_by_dest_constraints(hks->key, NULL, id, 551 NULL, NULL) != 0) { 552 debug3_f("key permitted at host but not after"); 553 return -1; 554 } 555 556 /* success */ 557 return 0; 558 } 559 560 static int 561 socket_is_remote(SocketEntry *e) 562 { 563 return e->session_bind_attempted || (e->nsession_ids != 0); 564 } 565 566 /* return matching private key for given public key */ 567 static Identity * 568 lookup_identity(struct sshkey *key) 569 { 570 Identity *id; 571 572 TAILQ_FOREACH(id, &idtab->idlist, next) { 573 if (sshkey_equal(key, id->key)) 574 return (id); 575 } 576 return (NULL); 577 } 578 579 /* Check confirmation of keysign request */ 580 static int 581 confirm_key(Identity *id, const char *extra) 582 { 583 char *p; 584 int ret = -1; 585 586 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT); 587 if (p != NULL && 588 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s", 589 id->comment, p, 590 extra == NULL ? "" : "\n", extra == NULL ? "" : extra)) 591 ret = 0; 592 free(p); 593 594 return (ret); 595 } 596 597 static void 598 send_status(SocketEntry *e, int success) 599 { 600 int r; 601 602 if ((r = sshbuf_put_u32(e->output, 1)) != 0 || 603 (r = sshbuf_put_u8(e->output, success ? 604 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0) 605 fatal_fr(r, "compose"); 606 } 607 608 /* send list of supported public keys to 'client' */ 609 static void 610 process_request_identities(SocketEntry *e) 611 { 612 Identity *id; 613 struct sshbuf *msg, *keys; 614 int r; 615 u_int i = 0, nentries = 0; 616 char *fp; 617 618 debug2_f("entering"); 619 620 if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL) 621 fatal_f("sshbuf_new failed"); 622 TAILQ_FOREACH(id, &idtab->idlist, next) { 623 if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT, 624 SSH_FP_DEFAULT)) == NULL) 625 fatal_f("fingerprint failed"); 626 debug_f("key %u / %u: %s %s", i++, idtab->nentries, 627 sshkey_ssh_name(id->key), fp); 628 dump_dest_constraints(__func__, 629 id->dest_constraints, id->ndest_constraints); 630 free(fp); 631 /* identity not visible, don't include in response */ 632 if (identity_permitted(id, e, NULL, NULL, NULL) != 0) 633 continue; 634 if ((r = sshkey_puts_opts(id->key, keys, 635 SSHKEY_SERIALIZE_INFO)) != 0 || 636 (r = sshbuf_put_cstring(keys, id->comment)) != 0) { 637 error_fr(r, "compose key/comment"); 638 continue; 639 } 640 nentries++; 641 } 642 debug2_f("replying with %u allowed of %u available keys", 643 nentries, idtab->nentries); 644 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 645 (r = sshbuf_put_u32(msg, nentries)) != 0 || 646 (r = sshbuf_putb(msg, keys)) != 0) 647 fatal_fr(r, "compose"); 648 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 649 fatal_fr(r, "enqueue"); 650 sshbuf_free(msg); 651 sshbuf_free(keys); 652 } 653 654 655 static char * 656 agent_decode_alg(struct sshkey *key, u_int flags) 657 { 658 if (key->type == KEY_RSA) { 659 if (flags & SSH_AGENT_RSA_SHA2_256) 660 return "rsa-sha2-256"; 661 else if (flags & SSH_AGENT_RSA_SHA2_512) 662 return "rsa-sha2-512"; 663 } else if (key->type == KEY_RSA_CERT) { 664 if (flags & SSH_AGENT_RSA_SHA2_256) 665 return "rsa-sha2-256-cert-v01@openssh.com"; 666 else if (flags & SSH_AGENT_RSA_SHA2_512) 667 return "rsa-sha2-512-cert-v01@openssh.com"; 668 } 669 return NULL; 670 } 671 672 /* 673 * Attempt to parse the contents of a buffer as a SSH publickey userauth 674 * request, checking its contents for consistency and matching the embedded 675 * key against the one that is being used for signing. 676 * Note: does not modify msg buffer. 677 * Optionally extract the username, session ID and/or hostkey from the request. 678 */ 679 static int 680 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key, 681 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp) 682 { 683 struct sshbuf *b = NULL, *sess_id = NULL; 684 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL; 685 int r; 686 u_char t, sig_follows; 687 struct sshkey *mkey = NULL, *hostkey = NULL; 688 689 if (userp != NULL) 690 *userp = NULL; 691 if (sess_idp != NULL) 692 *sess_idp = NULL; 693 if (hostkeyp != NULL) 694 *hostkeyp = NULL; 695 if ((b = sshbuf_fromb(msg)) == NULL) 696 fatal_f("sshbuf_fromb"); 697 698 /* SSH userauth request */ 699 if ((r = sshbuf_froms(b, &sess_id)) != 0) 700 goto out; 701 if (sshbuf_len(sess_id) == 0) { 702 r = SSH_ERR_INVALID_FORMAT; 703 goto out; 704 } 705 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */ 706 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */ 707 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */ 708 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */ 709 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */ 710 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */ 711 (r = sshkey_froms(b, &mkey)) != 0) /* key */ 712 goto out; 713 if (t != SSH2_MSG_USERAUTH_REQUEST || 714 sig_follows != 1 || 715 strcmp(service, "ssh-connection") != 0 || 716 !sshkey_equal(expected_key, mkey) || 717 sshkey_type_from_name(pkalg) != expected_key->type) { 718 r = SSH_ERR_INVALID_FORMAT; 719 goto out; 720 } 721 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) { 722 if ((r = sshkey_froms(b, &hostkey)) != 0) 723 goto out; 724 } else if (strcmp(method, "publickey") != 0) { 725 r = SSH_ERR_INVALID_FORMAT; 726 goto out; 727 } 728 if (sshbuf_len(b) != 0) { 729 r = SSH_ERR_INVALID_FORMAT; 730 goto out; 731 } 732 /* success */ 733 r = 0; 734 debug3_f("well formed userauth"); 735 if (userp != NULL) { 736 *userp = user; 737 user = NULL; 738 } 739 if (sess_idp != NULL) { 740 *sess_idp = sess_id; 741 sess_id = NULL; 742 } 743 if (hostkeyp != NULL) { 744 *hostkeyp = hostkey; 745 hostkey = NULL; 746 } 747 out: 748 sshbuf_free(b); 749 sshbuf_free(sess_id); 750 free(user); 751 free(service); 752 free(method); 753 free(pkalg); 754 sshkey_free(mkey); 755 sshkey_free(hostkey); 756 return r; 757 } 758 759 /* 760 * Attempt to parse the contents of a buffer as a SSHSIG signature request. 761 * Note: does not modify buffer. 762 */ 763 static int 764 parse_sshsig_request(struct sshbuf *msg) 765 { 766 int r; 767 struct sshbuf *b; 768 769 if ((b = sshbuf_fromb(msg)) == NULL) 770 fatal_f("sshbuf_fromb"); 771 772 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 || 773 (r = sshbuf_consume(b, 6)) != 0 || 774 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */ 775 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */ 776 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */ 777 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */ 778 goto out; 779 if (sshbuf_len(b) != 0) { 780 r = SSH_ERR_INVALID_FORMAT; 781 goto out; 782 } 783 /* success */ 784 r = 0; 785 out: 786 sshbuf_free(b); 787 return r; 788 } 789 790 /* 791 * This function inspects a message to be signed by a FIDO key that has a 792 * web-like application string (i.e. one that does not begin with "ssh:". 793 * It checks that the message is one of those expected for SSH operations 794 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges 795 * for the web. 796 */ 797 static int 798 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data) 799 { 800 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) { 801 debug_f("signed data matches public key userauth request"); 802 return 1; 803 } 804 if (parse_sshsig_request(data) == 0) { 805 debug_f("signed data matches SSHSIG signature request"); 806 return 1; 807 } 808 809 /* XXX check CA signature operation */ 810 811 error("web-origin key attempting to sign non-SSH message"); 812 return 0; 813 } 814 815 static int 816 buf_equal(const struct sshbuf *a, const struct sshbuf *b) 817 { 818 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL) 819 return SSH_ERR_INVALID_ARGUMENT; 820 if (sshbuf_len(a) != sshbuf_len(b)) 821 return SSH_ERR_INVALID_FORMAT; 822 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0) 823 return SSH_ERR_INVALID_FORMAT; 824 return 0; 825 } 826 827 /* ssh2 only */ 828 static void 829 process_sign_request2(SocketEntry *e) 830 { 831 u_char *signature = NULL; 832 size_t slen = 0; 833 u_int compat = 0, flags; 834 int r, ok = -1, retried = 0; 835 char *fp = NULL, *pin = NULL, *prompt = NULL; 836 char *user = NULL, *sig_dest = NULL; 837 const char *fwd_host = NULL, *dest_host = NULL; 838 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL; 839 struct sshkey *key = NULL, *hostkey = NULL; 840 struct identity *id; 841 struct notifier_ctx *notifier = NULL; 842 843 debug_f("entering"); 844 845 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL) 846 fatal_f("sshbuf_new failed"); 847 if ((r = sshkey_froms(e->request, &key)) != 0 || 848 (r = sshbuf_get_stringb(e->request, data)) != 0 || 849 (r = sshbuf_get_u32(e->request, &flags)) != 0) { 850 error_fr(r, "parse"); 851 goto send; 852 } 853 854 if ((id = lookup_identity(key)) == NULL) { 855 verbose_f("%s key not found", sshkey_type(key)); 856 goto send; 857 } 858 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT, 859 SSH_FP_DEFAULT)) == NULL) 860 fatal_f("fingerprint failed"); 861 862 if (id->ndest_constraints != 0) { 863 if (e->nsession_ids == 0) { 864 logit_f("refusing use of destination-constrained key " 865 "to sign on unbound connection"); 866 goto send; 867 } 868 if (parse_userauth_request(data, key, &user, &sid, 869 &hostkey) != 0) { 870 logit_f("refusing use of destination-constrained key " 871 "to sign an unidentified signature"); 872 goto send; 873 } 874 /* XXX logspam */ 875 debug_f("user=%s", user); 876 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0) 877 goto send; 878 /* XXX display fwd_host/dest_host in askpass UI */ 879 /* 880 * Ensure that the session ID is the most recent one 881 * registered on the socket - it should have been bound by 882 * ssh immediately before userauth. 883 */ 884 if (buf_equal(sid, 885 e->session_ids[e->nsession_ids - 1].sid) != 0) { 886 error_f("unexpected session ID (%zu listed) on " 887 "signature request for target user %s with " 888 "key %s %s", e->nsession_ids, user, 889 sshkey_type(id->key), fp); 890 goto send; 891 } 892 /* 893 * Ensure that the hostkey embedded in the signature matches 894 * the one most recently bound to the socket. An exception is 895 * made for the initial forwarding hop. 896 */ 897 if (e->nsession_ids > 1 && hostkey == NULL) { 898 error_f("refusing use of destination-constrained key: " 899 "no hostkey recorded in signature for forwarded " 900 "connection"); 901 goto send; 902 } 903 if (hostkey != NULL && !sshkey_equal(hostkey, 904 e->session_ids[e->nsession_ids - 1].key)) { 905 error_f("refusing use of destination-constrained key: " 906 "mismatch between hostkey in request and most " 907 "recently bound session"); 908 goto send; 909 } 910 xasprintf(&sig_dest, "public key authentication request for " 911 "user \"%s\" to listed host", user); 912 } 913 if (id->confirm && confirm_key(id, sig_dest) != 0) { 914 verbose_f("user refused key"); 915 goto send; 916 } 917 if (sshkey_is_sk(id->key)) { 918 if (restrict_websafe && 919 match_pattern_list(id->key->sk_application, 920 websafe_allowlist, 0) != 1 && 921 !check_websafe_message_contents(key, data)) { 922 /* error already logged */ 923 goto send; 924 } 925 if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) { 926 notifier = notify_start(0, 927 "Confirm user presence for key %s %s%s%s", 928 sshkey_type(id->key), fp, 929 sig_dest == NULL ? "" : "\n", 930 sig_dest == NULL ? "" : sig_dest); 931 } 932 } 933 retry_pin: 934 if ((r = sshkey_sign(id->key, &signature, &slen, 935 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags), 936 id->sk_provider, pin, compat)) != 0) { 937 debug_fr(r, "sshkey_sign"); 938 if (pin == NULL && !retried && sshkey_is_sk(id->key) && 939 r == SSH_ERR_KEY_WRONG_PASSPHRASE) { 940 notify_complete(notifier, NULL); 941 notifier = NULL; 942 /* XXX include sig_dest */ 943 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ", 944 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ? 945 " and confirm user presence " : " ", 946 sshkey_type(id->key), fp); 947 pin = read_passphrase(prompt, RP_USE_ASKPASS); 948 retried = 1; 949 goto retry_pin; 950 } 951 error_fr(r, "sshkey_sign"); 952 goto send; 953 } 954 /* Success */ 955 ok = 0; 956 debug_f("good signature"); 957 send: 958 notify_complete(notifier, "User presence confirmed"); 959 960 if (ok == 0) { 961 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 || 962 (r = sshbuf_put_string(msg, signature, slen)) != 0) 963 fatal_fr(r, "compose"); 964 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0) 965 fatal_fr(r, "compose failure"); 966 967 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 968 fatal_fr(r, "enqueue"); 969 970 sshbuf_free(sid); 971 sshbuf_free(data); 972 sshbuf_free(msg); 973 sshkey_free(key); 974 sshkey_free(hostkey); 975 free(fp); 976 free(signature); 977 free(sig_dest); 978 free(user); 979 free(prompt); 980 if (pin != NULL) 981 freezero(pin, strlen(pin)); 982 } 983 984 /* shared */ 985 static void 986 process_remove_identity(SocketEntry *e) 987 { 988 int r, success = 0; 989 struct sshkey *key = NULL; 990 Identity *id; 991 992 debug2_f("entering"); 993 if ((r = sshkey_froms(e->request, &key)) != 0) { 994 error_fr(r, "parse key"); 995 goto done; 996 } 997 if ((id = lookup_identity(key)) == NULL) { 998 debug_f("key not found"); 999 goto done; 1000 } 1001 /* identity not visible, cannot be removed */ 1002 if (identity_permitted(id, e, NULL, NULL, NULL) != 0) 1003 goto done; /* error already logged */ 1004 /* We have this key, free it. */ 1005 if (idtab->nentries < 1) 1006 fatal_f("internal error: nentries %d", idtab->nentries); 1007 TAILQ_REMOVE(&idtab->idlist, id, next); 1008 free_identity(id); 1009 idtab->nentries--; 1010 success = 1; 1011 done: 1012 sshkey_free(key); 1013 send_status(e, success); 1014 } 1015 1016 static void 1017 remove_all_identities(void) 1018 { 1019 Identity *id; 1020 1021 debug2_f("entering"); 1022 /* Loop over all identities and clear the keys. */ 1023 for (id = TAILQ_FIRST(&idtab->idlist); id; 1024 id = TAILQ_FIRST(&idtab->idlist)) { 1025 TAILQ_REMOVE(&idtab->idlist, id, next); 1026 free_identity(id); 1027 } 1028 1029 /* Mark that there are no identities. */ 1030 idtab->nentries = 0; 1031 } 1032 1033 static void 1034 process_remove_all_identities(SocketEntry *e) 1035 { 1036 remove_all_identities(); 1037 1038 /* Send success. */ 1039 send_status(e, 1); 1040 } 1041 1042 /* removes expired keys and returns number of seconds until the next expiry */ 1043 static time_t 1044 reaper(void) 1045 { 1046 time_t deadline = 0, now = monotime(); 1047 Identity *id, *nxt; 1048 1049 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 1050 nxt = TAILQ_NEXT(id, next); 1051 if (id->death == 0) 1052 continue; 1053 if (now >= id->death) { 1054 debug("expiring key '%s'", id->comment); 1055 TAILQ_REMOVE(&idtab->idlist, id, next); 1056 free_identity(id); 1057 idtab->nentries--; 1058 } else 1059 deadline = (deadline == 0) ? id->death : 1060 MINIMUM(deadline, id->death); 1061 } 1062 if (deadline == 0 || deadline <= now) 1063 return 0; 1064 else 1065 return (deadline - now); 1066 } 1067 1068 static int 1069 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch) 1070 { 1071 u_char key_is_ca; 1072 size_t elen = 0; 1073 int r; 1074 struct sshkey *k = NULL; 1075 char *fp; 1076 1077 memset(dch, '\0', sizeof(*dch)); 1078 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 || 1079 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 || 1080 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) { 1081 error_fr(r, "parse"); 1082 goto out; 1083 } 1084 if (elen != 0) { 1085 error_f("unsupported extensions (len %zu)", elen); 1086 r = SSH_ERR_FEATURE_UNSUPPORTED; 1087 goto out; 1088 } 1089 if (*dch->hostname == '\0') { 1090 free(dch->hostname); 1091 dch->hostname = NULL; 1092 } 1093 if (*dch->user == '\0') { 1094 free(dch->user); 1095 dch->user = NULL; 1096 } 1097 while (sshbuf_len(b) != 0) { 1098 dch->keys = xrecallocarray(dch->keys, dch->nkeys, 1099 dch->nkeys + 1, sizeof(*dch->keys)); 1100 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys, 1101 dch->nkeys + 1, sizeof(*dch->key_is_ca)); 1102 if ((r = sshkey_froms(b, &k)) != 0 || 1103 (r = sshbuf_get_u8(b, &key_is_ca)) != 0) 1104 goto out; 1105 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT, 1106 SSH_FP_DEFAULT)) == NULL) 1107 fatal_f("fingerprint failed"); 1108 debug3_f("%s%s%s: adding %skey %s %s", 1109 dch->user == NULL ? "" : dch->user, 1110 dch->user == NULL ? "" : "@", 1111 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp); 1112 free(fp); 1113 dch->keys[dch->nkeys] = k; 1114 dch->key_is_ca[dch->nkeys] = key_is_ca != 0; 1115 dch->nkeys++; 1116 k = NULL; /* transferred */ 1117 } 1118 /* success */ 1119 r = 0; 1120 out: 1121 sshkey_free(k); 1122 return r; 1123 } 1124 1125 static int 1126 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc) 1127 { 1128 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL; 1129 int r; 1130 size_t elen = 0; 1131 1132 debug3_f("entering"); 1133 1134 memset(dc, '\0', sizeof(*dc)); 1135 if ((r = sshbuf_froms(m, &b)) != 0 || 1136 (r = sshbuf_froms(b, &frombuf)) != 0 || 1137 (r = sshbuf_froms(b, &tobuf)) != 0 || 1138 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) { 1139 error_fr(r, "parse"); 1140 goto out; 1141 } 1142 if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 || 1143 (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0) 1144 goto out; /* already logged */ 1145 if (elen != 0) { 1146 error_f("unsupported extensions (len %zu)", elen); 1147 r = SSH_ERR_FEATURE_UNSUPPORTED; 1148 goto out; 1149 } 1150 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)", 1151 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys, 1152 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "", 1153 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys); 1154 /* check consistency */ 1155 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) || 1156 dc->from.user != NULL) { 1157 error_f("inconsistent \"from\" specification"); 1158 r = SSH_ERR_INVALID_FORMAT; 1159 goto out; 1160 } 1161 if (dc->to.hostname == NULL || dc->to.nkeys == 0) { 1162 error_f("incomplete \"to\" specification"); 1163 r = SSH_ERR_INVALID_FORMAT; 1164 goto out; 1165 } 1166 /* success */ 1167 r = 0; 1168 out: 1169 sshbuf_free(b); 1170 sshbuf_free(frombuf); 1171 sshbuf_free(tobuf); 1172 return r; 1173 } 1174 1175 static int 1176 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp, 1177 struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp, 1178 struct sshkey ***certs, size_t *ncerts) 1179 { 1180 char *ext_name = NULL; 1181 int r; 1182 struct sshbuf *b = NULL; 1183 u_char v; 1184 struct sshkey *k; 1185 1186 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) { 1187 error_fr(r, "parse constraint extension"); 1188 goto out; 1189 } 1190 debug_f("constraint ext %s", ext_name); 1191 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) { 1192 if (sk_providerp == NULL) { 1193 error_f("%s not valid here", ext_name); 1194 r = SSH_ERR_INVALID_FORMAT; 1195 goto out; 1196 } 1197 if (*sk_providerp != NULL) { 1198 error_f("%s already set", ext_name); 1199 r = SSH_ERR_INVALID_FORMAT; 1200 goto out; 1201 } 1202 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) { 1203 error_fr(r, "parse %s", ext_name); 1204 goto out; 1205 } 1206 } else if (strcmp(ext_name, 1207 "restrict-destination-v00@openssh.com") == 0) { 1208 if (*dcsp != NULL) { 1209 error_f("%s already set", ext_name); 1210 goto out; 1211 } 1212 if ((r = sshbuf_froms(m, &b)) != 0) { 1213 error_fr(r, "parse %s outer", ext_name); 1214 goto out; 1215 } 1216 while (sshbuf_len(b) != 0) { 1217 if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) { 1218 error_f("too many %s constraints", ext_name); 1219 goto out; 1220 } 1221 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1, 1222 sizeof(**dcsp)); 1223 if ((r = parse_dest_constraint(b, 1224 *dcsp + (*ndcsp)++)) != 0) 1225 goto out; /* error already logged */ 1226 } 1227 } else if (strcmp(ext_name, 1228 "associated-certs-v00@openssh.com") == 0) { 1229 if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) { 1230 error_f("%s not valid here", ext_name); 1231 r = SSH_ERR_INVALID_FORMAT; 1232 goto out; 1233 } 1234 if (*certs != NULL) { 1235 error_f("%s already set", ext_name); 1236 goto out; 1237 } 1238 if ((r = sshbuf_get_u8(m, &v)) != 0 || 1239 (r = sshbuf_froms(m, &b)) != 0) { 1240 error_fr(r, "parse %s", ext_name); 1241 goto out; 1242 } 1243 *cert_onlyp = v != 0; 1244 while (sshbuf_len(b) != 0) { 1245 if (*ncerts >= AGENT_MAX_EXT_CERTS) { 1246 error_f("too many %s constraints", ext_name); 1247 goto out; 1248 } 1249 *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1, 1250 sizeof(**certs)); 1251 if ((r = sshkey_froms(b, &k)) != 0) { 1252 error_fr(r, "parse key"); 1253 goto out; 1254 } 1255 (*certs)[(*ncerts)++] = k; 1256 } 1257 } else { 1258 error_f("unsupported constraint \"%s\"", ext_name); 1259 r = SSH_ERR_FEATURE_UNSUPPORTED; 1260 goto out; 1261 } 1262 /* success */ 1263 r = 0; 1264 out: 1265 free(ext_name); 1266 sshbuf_free(b); 1267 return r; 1268 } 1269 1270 static int 1271 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp, 1272 u_int *secondsp, int *confirmp, char **sk_providerp, 1273 struct dest_constraint **dcsp, size_t *ndcsp, 1274 int *cert_onlyp, size_t *ncerts, struct sshkey ***certs) 1275 { 1276 u_char ctype; 1277 int r; 1278 u_int seconds, maxsign = 0; 1279 1280 while (sshbuf_len(m)) { 1281 if ((r = sshbuf_get_u8(m, &ctype)) != 0) { 1282 error_fr(r, "parse constraint type"); 1283 goto out; 1284 } 1285 switch (ctype) { 1286 case SSH_AGENT_CONSTRAIN_LIFETIME: 1287 if (*deathp != 0) { 1288 error_f("lifetime already set"); 1289 r = SSH_ERR_INVALID_FORMAT; 1290 goto out; 1291 } 1292 if ((r = sshbuf_get_u32(m, &seconds)) != 0) { 1293 error_fr(r, "parse lifetime constraint"); 1294 goto out; 1295 } 1296 *deathp = monotime() + seconds; 1297 *secondsp = seconds; 1298 break; 1299 case SSH_AGENT_CONSTRAIN_CONFIRM: 1300 if (*confirmp != 0) { 1301 error_f("confirm already set"); 1302 r = SSH_ERR_INVALID_FORMAT; 1303 goto out; 1304 } 1305 *confirmp = 1; 1306 break; 1307 case SSH_AGENT_CONSTRAIN_MAXSIGN: 1308 if (k == NULL) { 1309 error_f("maxsign not valid here"); 1310 r = SSH_ERR_INVALID_FORMAT; 1311 goto out; 1312 } 1313 if (maxsign != 0) { 1314 error_f("maxsign already set"); 1315 r = SSH_ERR_INVALID_FORMAT; 1316 goto out; 1317 } 1318 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) { 1319 error_fr(r, "parse maxsign constraint"); 1320 goto out; 1321 } 1322 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) { 1323 error_fr(r, "enable maxsign"); 1324 goto out; 1325 } 1326 break; 1327 case SSH_AGENT_CONSTRAIN_EXTENSION: 1328 if ((r = parse_key_constraint_extension(m, 1329 sk_providerp, dcsp, ndcsp, 1330 cert_onlyp, certs, ncerts)) != 0) 1331 goto out; /* error already logged */ 1332 break; 1333 default: 1334 error_f("Unknown constraint %d", ctype); 1335 r = SSH_ERR_FEATURE_UNSUPPORTED; 1336 goto out; 1337 } 1338 } 1339 /* success */ 1340 r = 0; 1341 out: 1342 return r; 1343 } 1344 1345 static void 1346 process_add_identity(SocketEntry *e) 1347 { 1348 Identity *id; 1349 int success = 0, confirm = 0; 1350 char *fp, *comment = NULL, *sk_provider = NULL; 1351 char canonical_provider[PATH_MAX]; 1352 time_t death = 0; 1353 u_int seconds = 0; 1354 struct dest_constraint *dest_constraints = NULL; 1355 size_t ndest_constraints = 0; 1356 struct sshkey *k = NULL; 1357 int r = SSH_ERR_INTERNAL_ERROR; 1358 1359 debug2_f("entering"); 1360 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 || 1361 k == NULL || 1362 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) { 1363 error_fr(r, "parse"); 1364 goto out; 1365 } 1366 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm, 1367 &sk_provider, &dest_constraints, &ndest_constraints, 1368 NULL, NULL, NULL) != 0) { 1369 error_f("failed to parse constraints"); 1370 sshbuf_reset(e->request); 1371 goto out; 1372 } 1373 dump_dest_constraints(__func__, dest_constraints, ndest_constraints); 1374 1375 if (sk_provider != NULL) { 1376 if (!sshkey_is_sk(k)) { 1377 error("Cannot add provider: %s is not an " 1378 "authenticator-hosted key", sshkey_type(k)); 1379 goto out; 1380 } 1381 if (strcasecmp(sk_provider, "internal") == 0) { 1382 debug_f("internal provider"); 1383 } else { 1384 if (socket_is_remote(e) && !remote_add_provider) { 1385 verbose("failed add of SK provider \"%.100s\": " 1386 "remote addition of providers is disabled", 1387 sk_provider); 1388 goto out; 1389 } 1390 if (realpath(sk_provider, canonical_provider) == NULL) { 1391 verbose("failed provider \"%.100s\": " 1392 "realpath: %s", sk_provider, 1393 strerror(errno)); 1394 goto out; 1395 } 1396 free(sk_provider); 1397 sk_provider = xstrdup(canonical_provider); 1398 if (match_pattern_list(sk_provider, 1399 allowed_providers, 0) != 1) { 1400 error("Refusing add key: " 1401 "provider %s not allowed", sk_provider); 1402 goto out; 1403 } 1404 } 1405 } 1406 if ((r = sshkey_shield_private(k)) != 0) { 1407 error_fr(r, "shield private"); 1408 goto out; 1409 } 1410 if (lifetime && !death) 1411 death = monotime() + lifetime; 1412 if ((id = lookup_identity(k)) == NULL) { 1413 id = xcalloc(1, sizeof(Identity)); 1414 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 1415 /* Increment the number of identities. */ 1416 idtab->nentries++; 1417 } else { 1418 /* identity not visible, do not update */ 1419 if (identity_permitted(id, e, NULL, NULL, NULL) != 0) 1420 goto out; /* error already logged */ 1421 /* key state might have been updated */ 1422 sshkey_free(id->key); 1423 free(id->comment); 1424 free(id->sk_provider); 1425 free_dest_constraints(id->dest_constraints, 1426 id->ndest_constraints); 1427 } 1428 /* success */ 1429 id->key = k; 1430 id->comment = comment; 1431 id->death = death; 1432 id->confirm = confirm; 1433 id->sk_provider = sk_provider; 1434 id->dest_constraints = dest_constraints; 1435 id->ndest_constraints = ndest_constraints; 1436 1437 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT, 1438 SSH_FP_DEFAULT)) == NULL) 1439 fatal_f("sshkey_fingerprint failed"); 1440 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) " 1441 "(provider: %s) (destination constraints: %zu)", 1442 sshkey_ssh_name(k), fp, comment, seconds, confirm, 1443 sk_provider == NULL ? "none" : sk_provider, ndest_constraints); 1444 free(fp); 1445 /* transferred */ 1446 k = NULL; 1447 comment = NULL; 1448 sk_provider = NULL; 1449 dest_constraints = NULL; 1450 ndest_constraints = 0; 1451 success = 1; 1452 out: 1453 free(sk_provider); 1454 free(comment); 1455 sshkey_free(k); 1456 free_dest_constraints(dest_constraints, ndest_constraints); 1457 send_status(e, success); 1458 } 1459 1460 /* XXX todo: encrypt sensitive data with passphrase */ 1461 static void 1462 process_lock_agent(SocketEntry *e, int lock) 1463 { 1464 int r, success = 0, delay; 1465 char *passwd; 1466 u_char passwdhash[LOCK_SIZE]; 1467 static u_int fail_count = 0; 1468 size_t pwlen; 1469 1470 debug2_f("entering"); 1471 /* 1472 * This is deliberately fatal: the user has requested that we lock, 1473 * but we can't parse their request properly. The only safe thing to 1474 * do is abort. 1475 */ 1476 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0) 1477 fatal_fr(r, "parse"); 1478 if (pwlen == 0) { 1479 debug("empty password not supported"); 1480 } else if (locked && !lock) { 1481 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 1482 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0) 1483 fatal("bcrypt_pbkdf"); 1484 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) { 1485 debug("agent unlocked"); 1486 locked = 0; 1487 fail_count = 0; 1488 explicit_bzero(lock_pwhash, sizeof(lock_pwhash)); 1489 success = 1; 1490 } else { 1491 /* delay in 0.1s increments up to 10s */ 1492 if (fail_count < 100) 1493 fail_count++; 1494 delay = 100000 * fail_count; 1495 debug("unlock failed, delaying %0.1lf seconds", 1496 (double)delay/1000000); 1497 usleep(delay); 1498 } 1499 explicit_bzero(passwdhash, sizeof(passwdhash)); 1500 } else if (!locked && lock) { 1501 debug("agent locked"); 1502 locked = 1; 1503 arc4random_buf(lock_salt, sizeof(lock_salt)); 1504 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 1505 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0) 1506 fatal("bcrypt_pbkdf"); 1507 success = 1; 1508 } 1509 freezero(passwd, pwlen); 1510 send_status(e, success); 1511 } 1512 1513 static void 1514 no_identities(SocketEntry *e) 1515 { 1516 struct sshbuf *msg; 1517 int r; 1518 1519 if ((msg = sshbuf_new()) == NULL) 1520 fatal_f("sshbuf_new failed"); 1521 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 1522 (r = sshbuf_put_u32(msg, 0)) != 0 || 1523 (r = sshbuf_put_stringb(e->output, msg)) != 0) 1524 fatal_fr(r, "compose"); 1525 sshbuf_free(msg); 1526 } 1527 1528 #ifdef ENABLE_PKCS11 1529 /* Add an identity to idlist; takes ownership of 'key' and 'comment' */ 1530 static void 1531 add_p11_identity(struct sshkey *key, char *comment, const char *provider, 1532 time_t death, u_int confirm, struct dest_constraint *dest_constraints, 1533 size_t ndest_constraints) 1534 { 1535 Identity *id; 1536 1537 if (lookup_identity(key) != NULL) { 1538 sshkey_free(key); 1539 free(comment); 1540 return; 1541 } 1542 id = xcalloc(1, sizeof(Identity)); 1543 id->key = key; 1544 id->comment = comment; 1545 id->provider = xstrdup(provider); 1546 id->death = death; 1547 id->confirm = confirm; 1548 id->dest_constraints = dup_dest_constraints(dest_constraints, 1549 ndest_constraints); 1550 id->ndest_constraints = ndest_constraints; 1551 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 1552 idtab->nentries++; 1553 } 1554 1555 static void 1556 process_add_smartcard_key(SocketEntry *e) 1557 { 1558 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 1559 char **comments = NULL; 1560 int r, i, count = 0, success = 0, confirm = 0; 1561 u_int seconds = 0; 1562 time_t death = 0; 1563 struct sshkey **keys = NULL, *k; 1564 struct dest_constraint *dest_constraints = NULL; 1565 size_t j, ndest_constraints = 0, ncerts = 0; 1566 struct sshkey **certs = NULL; 1567 int cert_only = 0; 1568 1569 debug2_f("entering"); 1570 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 1571 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 1572 error_fr(r, "parse"); 1573 goto send; 1574 } 1575 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm, 1576 NULL, &dest_constraints, &ndest_constraints, &cert_only, 1577 &ncerts, &certs) != 0) { 1578 error_f("failed to parse constraints"); 1579 goto send; 1580 } 1581 dump_dest_constraints(__func__, dest_constraints, ndest_constraints); 1582 if (socket_is_remote(e) && !remote_add_provider) { 1583 verbose("failed PKCS#11 add of \"%.100s\": remote addition of " 1584 "providers is disabled", provider); 1585 goto send; 1586 } 1587 if (realpath(provider, canonical_provider) == NULL) { 1588 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 1589 provider, strerror(errno)); 1590 goto send; 1591 } 1592 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) { 1593 verbose("refusing PKCS#11 add of \"%.100s\": " 1594 "provider not allowed", canonical_provider); 1595 goto send; 1596 } 1597 debug_f("add %.100s", canonical_provider); 1598 if (lifetime && !death) 1599 death = monotime() + lifetime; 1600 1601 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments); 1602 for (i = 0; i < count; i++) { 1603 if (comments[i] == NULL || comments[i][0] == '\0') { 1604 free(comments[i]); 1605 comments[i] = xstrdup(canonical_provider); 1606 } 1607 for (j = 0; j < ncerts; j++) { 1608 if (!sshkey_is_cert(certs[j])) 1609 continue; 1610 if (!sshkey_equal_public(keys[i], certs[j])) 1611 continue; 1612 if (pkcs11_make_cert(keys[i], certs[j], &k) != 0) 1613 continue; 1614 add_p11_identity(k, xstrdup(comments[i]), 1615 canonical_provider, death, confirm, 1616 dest_constraints, ndest_constraints); 1617 success = 1; 1618 } 1619 if (!cert_only && lookup_identity(keys[i]) == NULL) { 1620 add_p11_identity(keys[i], comments[i], 1621 canonical_provider, death, confirm, 1622 dest_constraints, ndest_constraints); 1623 keys[i] = NULL; /* transferred */ 1624 comments[i] = NULL; /* transferred */ 1625 success = 1; 1626 } 1627 /* XXX update constraints for existing keys */ 1628 sshkey_free(keys[i]); 1629 free(comments[i]); 1630 } 1631 send: 1632 free(pin); 1633 free(provider); 1634 free(keys); 1635 free(comments); 1636 free_dest_constraints(dest_constraints, ndest_constraints); 1637 for (j = 0; j < ncerts; j++) 1638 sshkey_free(certs[j]); 1639 free(certs); 1640 send_status(e, success); 1641 } 1642 1643 static void 1644 process_remove_smartcard_key(SocketEntry *e) 1645 { 1646 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 1647 int r, success = 0; 1648 Identity *id, *nxt; 1649 1650 debug2_f("entering"); 1651 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 1652 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 1653 error_fr(r, "parse"); 1654 goto send; 1655 } 1656 free(pin); 1657 1658 if (realpath(provider, canonical_provider) == NULL) { 1659 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 1660 provider, strerror(errno)); 1661 goto send; 1662 } 1663 1664 debug_f("remove %.100s", canonical_provider); 1665 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 1666 nxt = TAILQ_NEXT(id, next); 1667 /* Skip file--based keys */ 1668 if (id->provider == NULL) 1669 continue; 1670 if (!strcmp(canonical_provider, id->provider)) { 1671 TAILQ_REMOVE(&idtab->idlist, id, next); 1672 free_identity(id); 1673 idtab->nentries--; 1674 } 1675 } 1676 if (pkcs11_del_provider(canonical_provider) == 0) 1677 success = 1; 1678 else 1679 error_f("pkcs11_del_provider failed"); 1680 send: 1681 free(provider); 1682 send_status(e, success); 1683 } 1684 #endif /* ENABLE_PKCS11 */ 1685 1686 static int 1687 process_ext_session_bind(SocketEntry *e) 1688 { 1689 int r, sid_match, key_match; 1690 struct sshkey *key = NULL; 1691 struct sshbuf *sid = NULL, *sig = NULL; 1692 char *fp = NULL; 1693 size_t i; 1694 u_char fwd = 0; 1695 1696 debug2_f("entering"); 1697 e->session_bind_attempted = 1; 1698 if ((r = sshkey_froms(e->request, &key)) != 0 || 1699 (r = sshbuf_froms(e->request, &sid)) != 0 || 1700 (r = sshbuf_froms(e->request, &sig)) != 0 || 1701 (r = sshbuf_get_u8(e->request, &fwd)) != 0) { 1702 error_fr(r, "parse"); 1703 goto out; 1704 } 1705 if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) { 1706 error_f("session ID too long"); 1707 goto out; 1708 } 1709 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT, 1710 SSH_FP_DEFAULT)) == NULL) 1711 fatal_f("fingerprint failed"); 1712 /* check signature with hostkey on session ID */ 1713 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig), 1714 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) { 1715 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp); 1716 goto out; 1717 } 1718 /* check whether sid/key already recorded */ 1719 for (i = 0; i < e->nsession_ids; i++) { 1720 if (!e->session_ids[i].forwarded) { 1721 error_f("attempt to bind session ID to socket " 1722 "previously bound for authentication attempt"); 1723 r = -1; 1724 goto out; 1725 } 1726 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0; 1727 key_match = sshkey_equal(key, e->session_ids[i].key); 1728 if (sid_match && key_match) { 1729 debug_f("session ID already recorded for %s %s", 1730 sshkey_type(key), fp); 1731 r = 0; 1732 goto out; 1733 } else if (sid_match) { 1734 error_f("session ID recorded against different key " 1735 "for %s %s", sshkey_type(key), fp); 1736 r = -1; 1737 goto out; 1738 } 1739 /* 1740 * new sid with previously-seen key can happen, e.g. multiple 1741 * connections to the same host. 1742 */ 1743 } 1744 /* record new key/sid */ 1745 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) { 1746 error_f("too many session IDs recorded"); 1747 goto out; 1748 } 1749 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids, 1750 e->nsession_ids + 1, sizeof(*e->session_ids)); 1751 i = e->nsession_ids++; 1752 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i, 1753 AGENT_MAX_SESSION_IDS); 1754 e->session_ids[i].key = key; 1755 e->session_ids[i].forwarded = fwd != 0; 1756 key = NULL; /* transferred */ 1757 /* can't transfer sid; it's refcounted and scoped to request's life */ 1758 if ((e->session_ids[i].sid = sshbuf_new()) == NULL) 1759 fatal_f("sshbuf_new"); 1760 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0) 1761 fatal_fr(r, "sshbuf_putb session ID"); 1762 /* success */ 1763 r = 0; 1764 out: 1765 free(fp); 1766 sshkey_free(key); 1767 sshbuf_free(sid); 1768 sshbuf_free(sig); 1769 return r == 0 ? 1 : 0; 1770 } 1771 1772 static void 1773 process_extension(SocketEntry *e) 1774 { 1775 int r, success = 0; 1776 char *name; 1777 1778 debug2_f("entering"); 1779 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) { 1780 error_fr(r, "parse"); 1781 goto send; 1782 } 1783 if (strcmp(name, "session-bind@openssh.com") == 0) 1784 success = process_ext_session_bind(e); 1785 else 1786 debug_f("unsupported extension \"%s\"", name); 1787 free(name); 1788 send: 1789 send_status(e, success); 1790 } 1791 /* 1792 * dispatch incoming message. 1793 * returns 1 on success, 0 for incomplete messages or -1 on error. 1794 */ 1795 static int 1796 process_message(u_int socknum) 1797 { 1798 u_int msg_len; 1799 u_char type; 1800 const u_char *cp; 1801 int r; 1802 SocketEntry *e; 1803 1804 if (socknum >= sockets_alloc) 1805 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc); 1806 e = &sockets[socknum]; 1807 1808 if (sshbuf_len(e->input) < 5) 1809 return 0; /* Incomplete message header. */ 1810 cp = sshbuf_ptr(e->input); 1811 msg_len = PEEK_U32(cp); 1812 if (msg_len > AGENT_MAX_LEN) { 1813 debug_f("socket %u (fd=%d) message too long %u > %u", 1814 socknum, e->fd, msg_len, AGENT_MAX_LEN); 1815 return -1; 1816 } 1817 if (sshbuf_len(e->input) < msg_len + 4) 1818 return 0; /* Incomplete message body. */ 1819 1820 /* move the current input to e->request */ 1821 sshbuf_reset(e->request); 1822 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 || 1823 (r = sshbuf_get_u8(e->request, &type)) != 0) { 1824 if (r == SSH_ERR_MESSAGE_INCOMPLETE || 1825 r == SSH_ERR_STRING_TOO_LARGE) { 1826 error_fr(r, "parse"); 1827 return -1; 1828 } 1829 fatal_fr(r, "parse"); 1830 } 1831 1832 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type); 1833 1834 /* check whether agent is locked */ 1835 if (locked && type != SSH_AGENTC_UNLOCK) { 1836 sshbuf_reset(e->request); 1837 switch (type) { 1838 case SSH2_AGENTC_REQUEST_IDENTITIES: 1839 /* send empty lists */ 1840 no_identities(e); 1841 break; 1842 default: 1843 /* send a fail message for all other request types */ 1844 send_status(e, 0); 1845 } 1846 return 1; 1847 } 1848 1849 switch (type) { 1850 case SSH_AGENTC_LOCK: 1851 case SSH_AGENTC_UNLOCK: 1852 process_lock_agent(e, type == SSH_AGENTC_LOCK); 1853 break; 1854 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES: 1855 process_remove_all_identities(e); /* safe for !WITH_SSH1 */ 1856 break; 1857 /* ssh2 */ 1858 case SSH2_AGENTC_SIGN_REQUEST: 1859 process_sign_request2(e); 1860 break; 1861 case SSH2_AGENTC_REQUEST_IDENTITIES: 1862 process_request_identities(e); 1863 break; 1864 case SSH2_AGENTC_ADD_IDENTITY: 1865 case SSH2_AGENTC_ADD_ID_CONSTRAINED: 1866 process_add_identity(e); 1867 break; 1868 case SSH2_AGENTC_REMOVE_IDENTITY: 1869 process_remove_identity(e); 1870 break; 1871 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: 1872 process_remove_all_identities(e); 1873 break; 1874 #ifdef ENABLE_PKCS11 1875 case SSH_AGENTC_ADD_SMARTCARD_KEY: 1876 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED: 1877 process_add_smartcard_key(e); 1878 break; 1879 case SSH_AGENTC_REMOVE_SMARTCARD_KEY: 1880 process_remove_smartcard_key(e); 1881 break; 1882 #endif /* ENABLE_PKCS11 */ 1883 case SSH_AGENTC_EXTENSION: 1884 process_extension(e); 1885 break; 1886 default: 1887 /* Unknown message. Respond with failure. */ 1888 error("Unknown message %d", type); 1889 sshbuf_reset(e->request); 1890 send_status(e, 0); 1891 break; 1892 } 1893 return 1; 1894 } 1895 1896 static void 1897 new_socket(sock_type type, int fd) 1898 { 1899 u_int i, old_alloc, new_alloc; 1900 1901 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" : 1902 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN")); 1903 set_nonblock(fd); 1904 1905 if (fd > max_fd) 1906 max_fd = fd; 1907 1908 for (i = 0; i < sockets_alloc; i++) 1909 if (sockets[i].type == AUTH_UNUSED) { 1910 sockets[i].fd = fd; 1911 if ((sockets[i].input = sshbuf_new()) == NULL || 1912 (sockets[i].output = sshbuf_new()) == NULL || 1913 (sockets[i].request = sshbuf_new()) == NULL) 1914 fatal_f("sshbuf_new failed"); 1915 sockets[i].type = type; 1916 return; 1917 } 1918 old_alloc = sockets_alloc; 1919 new_alloc = sockets_alloc + 10; 1920 sockets = xrecallocarray(sockets, old_alloc, new_alloc, 1921 sizeof(sockets[0])); 1922 for (i = old_alloc; i < new_alloc; i++) 1923 sockets[i].type = AUTH_UNUSED; 1924 sockets_alloc = new_alloc; 1925 sockets[old_alloc].fd = fd; 1926 if ((sockets[old_alloc].input = sshbuf_new()) == NULL || 1927 (sockets[old_alloc].output = sshbuf_new()) == NULL || 1928 (sockets[old_alloc].request = sshbuf_new()) == NULL) 1929 fatal_f("sshbuf_new failed"); 1930 sockets[old_alloc].type = type; 1931 } 1932 1933 static int 1934 handle_socket_read(u_int socknum) 1935 { 1936 struct sockaddr_un sunaddr; 1937 socklen_t slen; 1938 uid_t euid; 1939 gid_t egid; 1940 int fd; 1941 1942 slen = sizeof(sunaddr); 1943 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen); 1944 if (fd == -1) { 1945 error("accept from AUTH_SOCKET: %s", strerror(errno)); 1946 return -1; 1947 } 1948 if (getpeereid(fd, &euid, &egid) == -1) { 1949 error("getpeereid %d failed: %s", fd, strerror(errno)); 1950 close(fd); 1951 return -1; 1952 } 1953 if ((euid != 0) && (getuid() != euid)) { 1954 error("uid mismatch: peer euid %u != uid %u", 1955 (u_int) euid, (u_int) getuid()); 1956 close(fd); 1957 return -1; 1958 } 1959 new_socket(AUTH_CONNECTION, fd); 1960 return 0; 1961 } 1962 1963 static int 1964 handle_conn_read(u_int socknum) 1965 { 1966 char buf[AGENT_RBUF_LEN]; 1967 ssize_t len; 1968 int r; 1969 1970 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) { 1971 if (len == -1) { 1972 if (errno == EAGAIN || errno == EINTR) 1973 return 0; 1974 error_f("read error on socket %u (fd %d): %s", 1975 socknum, sockets[socknum].fd, strerror(errno)); 1976 } 1977 return -1; 1978 } 1979 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0) 1980 fatal_fr(r, "compose"); 1981 explicit_bzero(buf, sizeof(buf)); 1982 for (;;) { 1983 if ((r = process_message(socknum)) == -1) 1984 return -1; 1985 else if (r == 0) 1986 break; 1987 } 1988 return 0; 1989 } 1990 1991 static int 1992 handle_conn_write(u_int socknum) 1993 { 1994 ssize_t len; 1995 int r; 1996 1997 if (sshbuf_len(sockets[socknum].output) == 0) 1998 return 0; /* shouldn't happen */ 1999 if ((len = write(sockets[socknum].fd, 2000 sshbuf_ptr(sockets[socknum].output), 2001 sshbuf_len(sockets[socknum].output))) <= 0) { 2002 if (len == -1) { 2003 if (errno == EAGAIN || errno == EINTR) 2004 return 0; 2005 error_f("read error on socket %u (fd %d): %s", 2006 socknum, sockets[socknum].fd, strerror(errno)); 2007 } 2008 return -1; 2009 } 2010 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0) 2011 fatal_fr(r, "consume"); 2012 return 0; 2013 } 2014 2015 static void 2016 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds) 2017 { 2018 size_t i; 2019 u_int socknum, activefds = npfd; 2020 2021 for (i = 0; i < npfd; i++) { 2022 if (pfd[i].revents == 0) 2023 continue; 2024 /* Find sockets entry */ 2025 for (socknum = 0; socknum < sockets_alloc; socknum++) { 2026 if (sockets[socknum].type != AUTH_SOCKET && 2027 sockets[socknum].type != AUTH_CONNECTION) 2028 continue; 2029 if (pfd[i].fd == sockets[socknum].fd) 2030 break; 2031 } 2032 if (socknum >= sockets_alloc) { 2033 error_f("no socket for fd %d", pfd[i].fd); 2034 continue; 2035 } 2036 /* Process events */ 2037 switch (sockets[socknum].type) { 2038 case AUTH_SOCKET: 2039 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0) 2040 break; 2041 if (npfd > maxfds) { 2042 debug3("out of fds (active %u >= limit %u); " 2043 "skipping accept", activefds, maxfds); 2044 break; 2045 } 2046 if (handle_socket_read(socknum) == 0) 2047 activefds++; 2048 break; 2049 case AUTH_CONNECTION: 2050 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 && 2051 handle_conn_read(socknum) != 0) 2052 goto close_sock; 2053 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 && 2054 handle_conn_write(socknum) != 0) { 2055 close_sock: 2056 if (activefds == 0) 2057 fatal("activefds == 0 at close_sock"); 2058 close_socket(&sockets[socknum]); 2059 activefds--; 2060 break; 2061 } 2062 break; 2063 default: 2064 break; 2065 } 2066 } 2067 } 2068 2069 static int 2070 prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds) 2071 { 2072 struct pollfd *pfd = *pfdp; 2073 size_t i, j, npfd = 0; 2074 time_t deadline; 2075 int r; 2076 2077 /* Count active sockets */ 2078 for (i = 0; i < sockets_alloc; i++) { 2079 switch (sockets[i].type) { 2080 case AUTH_SOCKET: 2081 case AUTH_CONNECTION: 2082 npfd++; 2083 break; 2084 case AUTH_UNUSED: 2085 break; 2086 default: 2087 fatal("Unknown socket type %d", sockets[i].type); 2088 break; 2089 } 2090 } 2091 if (npfd != *npfdp && 2092 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL) 2093 fatal_f("recallocarray failed"); 2094 *pfdp = pfd; 2095 *npfdp = npfd; 2096 2097 for (i = j = 0; i < sockets_alloc; i++) { 2098 switch (sockets[i].type) { 2099 case AUTH_SOCKET: 2100 if (npfd > maxfds) { 2101 debug3("out of fds (active %zu >= limit %u); " 2102 "skipping arming listener", npfd, maxfds); 2103 break; 2104 } 2105 pfd[j].fd = sockets[i].fd; 2106 pfd[j].revents = 0; 2107 pfd[j].events = POLLIN; 2108 j++; 2109 break; 2110 case AUTH_CONNECTION: 2111 pfd[j].fd = sockets[i].fd; 2112 pfd[j].revents = 0; 2113 /* 2114 * Only prepare to read if we can handle a full-size 2115 * input read buffer and enqueue a max size reply.. 2116 */ 2117 if ((r = sshbuf_check_reserve(sockets[i].input, 2118 AGENT_RBUF_LEN)) == 0 && 2119 (r = sshbuf_check_reserve(sockets[i].output, 2120 AGENT_MAX_LEN)) == 0) 2121 pfd[j].events = POLLIN; 2122 else if (r != SSH_ERR_NO_BUFFER_SPACE) 2123 fatal_fr(r, "reserve"); 2124 if (sshbuf_len(sockets[i].output) > 0) 2125 pfd[j].events |= POLLOUT; 2126 j++; 2127 break; 2128 default: 2129 break; 2130 } 2131 } 2132 deadline = reaper(); 2133 if (parent_alive_interval != 0) 2134 deadline = (deadline == 0) ? parent_alive_interval : 2135 MINIMUM(deadline, parent_alive_interval); 2136 if (deadline != 0) 2137 ptimeout_deadline_sec(timeoutp, deadline); 2138 return (1); 2139 } 2140 2141 static void 2142 cleanup_socket(void) 2143 { 2144 if (cleanup_pid != 0 && getpid() != cleanup_pid) 2145 return; 2146 debug_f("cleanup"); 2147 if (socket_name[0]) 2148 unlink(socket_name); 2149 if (socket_dir[0]) 2150 rmdir(socket_dir); 2151 } 2152 2153 void 2154 cleanup_exit(int i) 2155 { 2156 cleanup_socket(); 2157 #ifdef ENABLE_PKCS11 2158 pkcs11_terminate(); 2159 #endif 2160 _exit(i); 2161 } 2162 2163 static void 2164 cleanup_handler(int sig) 2165 { 2166 signalled_exit = sig; 2167 } 2168 2169 static void 2170 keydrop_handler(int sig) 2171 { 2172 signalled_keydrop = sig; 2173 } 2174 2175 static void 2176 check_parent_exists(void) 2177 { 2178 /* 2179 * If our parent has exited then getppid() will return (pid_t)1, 2180 * so testing for that should be safe. 2181 */ 2182 if (parent_pid != -1 && getppid() != parent_pid) { 2183 /* printf("Parent has died - Authentication agent exiting.\n"); */ 2184 cleanup_socket(); 2185 _exit(2); 2186 } 2187 } 2188 2189 static void 2190 usage(void) 2191 { 2192 fprintf(stderr, 2193 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" 2194 " [-O option] [-P allowed_providers] [-t life]\n" 2195 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n" 2196 " [-P allowed_providers] [-t life] command [arg ...]\n" 2197 " ssh-agent [-c | -s] -k\n"); 2198 exit(1); 2199 } 2200 2201 int 2202 main(int ac, char **av) 2203 { 2204 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0; 2205 int sock, ch, result, saved_errno; 2206 char *shell, *format, *pidstr, *agentsocket = NULL; 2207 const char *ccp; 2208 struct rlimit rlim; 2209 extern int optind; 2210 extern char *optarg; 2211 pid_t pid; 2212 char pidstrbuf[1 + 3 * sizeof pid]; 2213 size_t len; 2214 mode_t prev_mask; 2215 struct timespec timeout; 2216 struct pollfd *pfd = NULL; 2217 size_t npfd = 0; 2218 u_int maxfds; 2219 sigset_t nsigset, osigset; 2220 2221 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 2222 sanitise_stdfd(); 2223 2224 /* drop */ 2225 (void)setegid(getgid()); 2226 (void)setgid(getgid()); 2227 2228 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) 2229 fatal("%s: getrlimit: %s", __progname, strerror(errno)); 2230 2231 #ifdef WITH_OPENSSL 2232 OpenSSL_add_all_algorithms(); 2233 #endif 2234 2235 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) { 2236 switch (ch) { 2237 case 'E': 2238 fingerprint_hash = ssh_digest_alg_by_name(optarg); 2239 if (fingerprint_hash == -1) 2240 fatal("Invalid hash algorithm \"%s\"", optarg); 2241 break; 2242 case 'c': 2243 if (s_flag) 2244 usage(); 2245 c_flag++; 2246 break; 2247 case 'k': 2248 k_flag++; 2249 break; 2250 case 'O': 2251 if (strcmp(optarg, "no-restrict-websafe") == 0) 2252 restrict_websafe = 0; 2253 else if (strcmp(optarg, "allow-remote-pkcs11") == 0) 2254 remote_add_provider = 1; 2255 else if ((ccp = strprefix(optarg, 2256 "websafe-allow=", 0)) != NULL) { 2257 if (websafe_allowlist != NULL) 2258 fatal("websafe-allow already set"); 2259 websafe_allowlist = xstrdup(ccp); 2260 } else 2261 fatal("Unknown -O option"); 2262 break; 2263 case 'P': 2264 if (allowed_providers != NULL) 2265 fatal("-P option already specified"); 2266 allowed_providers = xstrdup(optarg); 2267 break; 2268 case 's': 2269 if (c_flag) 2270 usage(); 2271 s_flag++; 2272 break; 2273 case 'd': 2274 if (d_flag || D_flag) 2275 usage(); 2276 d_flag++; 2277 break; 2278 case 'D': 2279 if (d_flag || D_flag) 2280 usage(); 2281 D_flag++; 2282 break; 2283 case 'a': 2284 agentsocket = optarg; 2285 break; 2286 case 't': 2287 if ((lifetime = convtime(optarg)) == -1) { 2288 fprintf(stderr, "Invalid lifetime\n"); 2289 usage(); 2290 } 2291 break; 2292 default: 2293 usage(); 2294 } 2295 } 2296 ac -= optind; 2297 av += optind; 2298 2299 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag)) 2300 usage(); 2301 2302 if (allowed_providers == NULL) 2303 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS); 2304 if (websafe_allowlist == NULL) 2305 websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST); 2306 2307 if (ac == 0 && !c_flag && !s_flag) { 2308 shell = getenv("SHELL"); 2309 if (shell != NULL && (len = strlen(shell)) > 2 && 2310 strncmp(shell + len - 3, "csh", 3) == 0) 2311 c_flag = 1; 2312 } 2313 if (k_flag) { 2314 const char *errstr = NULL; 2315 2316 pidstr = getenv(SSH_AGENTPID_ENV_NAME); 2317 if (pidstr == NULL) { 2318 fprintf(stderr, "%s not set, cannot kill agent\n", 2319 SSH_AGENTPID_ENV_NAME); 2320 exit(1); 2321 } 2322 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr); 2323 if (errstr) { 2324 fprintf(stderr, 2325 "%s=\"%s\", which is not a good PID: %s\n", 2326 SSH_AGENTPID_ENV_NAME, pidstr, errstr); 2327 exit(1); 2328 } 2329 if (kill(pid, SIGTERM) == -1) { 2330 perror("kill"); 2331 exit(1); 2332 } 2333 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n"; 2334 printf(format, SSH_AUTHSOCKET_ENV_NAME); 2335 printf(format, SSH_AGENTPID_ENV_NAME); 2336 printf("echo Agent pid %ld killed;\n", (long)pid); 2337 exit(0); 2338 } 2339 2340 /* 2341 * Minimum file descriptors: 2342 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) + 2343 * a few spare for libc / stack protectors / sanitisers, etc. 2344 */ 2345 #define SSH_AGENT_MIN_FDS (3+1+1+1+4) 2346 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS) 2347 fatal("%s: file descriptor rlimit %lld too low (minimum %u)", 2348 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS); 2349 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS; 2350 2351 parent_pid = getpid(); 2352 2353 if (agentsocket == NULL) { 2354 /* Create private directory for agent socket */ 2355 mktemp_proto(socket_dir, sizeof(socket_dir)); 2356 if (mkdtemp(socket_dir) == NULL) { 2357 perror("mkdtemp: private socket dir"); 2358 exit(1); 2359 } 2360 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir, 2361 (long)parent_pid); 2362 } else { 2363 /* Try to use specified agent socket */ 2364 socket_dir[0] = '\0'; 2365 strlcpy(socket_name, agentsocket, sizeof socket_name); 2366 } 2367 2368 /* 2369 * Create socket early so it will exist before command gets run from 2370 * the parent. 2371 */ 2372 prev_mask = umask(0177); 2373 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0); 2374 if (sock < 0) { 2375 /* XXX - unix_listener() calls error() not perror() */ 2376 *socket_name = '\0'; /* Don't unlink any existing file */ 2377 cleanup_exit(1); 2378 } 2379 umask(prev_mask); 2380 2381 /* 2382 * Fork, and have the parent execute the command, if any, or present 2383 * the socket data. The child continues as the authentication agent. 2384 */ 2385 if (D_flag || d_flag) { 2386 log_init(__progname, 2387 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 2388 SYSLOG_FACILITY_AUTH, 1); 2389 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 2390 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 2391 SSH_AUTHSOCKET_ENV_NAME); 2392 printf("echo Agent pid %ld;\n", (long)parent_pid); 2393 fflush(stdout); 2394 goto skip; 2395 } 2396 pid = fork(); 2397 if (pid == -1) { 2398 perror("fork"); 2399 cleanup_exit(1); 2400 } 2401 if (pid != 0) { /* Parent - execute the given command. */ 2402 close(sock); 2403 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid); 2404 if (ac == 0) { 2405 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 2406 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name, 2407 SSH_AUTHSOCKET_ENV_NAME); 2408 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf, 2409 SSH_AGENTPID_ENV_NAME); 2410 printf("echo Agent pid %ld;\n", (long)pid); 2411 exit(0); 2412 } 2413 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 || 2414 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) { 2415 perror("setenv"); 2416 exit(1); 2417 } 2418 execvp(av[0], av); 2419 perror(av[0]); 2420 exit(1); 2421 } 2422 /* child */ 2423 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0); 2424 2425 if (setsid() == -1) { 2426 error("setsid: %s", strerror(errno)); 2427 cleanup_exit(1); 2428 } 2429 2430 (void)chdir("/"); 2431 if (stdfd_devnull(1, 1, 1) == -1) 2432 error_f("stdfd_devnull failed"); 2433 2434 /* deny core dumps, since memory contains unencrypted private keys */ 2435 rlim.rlim_cur = rlim.rlim_max = 0; 2436 if (setrlimit(RLIMIT_CORE, &rlim) == -1) { 2437 error("setrlimit RLIMIT_CORE: %s", strerror(errno)); 2438 cleanup_exit(1); 2439 } 2440 2441 skip: 2442 2443 cleanup_pid = getpid(); 2444 2445 #ifdef ENABLE_PKCS11 2446 pkcs11_init(0); 2447 #endif 2448 new_socket(AUTH_SOCKET, sock); 2449 if (ac > 0) 2450 parent_alive_interval = 10; 2451 idtab_init(); 2452 ssh_signal(SIGPIPE, SIG_IGN); 2453 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN); 2454 ssh_signal(SIGHUP, cleanup_handler); 2455 ssh_signal(SIGTERM, cleanup_handler); 2456 ssh_signal(SIGUSR1, keydrop_handler); 2457 2458 sigemptyset(&nsigset); 2459 sigaddset(&nsigset, SIGINT); 2460 sigaddset(&nsigset, SIGHUP); 2461 sigaddset(&nsigset, SIGTERM); 2462 sigaddset(&nsigset, SIGUSR1); 2463 2464 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1) 2465 fatal("%s: pledge: %s", __progname, strerror(errno)); 2466 2467 while (1) { 2468 sigprocmask(SIG_BLOCK, &nsigset, &osigset); 2469 if (signalled_exit != 0) { 2470 logit("exiting on signal %d", (int)signalled_exit); 2471 cleanup_exit(2); 2472 } 2473 if (signalled_keydrop) { 2474 logit("signal %d received; removing all keys", 2475 signalled_keydrop); 2476 remove_all_identities(); 2477 signalled_keydrop = 0; 2478 } 2479 ptimeout_init(&timeout); 2480 prepare_poll(&pfd, &npfd, &timeout, maxfds); 2481 result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset); 2482 sigprocmask(SIG_SETMASK, &osigset, NULL); 2483 saved_errno = errno; 2484 if (parent_alive_interval != 0) 2485 check_parent_exists(); 2486 (void) reaper(); /* remove expired keys */ 2487 if (result == -1) { 2488 if (saved_errno == EINTR) 2489 continue; 2490 fatal("poll: %s", strerror(saved_errno)); 2491 } else if (result > 0) 2492 after_poll(pfd, npfd, maxfds); 2493 } 2494 /* NOTREACHED */ 2495 } 2496