jcs's openbsd hax
openbsd
at jcs 2541 lines 68 kB view raw
1/* $OpenBSD: ssh-agent.c,v 1.319 2026/02/16 23:47:06 jsg 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 103typedef enum { 104 AUTH_UNUSED = 0, 105 AUTH_SOCKET = 1, 106 AUTH_CONNECTION = 2, 107} sock_type; 108 109struct hostkey_sid { 110 struct sshkey *key; 111 struct sshbuf *sid; 112 int forwarded; 113}; 114 115typedef 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 126u_int sockets_alloc = 0; 127SocketEntry *sockets = NULL; 128 129typedef 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 141struct idtable { 142 int nentries; 143 TAILQ_HEAD(idqueue, identity) idlist; 144}; 145 146/* private key table */ 147struct idtable *idtab; 148 149int max_fd = 0; 150 151/* pid of shell == parent of agent */ 152pid_t parent_pid = -1; 153time_t parent_alive_interval = 0; 154 155static sig_atomic_t signalled_exit; 156static sig_atomic_t signalled_keydrop; 157 158/* pid of process for which cleanup_socket is applicable */ 159pid_t cleanup_pid = 0; 160 161/* pathname and directory for AUTH_SOCKET */ 162static char *socket_name; 163static char socket_dir[PATH_MAX]; 164 165/* Pattern-list of allowed PKCS#11/Security key paths */ 166static 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 */ 172static int remote_add_provider; 173 174/* locking */ 175#define LOCK_SIZE 32 176#define LOCK_SALT_SIZE 16 177#define LOCK_ROUNDS 1 178int locked = 0; 179u_char lock_pwhash[LOCK_SIZE]; 180u_char lock_salt[LOCK_SALT_SIZE]; 181 182extern char *__progname; 183 184/* Default lifetime in seconds (0 == forever) */ 185static int lifetime = 0; 186 187static int fingerprint_hash = SSH_FP_HASH_DEFAULT; 188 189/* Refuse signing of non-SSH messages for web-origin FIDO keys */ 190static int restrict_websafe = 1; 191static char *websafe_allowlist; 192 193static void 194close_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 212static void 213idtab_init(void) 214{ 215 idtab = xcalloc(1, sizeof(*idtab)); 216 TAILQ_INIT(&idtab->idlist); 217 idtab->nentries = 0; 218} 219 220static void 221free_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 235static void 236free_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 248static void 249dup_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 272static struct dest_constraint * 273dup_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 290static void 291dump_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 316static void 317dump_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 334static void 335free_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 */ 349static int 350match_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, 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 */ 404static int 405permitted_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 */ 460static int 461identity_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 560static int 561socket_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 */ 567static Identity * 568lookup_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 */ 580static int 581confirm_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 597static void 598send_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' */ 609static void 610process_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(id->key, keys)) != 0 || 635 (r = sshbuf_put_cstring(keys, id->comment)) != 0) { 636 error_fr(r, "compose key/comment"); 637 continue; 638 } 639 nentries++; 640 } 641 debug2_f("replying with %u allowed of %u available keys", 642 nentries, idtab->nentries); 643 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 644 (r = sshbuf_put_u32(msg, nentries)) != 0 || 645 (r = sshbuf_putb(msg, keys)) != 0) 646 fatal_fr(r, "compose"); 647 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 648 fatal_fr(r, "enqueue"); 649 sshbuf_free(msg); 650 sshbuf_free(keys); 651} 652 653 654static char * 655agent_decode_alg(struct sshkey *key, u_int flags) 656{ 657 if (key->type == KEY_RSA) { 658 if (flags & SSH_AGENT_RSA_SHA2_256) 659 return "rsa-sha2-256"; 660 else if (flags & SSH_AGENT_RSA_SHA2_512) 661 return "rsa-sha2-512"; 662 } else if (key->type == KEY_RSA_CERT) { 663 if (flags & SSH_AGENT_RSA_SHA2_256) 664 return "rsa-sha2-256-cert-v01@openssh.com"; 665 else if (flags & SSH_AGENT_RSA_SHA2_512) 666 return "rsa-sha2-512-cert-v01@openssh.com"; 667 } 668 return NULL; 669} 670 671/* 672 * Attempt to parse the contents of a buffer as a SSH publickey userauth 673 * request, checking its contents for consistency and matching the embedded 674 * key against the one that is being used for signing. 675 * Note: does not modify msg buffer. 676 * Optionally extract the username, session ID and/or hostkey from the request. 677 */ 678static int 679parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key, 680 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp) 681{ 682 struct sshbuf *b = NULL, *sess_id = NULL; 683 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL; 684 int r; 685 u_char t, sig_follows; 686 struct sshkey *mkey = NULL, *hostkey = NULL; 687 688 if (userp != NULL) 689 *userp = NULL; 690 if (sess_idp != NULL) 691 *sess_idp = NULL; 692 if (hostkeyp != NULL) 693 *hostkeyp = NULL; 694 if ((b = sshbuf_fromb(msg)) == NULL) 695 fatal_f("sshbuf_fromb"); 696 697 /* SSH userauth request */ 698 if ((r = sshbuf_froms(b, &sess_id)) != 0) 699 goto out; 700 if (sshbuf_len(sess_id) == 0) { 701 r = SSH_ERR_INVALID_FORMAT; 702 goto out; 703 } 704 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */ 705 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */ 706 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */ 707 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */ 708 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */ 709 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */ 710 (r = sshkey_froms(b, &mkey)) != 0) /* key */ 711 goto out; 712 if (t != SSH2_MSG_USERAUTH_REQUEST || 713 sig_follows != 1 || 714 strcmp(service, "ssh-connection") != 0 || 715 !sshkey_equal(expected_key, mkey) || 716 sshkey_type_from_name(pkalg) != expected_key->type) { 717 r = SSH_ERR_INVALID_FORMAT; 718 goto out; 719 } 720 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) { 721 if ((r = sshkey_froms(b, &hostkey)) != 0) 722 goto out; 723 } else if (strcmp(method, "publickey") != 0) { 724 r = SSH_ERR_INVALID_FORMAT; 725 goto out; 726 } 727 if (sshbuf_len(b) != 0) { 728 r = SSH_ERR_INVALID_FORMAT; 729 goto out; 730 } 731 /* success */ 732 r = 0; 733 debug3_f("well formed userauth"); 734 if (userp != NULL) { 735 *userp = user; 736 user = NULL; 737 } 738 if (sess_idp != NULL) { 739 *sess_idp = sess_id; 740 sess_id = NULL; 741 } 742 if (hostkeyp != NULL) { 743 *hostkeyp = hostkey; 744 hostkey = NULL; 745 } 746 out: 747 sshbuf_free(b); 748 sshbuf_free(sess_id); 749 free(user); 750 free(service); 751 free(method); 752 free(pkalg); 753 sshkey_free(mkey); 754 sshkey_free(hostkey); 755 return r; 756} 757 758/* 759 * Attempt to parse the contents of a buffer as a SSHSIG signature request. 760 * Note: does not modify buffer. 761 */ 762static int 763parse_sshsig_request(struct sshbuf *msg) 764{ 765 int r; 766 struct sshbuf *b; 767 768 if ((b = sshbuf_fromb(msg)) == NULL) 769 fatal_f("sshbuf_fromb"); 770 771 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 || 772 (r = sshbuf_consume(b, 6)) != 0 || 773 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */ 774 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */ 775 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */ 776 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */ 777 goto out; 778 if (sshbuf_len(b) != 0) { 779 r = SSH_ERR_INVALID_FORMAT; 780 goto out; 781 } 782 /* success */ 783 r = 0; 784 out: 785 sshbuf_free(b); 786 return r; 787} 788 789/* 790 * This function inspects a message to be signed by a FIDO key that has a 791 * web-like application string (i.e. one that does not begin with "ssh:". 792 * It checks that the message is one of those expected for SSH operations 793 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges 794 * for the web. 795 */ 796static int 797check_websafe_message_contents(struct sshkey *key, struct sshbuf *data) 798{ 799 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) { 800 debug_f("signed data matches public key userauth request"); 801 return 1; 802 } 803 if (parse_sshsig_request(data) == 0) { 804 debug_f("signed data matches SSHSIG signature request"); 805 return 1; 806 } 807 808 /* XXX check CA signature operation */ 809 810 error("web-origin key attempting to sign non-SSH message"); 811 return 0; 812} 813 814static int 815buf_equal(const struct sshbuf *a, const struct sshbuf *b) 816{ 817 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL) 818 return SSH_ERR_INVALID_ARGUMENT; 819 if (sshbuf_len(a) != sshbuf_len(b)) 820 return SSH_ERR_INVALID_FORMAT; 821 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0) 822 return SSH_ERR_INVALID_FORMAT; 823 return 0; 824} 825 826/* ssh2 only */ 827static void 828process_sign_request2(SocketEntry *e) 829{ 830 u_char *signature = NULL; 831 size_t slen = 0; 832 u_int compat = 0, flags; 833 int r, ok = -1, retried = 0; 834 char *fp = NULL, *pin = NULL, *prompt = NULL; 835 char *user = NULL, *sig_dest = NULL; 836 const char *fwd_host = NULL, *dest_host = NULL; 837 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL; 838 struct sshkey *key = NULL, *hostkey = NULL; 839 struct identity *id; 840 struct notifier_ctx *notifier = NULL; 841 842 debug_f("entering"); 843 844 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL) 845 fatal_f("sshbuf_new failed"); 846 if ((r = sshkey_froms(e->request, &key)) != 0 || 847 (r = sshbuf_get_stringb(e->request, data)) != 0 || 848 (r = sshbuf_get_u32(e->request, &flags)) != 0) { 849 error_fr(r, "parse"); 850 goto send; 851 } 852 853 if ((id = lookup_identity(key)) == NULL) { 854 verbose_f("%s key not found", sshkey_type(key)); 855 goto send; 856 } 857 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT, 858 SSH_FP_DEFAULT)) == NULL) 859 fatal_f("fingerprint failed"); 860 861 if (id->ndest_constraints != 0) { 862 if (e->nsession_ids == 0) { 863 logit_f("refusing use of destination-constrained key " 864 "to sign on unbound connection"); 865 goto send; 866 } 867 if (parse_userauth_request(data, key, &user, &sid, 868 &hostkey) != 0) { 869 logit_f("refusing use of destination-constrained key " 870 "to sign an unidentified signature"); 871 goto send; 872 } 873 /* XXX logspam */ 874 debug_f("user=%s", user); 875 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0) 876 goto send; 877 /* XXX display fwd_host/dest_host in askpass UI */ 878 /* 879 * Ensure that the session ID is the most recent one 880 * registered on the socket - it should have been bound by 881 * ssh immediately before userauth. 882 */ 883 if (buf_equal(sid, 884 e->session_ids[e->nsession_ids - 1].sid) != 0) { 885 error_f("unexpected session ID (%zu listed) on " 886 "signature request for target user %s with " 887 "key %s %s", e->nsession_ids, user, 888 sshkey_type(id->key), fp); 889 goto send; 890 } 891 /* 892 * Ensure that the hostkey embedded in the signature matches 893 * the one most recently bound to the socket. An exception is 894 * made for the initial forwarding hop. 895 */ 896 if (e->nsession_ids > 1 && hostkey == NULL) { 897 error_f("refusing use of destination-constrained key: " 898 "no hostkey recorded in signature for forwarded " 899 "connection"); 900 goto send; 901 } 902 if (hostkey != NULL && !sshkey_equal(hostkey, 903 e->session_ids[e->nsession_ids - 1].key)) { 904 error_f("refusing use of destination-constrained key: " 905 "mismatch between hostkey in request and most " 906 "recently bound session"); 907 goto send; 908 } 909 xasprintf(&sig_dest, "public key authentication request for " 910 "user \"%s\" to listed host", user); 911 } 912 if (id->confirm && confirm_key(id, sig_dest) != 0) { 913 verbose_f("user refused key"); 914 goto send; 915 } 916 if (sshkey_is_sk(id->key)) { 917 if (restrict_websafe && 918 match_pattern_list(id->key->sk_application, 919 websafe_allowlist, 0) != 1 && 920 !check_websafe_message_contents(key, data)) { 921 /* error already logged */ 922 goto send; 923 } 924 if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) { 925 notifier = notify_start(0, 926 "Confirm user presence for key %s %s%s%s", 927 sshkey_type(id->key), fp, 928 sig_dest == NULL ? "" : "\n", 929 sig_dest == NULL ? "" : sig_dest); 930 } 931 } 932 retry_pin: 933 if ((r = sshkey_sign(id->key, &signature, &slen, 934 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags), 935 id->sk_provider, pin, compat)) != 0) { 936 debug_fr(r, "sshkey_sign"); 937 if (pin == NULL && !retried && sshkey_is_sk(id->key) && 938 r == SSH_ERR_KEY_WRONG_PASSPHRASE) { 939 notify_complete(notifier, NULL); 940 notifier = NULL; 941 /* XXX include sig_dest */ 942 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ", 943 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ? 944 " and confirm user presence " : " ", 945 sshkey_type(id->key), fp); 946 pin = read_passphrase(prompt, RP_USE_ASKPASS); 947 retried = 1; 948 goto retry_pin; 949 } 950 error_fr(r, "sshkey_sign"); 951 goto send; 952 } 953 /* Success */ 954 ok = 0; 955 debug_f("good signature"); 956 send: 957 notify_complete(notifier, "User presence confirmed"); 958 959 if (ok == 0) { 960 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 || 961 (r = sshbuf_put_string(msg, signature, slen)) != 0) 962 fatal_fr(r, "compose"); 963 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0) 964 fatal_fr(r, "compose failure"); 965 966 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 967 fatal_fr(r, "enqueue"); 968 969 sshbuf_free(sid); 970 sshbuf_free(data); 971 sshbuf_free(msg); 972 sshkey_free(key); 973 sshkey_free(hostkey); 974 free(fp); 975 free(signature); 976 free(sig_dest); 977 free(user); 978 free(prompt); 979 if (pin != NULL) 980 freezero(pin, strlen(pin)); 981} 982 983/* shared */ 984static void 985process_remove_identity(SocketEntry *e) 986{ 987 int r, success = 0; 988 struct sshkey *key = NULL; 989 Identity *id; 990 991 debug2_f("entering"); 992 if ((r = sshkey_froms(e->request, &key)) != 0) { 993 error_fr(r, "parse key"); 994 goto done; 995 } 996 if ((id = lookup_identity(key)) == NULL) { 997 debug_f("key not found"); 998 goto done; 999 } 1000 /* identity not visible, cannot be removed */ 1001 if (identity_permitted(id, e, NULL, NULL, NULL) != 0) 1002 goto done; /* error already logged */ 1003 /* We have this key, free it. */ 1004 if (idtab->nentries < 1) 1005 fatal_f("internal error: nentries %d", idtab->nentries); 1006 TAILQ_REMOVE(&idtab->idlist, id, next); 1007 free_identity(id); 1008 idtab->nentries--; 1009 success = 1; 1010 done: 1011 sshkey_free(key); 1012 send_status(e, success); 1013} 1014 1015static void 1016remove_all_identities(void) 1017{ 1018 Identity *id; 1019 1020 debug2_f("entering"); 1021 /* Loop over all identities and clear the keys. */ 1022 for (id = TAILQ_FIRST(&idtab->idlist); id; 1023 id = TAILQ_FIRST(&idtab->idlist)) { 1024 TAILQ_REMOVE(&idtab->idlist, id, next); 1025 free_identity(id); 1026 } 1027 1028 /* Mark that there are no identities. */ 1029 idtab->nentries = 0; 1030} 1031 1032static void 1033process_remove_all_identities(SocketEntry *e) 1034{ 1035 remove_all_identities(); 1036 1037 /* Send success. */ 1038 send_status(e, 1); 1039} 1040 1041/* removes expired keys and returns number of seconds until the next expiry */ 1042static time_t 1043reaper(void) 1044{ 1045 time_t deadline = 0, now = monotime(); 1046 Identity *id, *nxt; 1047 1048 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 1049 nxt = TAILQ_NEXT(id, next); 1050 if (id->death == 0) 1051 continue; 1052 if (now >= id->death) { 1053 debug("expiring key '%s'", id->comment); 1054 TAILQ_REMOVE(&idtab->idlist, id, next); 1055 free_identity(id); 1056 idtab->nentries--; 1057 } else 1058 deadline = (deadline == 0) ? id->death : 1059 MINIMUM(deadline, id->death); 1060 } 1061 if (deadline == 0 || deadline <= now) 1062 return 0; 1063 else 1064 return (deadline - now); 1065} 1066 1067static int 1068parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch) 1069{ 1070 u_char key_is_ca; 1071 size_t elen = 0; 1072 int r; 1073 struct sshkey *k = NULL; 1074 char *fp; 1075 1076 memset(dch, '\0', sizeof(*dch)); 1077 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 || 1078 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 || 1079 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) { 1080 error_fr(r, "parse"); 1081 goto out; 1082 } 1083 if (elen != 0) { 1084 error_f("unsupported extensions (len %zu)", elen); 1085 r = SSH_ERR_FEATURE_UNSUPPORTED; 1086 goto out; 1087 } 1088 if (*dch->hostname == '\0') { 1089 free(dch->hostname); 1090 dch->hostname = NULL; 1091 } 1092 if (*dch->user == '\0') { 1093 free(dch->user); 1094 dch->user = NULL; 1095 } 1096 while (sshbuf_len(b) != 0) { 1097 dch->keys = xrecallocarray(dch->keys, dch->nkeys, 1098 dch->nkeys + 1, sizeof(*dch->keys)); 1099 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys, 1100 dch->nkeys + 1, sizeof(*dch->key_is_ca)); 1101 if ((r = sshkey_froms(b, &k)) != 0 || 1102 (r = sshbuf_get_u8(b, &key_is_ca)) != 0) 1103 goto out; 1104 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT, 1105 SSH_FP_DEFAULT)) == NULL) 1106 fatal_f("fingerprint failed"); 1107 debug3_f("%s%s%s: adding %skey %s %s", 1108 dch->user == NULL ? "" : dch->user, 1109 dch->user == NULL ? "" : "@", 1110 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp); 1111 free(fp); 1112 dch->keys[dch->nkeys] = k; 1113 dch->key_is_ca[dch->nkeys] = key_is_ca != 0; 1114 dch->nkeys++; 1115 k = NULL; /* transferred */ 1116 } 1117 /* success */ 1118 r = 0; 1119 out: 1120 sshkey_free(k); 1121 return r; 1122} 1123 1124static int 1125parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc) 1126{ 1127 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL; 1128 int r; 1129 size_t elen = 0; 1130 1131 debug3_f("entering"); 1132 1133 memset(dc, '\0', sizeof(*dc)); 1134 if ((r = sshbuf_froms(m, &b)) != 0 || 1135 (r = sshbuf_froms(b, &frombuf)) != 0 || 1136 (r = sshbuf_froms(b, &tobuf)) != 0 || 1137 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) { 1138 error_fr(r, "parse"); 1139 goto out; 1140 } 1141 if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 || 1142 (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0) 1143 goto out; /* already logged */ 1144 if (elen != 0) { 1145 error_f("unsupported extensions (len %zu)", elen); 1146 r = SSH_ERR_FEATURE_UNSUPPORTED; 1147 goto out; 1148 } 1149 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)", 1150 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys, 1151 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "", 1152 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys); 1153 /* check consistency */ 1154 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) || 1155 dc->from.user != NULL) { 1156 error_f("inconsistent \"from\" specification"); 1157 r = SSH_ERR_INVALID_FORMAT; 1158 goto out; 1159 } 1160 if (dc->to.hostname == NULL || dc->to.nkeys == 0) { 1161 error_f("incomplete \"to\" specification"); 1162 r = SSH_ERR_INVALID_FORMAT; 1163 goto out; 1164 } 1165 /* success */ 1166 r = 0; 1167 out: 1168 sshbuf_free(b); 1169 sshbuf_free(frombuf); 1170 sshbuf_free(tobuf); 1171 return r; 1172} 1173 1174static int 1175parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp, 1176 struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp, 1177 struct sshkey ***certs, size_t *ncerts) 1178{ 1179 char *ext_name = NULL; 1180 int r; 1181 struct sshbuf *b = NULL; 1182 u_char v; 1183 struct sshkey *k; 1184 1185 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) { 1186 error_fr(r, "parse constraint extension"); 1187 goto out; 1188 } 1189 debug_f("constraint ext %s", ext_name); 1190 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) { 1191 if (sk_providerp == NULL) { 1192 error_f("%s not valid here", ext_name); 1193 r = SSH_ERR_INVALID_FORMAT; 1194 goto out; 1195 } 1196 if (*sk_providerp != NULL) { 1197 error_f("%s already set", ext_name); 1198 r = SSH_ERR_INVALID_FORMAT; 1199 goto out; 1200 } 1201 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) { 1202 error_fr(r, "parse %s", ext_name); 1203 goto out; 1204 } 1205 } else if (strcmp(ext_name, 1206 "restrict-destination-v00@openssh.com") == 0) { 1207 if (*dcsp != NULL) { 1208 error_f("%s already set", ext_name); 1209 r = SSH_ERR_INVALID_FORMAT; 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 r = SSH_ERR_INVALID_FORMAT; 1220 goto out; 1221 } 1222 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1, 1223 sizeof(**dcsp)); 1224 if ((r = parse_dest_constraint(b, 1225 *dcsp + (*ndcsp)++)) != 0) 1226 goto out; /* error already logged */ 1227 } 1228 } else if (strcmp(ext_name, 1229 "associated-certs-v00@openssh.com") == 0) { 1230 if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) { 1231 error_f("%s not valid here", ext_name); 1232 r = SSH_ERR_INVALID_FORMAT; 1233 goto out; 1234 } 1235 if (*certs != NULL) { 1236 error_f("%s already set", ext_name); 1237 r = SSH_ERR_INVALID_FORMAT; 1238 goto out; 1239 } 1240 if ((r = sshbuf_get_u8(m, &v)) != 0 || 1241 (r = sshbuf_froms(m, &b)) != 0) { 1242 error_fr(r, "parse %s", ext_name); 1243 goto out; 1244 } 1245 *cert_onlyp = v != 0; 1246 while (sshbuf_len(b) != 0) { 1247 if (*ncerts >= AGENT_MAX_EXT_CERTS) { 1248 error_f("too many %s constraints", ext_name); 1249 r = SSH_ERR_INVALID_FORMAT; 1250 goto out; 1251 } 1252 *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1, 1253 sizeof(**certs)); 1254 if ((r = sshkey_froms(b, &k)) != 0) { 1255 error_fr(r, "parse key"); 1256 goto out; 1257 } 1258 (*certs)[(*ncerts)++] = k; 1259 } 1260 } else { 1261 error_f("unsupported constraint \"%s\"", ext_name); 1262 r = SSH_ERR_FEATURE_UNSUPPORTED; 1263 goto out; 1264 } 1265 /* success */ 1266 r = 0; 1267 out: 1268 free(ext_name); 1269 sshbuf_free(b); 1270 return r; 1271} 1272 1273static int 1274parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp, 1275 u_int *secondsp, int *confirmp, char **sk_providerp, 1276 struct dest_constraint **dcsp, size_t *ndcsp, 1277 int *cert_onlyp, size_t *ncerts, struct sshkey ***certs) 1278{ 1279 u_char ctype; 1280 int r; 1281 u_int seconds; 1282 1283 while (sshbuf_len(m)) { 1284 if ((r = sshbuf_get_u8(m, &ctype)) != 0) { 1285 error_fr(r, "parse constraint type"); 1286 goto out; 1287 } 1288 switch (ctype) { 1289 case SSH_AGENT_CONSTRAIN_LIFETIME: 1290 if (*deathp != 0) { 1291 error_f("lifetime already set"); 1292 r = SSH_ERR_INVALID_FORMAT; 1293 goto out; 1294 } 1295 if ((r = sshbuf_get_u32(m, &seconds)) != 0) { 1296 error_fr(r, "parse lifetime constraint"); 1297 goto out; 1298 } 1299 *deathp = monotime() + seconds; 1300 *secondsp = seconds; 1301 break; 1302 case SSH_AGENT_CONSTRAIN_CONFIRM: 1303 if (*confirmp != 0) { 1304 error_f("confirm already set"); 1305 r = SSH_ERR_INVALID_FORMAT; 1306 goto out; 1307 } 1308 *confirmp = 1; 1309 break; 1310 case SSH_AGENT_CONSTRAIN_EXTENSION: 1311 if ((r = parse_key_constraint_extension(m, 1312 sk_providerp, dcsp, ndcsp, 1313 cert_onlyp, certs, ncerts)) != 0) 1314 goto out; /* error already logged */ 1315 break; 1316 default: 1317 error_f("Unknown constraint %d", ctype); 1318 r = SSH_ERR_FEATURE_UNSUPPORTED; 1319 goto out; 1320 } 1321 } 1322 /* success */ 1323 r = 0; 1324 out: 1325 return r; 1326} 1327 1328static void 1329process_add_identity(SocketEntry *e) 1330{ 1331 Identity *id; 1332 int success = 0, confirm = 0; 1333 char *fp, *comment = NULL, *sk_provider = NULL; 1334 char canonical_provider[PATH_MAX]; 1335 time_t death = 0; 1336 u_int seconds = 0; 1337 struct dest_constraint *dest_constraints = NULL; 1338 size_t ndest_constraints = 0; 1339 struct sshkey *k = NULL; 1340 int r = SSH_ERR_INTERNAL_ERROR; 1341 1342 debug2_f("entering"); 1343 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 || 1344 k == NULL || 1345 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) { 1346 error_fr(r, "parse"); 1347 goto out; 1348 } 1349 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm, 1350 &sk_provider, &dest_constraints, &ndest_constraints, 1351 NULL, NULL, NULL) != 0) { 1352 error_f("failed to parse constraints"); 1353 sshbuf_reset(e->request); 1354 goto out; 1355 } 1356 dump_dest_constraints(__func__, dest_constraints, ndest_constraints); 1357 1358 if (sk_provider != NULL) { 1359 if (!sshkey_is_sk(k)) { 1360 error("Cannot add provider: %s is not an " 1361 "authenticator-hosted key", sshkey_type(k)); 1362 goto out; 1363 } 1364 if (strcasecmp(sk_provider, "internal") == 0) { 1365 debug_f("internal provider"); 1366 } else { 1367 if (socket_is_remote(e) && !remote_add_provider) { 1368 verbose("failed add of SK provider \"%.100s\": " 1369 "remote addition of providers is disabled", 1370 sk_provider); 1371 goto out; 1372 } 1373 if (realpath(sk_provider, canonical_provider) == NULL) { 1374 verbose("failed provider \"%.100s\": " 1375 "realpath: %s", sk_provider, 1376 strerror(errno)); 1377 goto out; 1378 } 1379 free(sk_provider); 1380 sk_provider = xstrdup(canonical_provider); 1381 if (match_pattern_list(sk_provider, 1382 allowed_providers, 0) != 1) { 1383 error("Refusing add key: " 1384 "provider %s not allowed", sk_provider); 1385 goto out; 1386 } 1387 } 1388 } 1389 if ((r = sshkey_shield_private(k)) != 0) { 1390 error_fr(r, "shield private"); 1391 goto out; 1392 } 1393 if (lifetime && !death) 1394 death = monotime() + lifetime; 1395 if ((id = lookup_identity(k)) == NULL) { 1396 id = xcalloc(1, sizeof(Identity)); 1397 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 1398 /* Increment the number of identities. */ 1399 idtab->nentries++; 1400 } else { 1401 /* identity not visible, do not update */ 1402 if (identity_permitted(id, e, NULL, NULL, NULL) != 0) 1403 goto out; /* error already logged */ 1404 /* key state might have been updated */ 1405 sshkey_free(id->key); 1406 free(id->comment); 1407 free(id->sk_provider); 1408 free_dest_constraints(id->dest_constraints, 1409 id->ndest_constraints); 1410 } 1411 /* success */ 1412 id->key = k; 1413 id->comment = comment; 1414 id->death = death; 1415 id->confirm = confirm; 1416 id->sk_provider = sk_provider; 1417 id->dest_constraints = dest_constraints; 1418 id->ndest_constraints = ndest_constraints; 1419 1420 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT, 1421 SSH_FP_DEFAULT)) == NULL) 1422 fatal_f("sshkey_fingerprint failed"); 1423 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) " 1424 "(provider: %s) (destination constraints: %zu)", 1425 sshkey_ssh_name(k), fp, comment, seconds, confirm, 1426 sk_provider == NULL ? "none" : sk_provider, ndest_constraints); 1427 free(fp); 1428 /* transferred */ 1429 k = NULL; 1430 comment = NULL; 1431 sk_provider = NULL; 1432 dest_constraints = NULL; 1433 ndest_constraints = 0; 1434 success = 1; 1435 out: 1436 free(sk_provider); 1437 free(comment); 1438 sshkey_free(k); 1439 free_dest_constraints(dest_constraints, ndest_constraints); 1440 send_status(e, success); 1441} 1442 1443/* XXX todo: encrypt sensitive data with passphrase */ 1444static void 1445process_lock_agent(SocketEntry *e, int lock) 1446{ 1447 int r, success = 0, delay; 1448 char *passwd; 1449 u_char passwdhash[LOCK_SIZE]; 1450 static u_int fail_count = 0; 1451 size_t pwlen; 1452 1453 debug2_f("entering"); 1454 /* 1455 * This is deliberately fatal: the user has requested that we lock, 1456 * but we can't parse their request properly. The only safe thing to 1457 * do is abort. 1458 */ 1459 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0) 1460 fatal_fr(r, "parse"); 1461 if (pwlen == 0) { 1462 debug("empty password not supported"); 1463 } else if (locked && !lock) { 1464 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 1465 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0) 1466 fatal("bcrypt_pbkdf"); 1467 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) { 1468 debug("agent unlocked"); 1469 locked = 0; 1470 fail_count = 0; 1471 explicit_bzero(lock_pwhash, sizeof(lock_pwhash)); 1472 success = 1; 1473 } else { 1474 /* delay in 0.1s increments up to 10s */ 1475 if (fail_count < 100) 1476 fail_count++; 1477 delay = 100000 * fail_count; 1478 debug("unlock failed, delaying %0.1lf seconds", 1479 (double)delay/1000000); 1480 usleep(delay); 1481 } 1482 explicit_bzero(passwdhash, sizeof(passwdhash)); 1483 } else if (!locked && lock) { 1484 debug("agent locked"); 1485 locked = 1; 1486 arc4random_buf(lock_salt, sizeof(lock_salt)); 1487 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt), 1488 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0) 1489 fatal("bcrypt_pbkdf"); 1490 success = 1; 1491 } 1492 freezero(passwd, pwlen); 1493 send_status(e, success); 1494} 1495 1496static void 1497no_identities(SocketEntry *e) 1498{ 1499 struct sshbuf *msg; 1500 int r; 1501 1502 if ((msg = sshbuf_new()) == NULL) 1503 fatal_f("sshbuf_new failed"); 1504 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 || 1505 (r = sshbuf_put_u32(msg, 0)) != 0 || 1506 (r = sshbuf_put_stringb(e->output, msg)) != 0) 1507 fatal_fr(r, "compose"); 1508 sshbuf_free(msg); 1509} 1510 1511#ifdef ENABLE_PKCS11 1512/* Add an identity to idlist; takes ownership of 'key' and 'comment' */ 1513static void 1514add_p11_identity(struct sshkey *key, char *comment, const char *provider, 1515 time_t death, u_int confirm, struct dest_constraint *dest_constraints, 1516 size_t ndest_constraints) 1517{ 1518 Identity *id; 1519 1520 if (lookup_identity(key) != NULL) { 1521 sshkey_free(key); 1522 free(comment); 1523 return; 1524 } 1525 id = xcalloc(1, sizeof(Identity)); 1526 id->key = key; 1527 id->comment = comment; 1528 id->provider = xstrdup(provider); 1529 id->death = death; 1530 id->confirm = confirm; 1531 id->dest_constraints = dup_dest_constraints(dest_constraints, 1532 ndest_constraints); 1533 id->ndest_constraints = ndest_constraints; 1534 TAILQ_INSERT_TAIL(&idtab->idlist, id, next); 1535 idtab->nentries++; 1536} 1537 1538static void 1539process_add_smartcard_key(SocketEntry *e) 1540{ 1541 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 1542 char **comments = NULL; 1543 int r, i, count = 0, success = 0, confirm = 0; 1544 u_int seconds = 0; 1545 time_t death = 0; 1546 struct sshkey **keys = NULL, *k; 1547 struct dest_constraint *dest_constraints = NULL; 1548 size_t j, ndest_constraints = 0, ncerts = 0; 1549 struct sshkey **certs = NULL; 1550 int cert_only = 0; 1551 1552 debug2_f("entering"); 1553 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 1554 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 1555 error_fr(r, "parse"); 1556 goto send; 1557 } 1558 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm, 1559 NULL, &dest_constraints, &ndest_constraints, &cert_only, 1560 &ncerts, &certs) != 0) { 1561 error_f("failed to parse constraints"); 1562 goto send; 1563 } 1564 dump_dest_constraints(__func__, dest_constraints, ndest_constraints); 1565 if (socket_is_remote(e) && !remote_add_provider) { 1566 verbose("failed PKCS#11 add of \"%.100s\": remote addition of " 1567 "providers is disabled", provider); 1568 goto send; 1569 } 1570 if (realpath(provider, canonical_provider) == NULL) { 1571 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 1572 provider, strerror(errno)); 1573 goto send; 1574 } 1575 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) { 1576 verbose("refusing PKCS#11 add of \"%.100s\": " 1577 "provider not allowed", canonical_provider); 1578 goto send; 1579 } 1580 debug_f("add %.100s", canonical_provider); 1581 if (lifetime && !death) 1582 death = monotime() + lifetime; 1583 1584 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments); 1585 for (i = 0; i < count; i++) { 1586 if (comments[i] == NULL || comments[i][0] == '\0') { 1587 free(comments[i]); 1588 comments[i] = xstrdup(canonical_provider); 1589 } 1590 for (j = 0; j < ncerts; j++) { 1591 if (!sshkey_is_cert(certs[j])) 1592 continue; 1593 if (!sshkey_equal_public(keys[i], certs[j])) 1594 continue; 1595 if (pkcs11_make_cert(keys[i], certs[j], &k) != 0) 1596 continue; 1597 add_p11_identity(k, xstrdup(comments[i]), 1598 canonical_provider, death, confirm, 1599 dest_constraints, ndest_constraints); 1600 success = 1; 1601 } 1602 if (!cert_only && lookup_identity(keys[i]) == NULL) { 1603 add_p11_identity(keys[i], comments[i], 1604 canonical_provider, death, confirm, 1605 dest_constraints, ndest_constraints); 1606 keys[i] = NULL; /* transferred */ 1607 comments[i] = NULL; /* transferred */ 1608 success = 1; 1609 } 1610 /* XXX update constraints for existing keys */ 1611 sshkey_free(keys[i]); 1612 free(comments[i]); 1613 } 1614send: 1615 free(pin); 1616 free(provider); 1617 free(keys); 1618 free(comments); 1619 free_dest_constraints(dest_constraints, ndest_constraints); 1620 for (j = 0; j < ncerts; j++) 1621 sshkey_free(certs[j]); 1622 free(certs); 1623 send_status(e, success); 1624} 1625 1626static void 1627process_remove_smartcard_key(SocketEntry *e) 1628{ 1629 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX]; 1630 int r, success = 0; 1631 Identity *id, *nxt; 1632 1633 debug2_f("entering"); 1634 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || 1635 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) { 1636 error_fr(r, "parse"); 1637 goto send; 1638 } 1639 free(pin); 1640 1641 if (realpath(provider, canonical_provider) == NULL) { 1642 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s", 1643 provider, strerror(errno)); 1644 goto send; 1645 } 1646 1647 debug_f("remove %.100s", canonical_provider); 1648 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) { 1649 nxt = TAILQ_NEXT(id, next); 1650 /* Skip file--based keys */ 1651 if (id->provider == NULL) 1652 continue; 1653 if (!strcmp(canonical_provider, id->provider)) { 1654 TAILQ_REMOVE(&idtab->idlist, id, next); 1655 free_identity(id); 1656 idtab->nentries--; 1657 } 1658 } 1659 if (pkcs11_del_provider(canonical_provider) == 0) 1660 success = 1; 1661 else 1662 error_f("pkcs11_del_provider failed"); 1663send: 1664 free(provider); 1665 send_status(e, success); 1666} 1667#endif /* ENABLE_PKCS11 */ 1668 1669static int 1670process_ext_session_bind(SocketEntry *e) 1671{ 1672 int r, sid_match, key_match; 1673 struct sshkey *key = NULL; 1674 struct sshbuf *sid = NULL, *sig = NULL; 1675 char *fp = NULL; 1676 size_t i; 1677 u_char fwd = 0; 1678 1679 debug2_f("entering"); 1680 e->session_bind_attempted = 1; 1681 if ((r = sshkey_froms(e->request, &key)) != 0 || 1682 (r = sshbuf_froms(e->request, &sid)) != 0 || 1683 (r = sshbuf_froms(e->request, &sig)) != 0 || 1684 (r = sshbuf_get_u8(e->request, &fwd)) != 0) { 1685 error_fr(r, "parse"); 1686 goto out; 1687 } 1688 if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) { 1689 error_f("session ID too long"); 1690 goto out; 1691 } 1692 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT, 1693 SSH_FP_DEFAULT)) == NULL) 1694 fatal_f("fingerprint failed"); 1695 /* check signature with hostkey on session ID */ 1696 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig), 1697 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) { 1698 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp); 1699 goto out; 1700 } 1701 /* check whether sid/key already recorded */ 1702 for (i = 0; i < e->nsession_ids; i++) { 1703 if (!e->session_ids[i].forwarded) { 1704 error_f("attempt to bind session ID to socket " 1705 "previously bound for authentication attempt"); 1706 r = -1; 1707 goto out; 1708 } 1709 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0; 1710 key_match = sshkey_equal(key, e->session_ids[i].key); 1711 if (sid_match && key_match) { 1712 debug_f("session ID already recorded for %s %s", 1713 sshkey_type(key), fp); 1714 r = 0; 1715 goto out; 1716 } else if (sid_match) { 1717 error_f("session ID recorded against different key " 1718 "for %s %s", sshkey_type(key), fp); 1719 r = -1; 1720 goto out; 1721 } 1722 /* 1723 * new sid with previously-seen key can happen, e.g. multiple 1724 * connections to the same host. 1725 */ 1726 } 1727 /* record new key/sid */ 1728 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) { 1729 error_f("too many session IDs recorded"); 1730 r = -1; 1731 goto out; 1732 } 1733 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids, 1734 e->nsession_ids + 1, sizeof(*e->session_ids)); 1735 i = e->nsession_ids++; 1736 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i, 1737 AGENT_MAX_SESSION_IDS); 1738 e->session_ids[i].key = key; 1739 e->session_ids[i].forwarded = fwd != 0; 1740 key = NULL; /* transferred */ 1741 /* can't transfer sid; it's refcounted and scoped to request's life */ 1742 if ((e->session_ids[i].sid = sshbuf_new()) == NULL) 1743 fatal_f("sshbuf_new"); 1744 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0) 1745 fatal_fr(r, "sshbuf_putb session ID"); 1746 /* success */ 1747 r = 0; 1748 out: 1749 free(fp); 1750 sshkey_free(key); 1751 sshbuf_free(sid); 1752 sshbuf_free(sig); 1753 return r == 0 ? 1 : 0; 1754} 1755 1756static int 1757process_ext_query(SocketEntry *e) 1758{ 1759 int r; 1760 struct sshbuf *msg = NULL; 1761 1762 debug2_f("entering"); 1763 if ((msg = sshbuf_new()) == NULL) 1764 fatal_f("sshbuf_new failed"); 1765 if ((r = sshbuf_put_u8(msg, SSH_AGENT_EXTENSION_RESPONSE)) != 0 || 1766 (r = sshbuf_put_cstring(msg, "query")) != 0 || 1767 /* string[] supported extension types */ 1768 (r = sshbuf_put_cstring(msg, "session-bind@openssh.com")) != 0) 1769 fatal_fr(r, "compose"); 1770 if ((r = sshbuf_put_stringb(e->output, msg)) != 0) 1771 fatal_fr(r, "enqueue"); 1772 sshbuf_free(msg); 1773 return 1; 1774} 1775 1776static void 1777process_extension(SocketEntry *e) 1778{ 1779 int r, success = 0; 1780 char *name; 1781 1782 debug2_f("entering"); 1783 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) { 1784 error_fr(r, "parse"); 1785 goto send; 1786 } 1787 if (strcmp(name, "query") == 0) 1788 success = process_ext_query(e); 1789 else if (strcmp(name, "session-bind@openssh.com") == 0) 1790 success = process_ext_session_bind(e); 1791 else 1792 debug_f("unsupported extension \"%s\"", name); 1793 free(name); 1794send: 1795 send_status(e, success); 1796} 1797/* 1798 * dispatch incoming message. 1799 * returns 1 on success, 0 for incomplete messages or -1 on error. 1800 */ 1801static int 1802process_message(u_int socknum) 1803{ 1804 u_int msg_len; 1805 u_char type; 1806 const u_char *cp; 1807 int r; 1808 SocketEntry *e; 1809 1810 if (socknum >= sockets_alloc) 1811 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc); 1812 e = &sockets[socknum]; 1813 1814 if (sshbuf_len(e->input) < 5) 1815 return 0; /* Incomplete message header. */ 1816 cp = sshbuf_ptr(e->input); 1817 msg_len = PEEK_U32(cp); 1818 if (msg_len > AGENT_MAX_LEN) { 1819 debug_f("socket %u (fd=%d) message too long %u > %u", 1820 socknum, e->fd, msg_len, AGENT_MAX_LEN); 1821 return -1; 1822 } 1823 if (sshbuf_len(e->input) < msg_len + 4) 1824 return 0; /* Incomplete message body. */ 1825 1826 /* move the current input to e->request */ 1827 sshbuf_reset(e->request); 1828 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 || 1829 (r = sshbuf_get_u8(e->request, &type)) != 0) { 1830 if (r == SSH_ERR_MESSAGE_INCOMPLETE || 1831 r == SSH_ERR_STRING_TOO_LARGE) { 1832 error_fr(r, "parse"); 1833 return -1; 1834 } 1835 fatal_fr(r, "parse"); 1836 } 1837 1838 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type); 1839 1840 /* check whether agent is locked */ 1841 if (locked && type != SSH_AGENTC_UNLOCK) { 1842 sshbuf_reset(e->request); 1843 switch (type) { 1844 case SSH2_AGENTC_REQUEST_IDENTITIES: 1845 /* send empty lists */ 1846 no_identities(e); 1847 break; 1848 default: 1849 /* send a fail message for all other request types */ 1850 send_status(e, 0); 1851 } 1852 return 1; 1853 } 1854 1855 switch (type) { 1856 case SSH_AGENTC_LOCK: 1857 case SSH_AGENTC_UNLOCK: 1858 process_lock_agent(e, type == SSH_AGENTC_LOCK); 1859 break; 1860 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES: 1861 process_remove_all_identities(e); /* safe for !WITH_SSH1 */ 1862 break; 1863 /* ssh2 */ 1864 case SSH2_AGENTC_SIGN_REQUEST: 1865 process_sign_request2(e); 1866 break; 1867 case SSH2_AGENTC_REQUEST_IDENTITIES: 1868 process_request_identities(e); 1869 break; 1870 case SSH2_AGENTC_ADD_IDENTITY: 1871 case SSH2_AGENTC_ADD_ID_CONSTRAINED: 1872 process_add_identity(e); 1873 break; 1874 case SSH2_AGENTC_REMOVE_IDENTITY: 1875 process_remove_identity(e); 1876 break; 1877 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: 1878 process_remove_all_identities(e); 1879 break; 1880#ifdef ENABLE_PKCS11 1881 case SSH_AGENTC_ADD_SMARTCARD_KEY: 1882 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED: 1883 process_add_smartcard_key(e); 1884 break; 1885 case SSH_AGENTC_REMOVE_SMARTCARD_KEY: 1886 process_remove_smartcard_key(e); 1887 break; 1888#endif /* ENABLE_PKCS11 */ 1889 case SSH_AGENTC_EXTENSION: 1890 process_extension(e); 1891 break; 1892 default: 1893 /* Unknown message. Respond with failure. */ 1894 error("Unknown message %d", type); 1895 sshbuf_reset(e->request); 1896 send_status(e, 0); 1897 break; 1898 } 1899 return 1; 1900} 1901 1902static void 1903new_socket(sock_type type, int fd) 1904{ 1905 u_int i, old_alloc, new_alloc; 1906 1907 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" : 1908 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN")); 1909 set_nonblock(fd); 1910 1911 if (fd > max_fd) 1912 max_fd = fd; 1913 1914 for (i = 0; i < sockets_alloc; i++) 1915 if (sockets[i].type == AUTH_UNUSED) { 1916 sockets[i].fd = fd; 1917 if ((sockets[i].input = sshbuf_new()) == NULL || 1918 (sockets[i].output = sshbuf_new()) == NULL || 1919 (sockets[i].request = sshbuf_new()) == NULL) 1920 fatal_f("sshbuf_new failed"); 1921 sockets[i].type = type; 1922 return; 1923 } 1924 old_alloc = sockets_alloc; 1925 new_alloc = sockets_alloc + 10; 1926 sockets = xrecallocarray(sockets, old_alloc, new_alloc, 1927 sizeof(sockets[0])); 1928 for (i = old_alloc; i < new_alloc; i++) 1929 sockets[i].type = AUTH_UNUSED; 1930 sockets_alloc = new_alloc; 1931 sockets[old_alloc].fd = fd; 1932 if ((sockets[old_alloc].input = sshbuf_new()) == NULL || 1933 (sockets[old_alloc].output = sshbuf_new()) == NULL || 1934 (sockets[old_alloc].request = sshbuf_new()) == NULL) 1935 fatal_f("sshbuf_new failed"); 1936 sockets[old_alloc].type = type; 1937} 1938 1939static int 1940handle_socket_read(u_int socknum) 1941{ 1942 struct sockaddr_un sunaddr; 1943 socklen_t slen; 1944 uid_t euid; 1945 gid_t egid; 1946 int fd; 1947 1948 slen = sizeof(sunaddr); 1949 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen); 1950 if (fd == -1) { 1951 error("accept from AUTH_SOCKET: %s", strerror(errno)); 1952 return -1; 1953 } 1954 if (getpeereid(fd, &euid, &egid) == -1) { 1955 error("getpeereid %d failed: %s", fd, strerror(errno)); 1956 close(fd); 1957 return -1; 1958 } 1959 if ((euid != 0) && (getuid() != euid)) { 1960 error("uid mismatch: peer euid %u != uid %u", 1961 (u_int) euid, (u_int) getuid()); 1962 close(fd); 1963 return -1; 1964 } 1965 new_socket(AUTH_CONNECTION, fd); 1966 return 0; 1967} 1968 1969static int 1970handle_conn_read(u_int socknum) 1971{ 1972 char buf[AGENT_RBUF_LEN]; 1973 ssize_t len; 1974 int r; 1975 1976 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) { 1977 if (len == -1) { 1978 if (errno == EAGAIN || errno == EINTR) 1979 return 0; 1980 error_f("read error on socket %u (fd %d): %s", 1981 socknum, sockets[socknum].fd, strerror(errno)); 1982 } 1983 return -1; 1984 } 1985 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0) 1986 fatal_fr(r, "compose"); 1987 explicit_bzero(buf, sizeof(buf)); 1988 for (;;) { 1989 if ((r = process_message(socknum)) == -1) 1990 return -1; 1991 else if (r == 0) 1992 break; 1993 } 1994 return 0; 1995} 1996 1997static int 1998handle_conn_write(u_int socknum) 1999{ 2000 ssize_t len; 2001 int r; 2002 2003 if (sshbuf_len(sockets[socknum].output) == 0) 2004 return 0; /* shouldn't happen */ 2005 if ((len = write(sockets[socknum].fd, 2006 sshbuf_ptr(sockets[socknum].output), 2007 sshbuf_len(sockets[socknum].output))) <= 0) { 2008 if (len == -1) { 2009 if (errno == EAGAIN || errno == EINTR) 2010 return 0; 2011 error_f("read error on socket %u (fd %d): %s", 2012 socknum, sockets[socknum].fd, strerror(errno)); 2013 } 2014 return -1; 2015 } 2016 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0) 2017 fatal_fr(r, "consume"); 2018 return 0; 2019} 2020 2021static void 2022after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds) 2023{ 2024 size_t i; 2025 u_int socknum, activefds = npfd; 2026 2027 for (i = 0; i < npfd; i++) { 2028 if (pfd[i].revents == 0) 2029 continue; 2030 /* Find sockets entry */ 2031 for (socknum = 0; socknum < sockets_alloc; socknum++) { 2032 if (sockets[socknum].type != AUTH_SOCKET && 2033 sockets[socknum].type != AUTH_CONNECTION) 2034 continue; 2035 if (pfd[i].fd == sockets[socknum].fd) 2036 break; 2037 } 2038 if (socknum >= sockets_alloc) { 2039 error_f("no socket for fd %d", pfd[i].fd); 2040 continue; 2041 } 2042 /* Process events */ 2043 switch (sockets[socknum].type) { 2044 case AUTH_SOCKET: 2045 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0) 2046 break; 2047 if (npfd > maxfds) { 2048 debug3("out of fds (active %u >= limit %u); " 2049 "skipping accept", activefds, maxfds); 2050 break; 2051 } 2052 if (handle_socket_read(socknum) == 0) 2053 activefds++; 2054 break; 2055 case AUTH_CONNECTION: 2056 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 && 2057 handle_conn_read(socknum) != 0) 2058 goto close_sock; 2059 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 && 2060 handle_conn_write(socknum) != 0) { 2061 close_sock: 2062 if (activefds == 0) 2063 fatal("activefds == 0 at close_sock"); 2064 close_socket(&sockets[socknum]); 2065 activefds--; 2066 break; 2067 } 2068 break; 2069 default: 2070 break; 2071 } 2072 } 2073} 2074 2075static int 2076prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds) 2077{ 2078 struct pollfd *pfd = *pfdp; 2079 size_t i, j, npfd = 0; 2080 time_t deadline; 2081 int r; 2082 2083 /* Count active sockets */ 2084 for (i = 0; i < sockets_alloc; i++) { 2085 switch (sockets[i].type) { 2086 case AUTH_SOCKET: 2087 case AUTH_CONNECTION: 2088 npfd++; 2089 break; 2090 case AUTH_UNUSED: 2091 break; 2092 default: 2093 fatal("Unknown socket type %d", sockets[i].type); 2094 break; 2095 } 2096 } 2097 if (npfd != *npfdp && 2098 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL) 2099 fatal_f("recallocarray failed"); 2100 *pfdp = pfd; 2101 *npfdp = npfd; 2102 2103 for (i = j = 0; i < sockets_alloc; i++) { 2104 switch (sockets[i].type) { 2105 case AUTH_SOCKET: 2106 if (npfd > maxfds) { 2107 debug3("out of fds (active %zu >= limit %u); " 2108 "skipping arming listener", npfd, maxfds); 2109 break; 2110 } 2111 pfd[j].fd = sockets[i].fd; 2112 pfd[j].revents = 0; 2113 pfd[j].events = POLLIN; 2114 j++; 2115 break; 2116 case AUTH_CONNECTION: 2117 pfd[j].fd = sockets[i].fd; 2118 pfd[j].revents = 0; 2119 /* 2120 * Only prepare to read if we can handle a full-size 2121 * input read buffer and enqueue a max size reply.. 2122 */ 2123 if ((r = sshbuf_check_reserve(sockets[i].input, 2124 AGENT_RBUF_LEN)) == 0 && 2125 (r = sshbuf_check_reserve(sockets[i].output, 2126 AGENT_MAX_LEN)) == 0) 2127 pfd[j].events = POLLIN; 2128 else if (r != SSH_ERR_NO_BUFFER_SPACE) 2129 fatal_fr(r, "reserve"); 2130 if (sshbuf_len(sockets[i].output) > 0) 2131 pfd[j].events |= POLLOUT; 2132 j++; 2133 break; 2134 default: 2135 break; 2136 } 2137 } 2138 deadline = reaper(); 2139 if (parent_alive_interval != 0) 2140 deadline = (deadline == 0) ? parent_alive_interval : 2141 MINIMUM(deadline, parent_alive_interval); 2142 if (deadline != 0) 2143 ptimeout_deadline_sec(timeoutp, deadline); 2144 return (1); 2145} 2146 2147static void 2148cleanup_socket(void) 2149{ 2150 if (cleanup_pid != 0 && getpid() != cleanup_pid) 2151 return; 2152 debug_f("cleanup"); 2153 if (socket_name != NULL) { 2154 unlink(socket_name); 2155 free(socket_name); 2156 socket_name = NULL; 2157 } 2158 if (socket_dir[0]) 2159 rmdir(socket_dir); 2160} 2161 2162void 2163cleanup_exit(int i) 2164{ 2165 cleanup_socket(); 2166#ifdef ENABLE_PKCS11 2167 pkcs11_terminate(); 2168#endif 2169 _exit(i); 2170} 2171 2172static void 2173cleanup_handler(int sig) 2174{ 2175 signalled_exit = sig; 2176} 2177 2178static void 2179keydrop_handler(int sig) 2180{ 2181 signalled_keydrop = sig; 2182} 2183 2184static void 2185check_parent_exists(void) 2186{ 2187 /* 2188 * If our parent has exited then getppid() will return (pid_t)1, 2189 * so testing for that should be safe. 2190 */ 2191 if (parent_pid != -1 && getppid() != parent_pid) { 2192 /* printf("Parent has died - Authentication agent exiting.\n"); */ 2193 cleanup_socket(); 2194 _exit(2); 2195 } 2196} 2197 2198static void 2199usage(void) 2200{ 2201 fprintf(stderr, 2202 "usage: ssh-agent [-c | -s] [-DdTU] [-a bind_address] [-E fingerprint_hash]\n" 2203 " [-O option] [-P allowed_providers] [-t life]\n" 2204 " ssh-agent [-TU] [-a bind_address] [-E fingerprint_hash] [-O option]\n" 2205 " [-P allowed_providers] [-t life] command [arg ...]\n" 2206 " ssh-agent [-c | -s] -k\n" 2207 " ssh-agent -u\n"); 2208 exit(1); 2209} 2210 2211int 2212main(int ac, char **av) 2213{ 2214 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0; 2215 int s_flag = 0, T_flag = 0, u_flag = 0, U_flag = 0; 2216 int sock = -1, ch, result, saved_errno; 2217 pid_t pid; 2218 char *homedir = NULL, *shell, *format, *pidstr, *agentsocket = NULL; 2219 char *cp, pidstrbuf[1 + 3 * sizeof pid]; 2220 const char *ccp; 2221 struct rlimit rlim; 2222 extern int optind; 2223 extern char *optarg; 2224 size_t len; 2225 mode_t prev_mask; 2226 struct timespec timeout; 2227 struct pollfd *pfd = NULL; 2228 size_t npfd = 0; 2229 u_int maxfds; 2230 sigset_t nsigset, osigset; 2231 2232 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 2233 sanitise_stdfd(); 2234 2235 /* drop */ 2236 (void)setegid(getgid()); 2237 (void)setgid(getgid()); 2238 2239 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) 2240 fatal("%s: getrlimit: %s", __progname, strerror(errno)); 2241 2242 while ((ch = getopt(ac, av, "cDdksTuUE:a:O:P:t:")) != -1) { 2243 switch (ch) { 2244 case 'E': 2245 fingerprint_hash = ssh_digest_alg_by_name(optarg); 2246 if (fingerprint_hash == -1) 2247 fatal("Invalid hash algorithm \"%s\"", optarg); 2248 break; 2249 case 'c': 2250 if (s_flag) 2251 usage(); 2252 c_flag++; 2253 break; 2254 case 'k': 2255 k_flag++; 2256 break; 2257 case 'O': 2258 if (strcmp(optarg, "no-restrict-websafe") == 0) 2259 restrict_websafe = 0; 2260 else if (strcmp(optarg, "allow-remote-pkcs11") == 0) 2261 remote_add_provider = 1; 2262 else if ((ccp = strprefix(optarg, 2263 "websafe-allow=", 0)) != NULL) { 2264 if (websafe_allowlist != NULL) 2265 fatal("websafe-allow already set"); 2266 websafe_allowlist = xstrdup(ccp); 2267 } else 2268 fatal("Unknown -O option"); 2269 break; 2270 case 'P': 2271 if (allowed_providers != NULL) 2272 fatal("-P option already specified"); 2273 allowed_providers = xstrdup(optarg); 2274 break; 2275 case 's': 2276 if (c_flag) 2277 usage(); 2278 s_flag++; 2279 break; 2280 case 'd': 2281 if (d_flag || D_flag) 2282 usage(); 2283 d_flag++; 2284 break; 2285 case 'D': 2286 if (d_flag || D_flag) 2287 usage(); 2288 D_flag++; 2289 break; 2290 case 'a': 2291 agentsocket = optarg; 2292 break; 2293 case 't': 2294 if ((lifetime = convtime(optarg)) == -1) { 2295 fprintf(stderr, "Invalid lifetime\n"); 2296 usage(); 2297 } 2298 break; 2299 case 'T': 2300 T_flag++; 2301 break; 2302 case 'u': 2303 u_flag++; 2304 break; 2305 case 'U': 2306 U_flag++; 2307 break; 2308 default: 2309 usage(); 2310 } 2311 } 2312 ac -= optind; 2313 av += optind; 2314 2315 if (ac > 0 && 2316 (c_flag || k_flag || s_flag || d_flag || D_flag || u_flag)) 2317 usage(); 2318 2319 log_init(__progname, 2320 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 2321 SYSLOG_FACILITY_AUTH, 1); 2322 2323 if (allowed_providers == NULL) 2324 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS); 2325 if (websafe_allowlist == NULL) 2326 websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST); 2327 2328 if (ac == 0 && !c_flag && !s_flag) { 2329 shell = getenv("SHELL"); 2330 if (shell != NULL && (len = strlen(shell)) > 2 && 2331 strncmp(shell + len - 3, "csh", 3) == 0) 2332 c_flag = 1; 2333 } 2334 if (k_flag) { 2335 const char *errstr = NULL; 2336 2337 pidstr = getenv(SSH_AGENTPID_ENV_NAME); 2338 if (pidstr == NULL) { 2339 fprintf(stderr, "%s not set, cannot kill agent\n", 2340 SSH_AGENTPID_ENV_NAME); 2341 exit(1); 2342 } 2343 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr); 2344 if (errstr) { 2345 fprintf(stderr, 2346 "%s=\"%s\", which is not a good PID: %s\n", 2347 SSH_AGENTPID_ENV_NAME, pidstr, errstr); 2348 exit(1); 2349 } 2350 if (kill(pid, SIGTERM) == -1) { 2351 perror("kill"); 2352 exit(1); 2353 } 2354 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n"; 2355 printf(format, SSH_AUTHSOCKET_ENV_NAME); 2356 printf(format, SSH_AGENTPID_ENV_NAME); 2357 printf("echo Agent pid %ld killed;\n", (long)pid); 2358 exit(0); 2359 } 2360 if (u_flag) { 2361 if ((homedir = get_homedir()) == NULL) 2362 fatal("Couldn't determine home directory"); 2363 agent_cleanup_stale(homedir, u_flag > 1); 2364 printf("Deleted stale agent sockets in ~/%s\n", 2365 _PATH_SSH_AGENT_SOCKET_DIR); 2366 exit(0); 2367 } 2368 2369 /* 2370 * Minimum file descriptors: 2371 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) + 2372 * a few spare for libc / stack protectors / sanitisers, etc. 2373 */ 2374#define SSH_AGENT_MIN_FDS (3+1+1+1+4) 2375 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS) 2376 fatal("%s: file descriptor rlimit %lld too low (minimum %u)", 2377 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS); 2378 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS; 2379 2380 parent_pid = getpid(); 2381 2382 /* 2383 * Create socket early so it will exist before command gets run from 2384 * the parent. 2385 */ 2386 if (agentsocket == NULL && !T_flag) { 2387 /* Default case: ~/.ssh/agent/[socket] */ 2388 if ((homedir = get_homedir()) == NULL) 2389 fatal("Couldn't determine home directory"); 2390 if (!U_flag) 2391 agent_cleanup_stale(homedir, 0); 2392 if (agent_listener(homedir, "agent", &sock, &socket_name) != 0) 2393 fatal_f("Couldn't prepare agent socket"); 2394 free(homedir); 2395 } else { 2396 if (T_flag) { 2397 /* 2398 * Create private directory for agent socket 2399 * in $TMPDIR. 2400 */ 2401 mktemp_proto(socket_dir, sizeof(socket_dir)); 2402 if (mkdtemp(socket_dir) == NULL) { 2403 perror("mkdtemp: private socket dir"); 2404 exit(1); 2405 } 2406 xasprintf(&socket_name, "%s/agent.%ld", 2407 socket_dir, (long)parent_pid); 2408 } else { 2409 /* Try to use specified agent socket */ 2410 socket_dir[0] = '\0'; 2411 socket_name = xstrdup(agentsocket); 2412 } 2413 /* Listen on socket */ 2414 prev_mask = umask(0177); 2415 if ((sock = unix_listener(socket_name, 2416 SSH_LISTEN_BACKLOG, 0)) < 0) { 2417 *socket_name = '\0'; /* Don't unlink existing file */ 2418 cleanup_exit(1); 2419 } 2420 umask(prev_mask); 2421 } 2422 2423 /* 2424 * Fork, and have the parent execute the command, if any, or present 2425 * the socket data. The child continues as the authentication agent. 2426 */ 2427 if (D_flag || d_flag) { 2428 log_init(__progname, 2429 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 2430 SYSLOG_FACILITY_AUTH, 1); 2431 cp = argv_assemble(1, &socket_name); 2432 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 2433 printf(format, SSH_AUTHSOCKET_ENV_NAME, cp, 2434 SSH_AUTHSOCKET_ENV_NAME); 2435 free(cp); 2436 printf("echo Agent pid %ld;\n", (long)parent_pid); 2437 fflush(stdout); 2438 goto skip; 2439 } 2440 pid = fork(); 2441 if (pid == -1) { 2442 perror("fork"); 2443 cleanup_exit(1); 2444 } 2445 if (pid != 0) { /* Parent - execute the given command. */ 2446 close(sock); 2447 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid); 2448 if (ac == 0) { 2449 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n"; 2450 cp = argv_assemble(1, &socket_name); 2451 printf(format, SSH_AUTHSOCKET_ENV_NAME, cp, 2452 SSH_AUTHSOCKET_ENV_NAME); 2453 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf, 2454 SSH_AGENTPID_ENV_NAME); 2455 free(cp); 2456 printf("echo Agent pid %ld;\n", (long)pid); 2457 exit(0); 2458 } 2459 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 || 2460 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) { 2461 perror("setenv"); 2462 exit(1); 2463 } 2464 execvp(av[0], av); 2465 perror(av[0]); 2466 exit(1); 2467 } 2468 /* child */ 2469 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0); 2470 2471 if (setsid() == -1) { 2472 error("setsid: %s", strerror(errno)); 2473 cleanup_exit(1); 2474 } 2475 2476 (void)chdir("/"); 2477 if (stdfd_devnull(1, 1, 1) == -1) 2478 error_f("stdfd_devnull failed"); 2479 2480 /* deny core dumps, since memory contains unencrypted private keys */ 2481 rlim.rlim_cur = rlim.rlim_max = 0; 2482 if (setrlimit(RLIMIT_CORE, &rlim) == -1) { 2483 error("setrlimit RLIMIT_CORE: %s", strerror(errno)); 2484 cleanup_exit(1); 2485 } 2486 2487skip: 2488 2489 cleanup_pid = getpid(); 2490 2491#ifdef ENABLE_PKCS11 2492 pkcs11_init(0); 2493#endif 2494 new_socket(AUTH_SOCKET, sock); 2495 if (ac > 0) 2496 parent_alive_interval = 10; 2497 idtab_init(); 2498 ssh_signal(SIGPIPE, SIG_IGN); 2499 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN); 2500 ssh_signal(SIGHUP, cleanup_handler); 2501 ssh_signal(SIGTERM, cleanup_handler); 2502 ssh_signal(SIGUSR1, keydrop_handler); 2503 2504 sigemptyset(&nsigset); 2505 sigaddset(&nsigset, SIGINT); 2506 sigaddset(&nsigset, SIGHUP); 2507 sigaddset(&nsigset, SIGTERM); 2508 sigaddset(&nsigset, SIGUSR1); 2509 2510 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1) 2511 fatal("%s: pledge: %s", __progname, strerror(errno)); 2512 2513 while (1) { 2514 sigprocmask(SIG_BLOCK, &nsigset, &osigset); 2515 if (signalled_exit != 0) { 2516 logit("exiting on signal %d", (int)signalled_exit); 2517 cleanup_exit(2); 2518 } 2519 if (signalled_keydrop) { 2520 logit("signal %d received; removing all keys", 2521 (int)signalled_keydrop); 2522 remove_all_identities(); 2523 signalled_keydrop = 0; 2524 } 2525 ptimeout_init(&timeout); 2526 prepare_poll(&pfd, &npfd, &timeout, maxfds); 2527 result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset); 2528 sigprocmask(SIG_SETMASK, &osigset, NULL); 2529 saved_errno = errno; 2530 if (parent_alive_interval != 0) 2531 check_parent_exists(); 2532 (void) reaper(); /* remove expired keys */ 2533 if (result == -1) { 2534 if (saved_errno == EINTR) 2535 continue; 2536 fatal("poll: %s", strerror(saved_errno)); 2537 } else if (result > 0) 2538 after_poll(pfd, npfd, maxfds); 2539 } 2540 /* NOTREACHED */ 2541}