sshd-session.c revision 1.3
1/* $NetBSD: sshd-session.c,v 1.3 2024/07/11 17:26:53 riastradh Exp $ */ 2 3/* $OpenBSD: sshd-session.c,v 1.4 2024/06/26 23:16:52 deraadt Exp $ */ 4/* 5 * SSH2 implementation: 6 * Privilege Separation: 7 * 8 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved. 9 * Copyright (c) 2002 Niels Provos. All rights reserved. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32#include "includes.h" 33__RCSID("$NetBSD: sshd-session.c,v 1.3 2024/07/11 17:26:53 riastradh Exp $"); 34 35#include <sys/types.h> 36#include <sys/param.h> 37#include <sys/ioctl.h> 38#include <sys/wait.h> 39#include <sys/tree.h> 40#include <sys/stat.h> 41#include <sys/socket.h> 42#include <sys/time.h> 43#include <sys/queue.h> 44 45#include <errno.h> 46#include <fcntl.h> 47#include <netdb.h> 48#include <paths.h> 49#include <pwd.h> 50#include <signal.h> 51#include <stdio.h> 52#include <stdlib.h> 53#include <string.h> 54#include <stdarg.h> 55#include <unistd.h> 56#include <limits.h> 57 58#ifdef WITH_OPENSSL 59#include <openssl/bn.h> 60#include <openssl/evp.h> 61#endif 62 63#include <netinet/in.h> 64 65#include "xmalloc.h" 66#include "ssh.h" 67#include "ssh2.h" 68#include "sshpty.h" 69#include "packet.h" 70#include "log.h" 71#include "sshbuf.h" 72#include "misc.h" 73#include "match.h" 74#include "servconf.h" 75#include "uidswap.h" 76#include "compat.h" 77#include "cipher.h" 78#include "digest.h" 79#include "sshkey.h" 80#include "kex.h" 81#include "authfile.h" 82#include "pathnames.h" 83#include "atomicio.h" 84#include "canohost.h" 85#include "hostfile.h" 86#include "auth.h" 87#include "authfd.h" 88#include "msg.h" 89#include "dispatch.h" 90#include "channels.h" 91#include "session.h" 92#include "monitor.h" 93#ifdef GSSAPI 94#include "ssh-gss.h" 95#endif 96#include "monitor_wrap.h" 97#include "ssh-sandbox.h" 98#include "auth-options.h" 99#include "version.h" 100#include "ssherr.h" 101#include "sk-api.h" 102#include "srclimit.h" 103#include "dh.h" 104 105#include "pfilter.h" 106 107#ifdef LIBWRAP 108#include <tcpd.h> 109#include <syslog.h> 110int allow_severity = LOG_INFO; 111int deny_severity = LOG_WARNING; 112#endif /* LIBWRAP */ 113 114#ifdef WITH_LDAP_PUBKEY 115#include "ldapauth.h" 116#endif 117 118#ifndef HOST_NAME_MAX 119#define HOST_NAME_MAX MAXHOSTNAMELEN 120#endif 121 122/* Re-exec fds */ 123#define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) 124#define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2) 125#define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3) 126#define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4) 127 128extern char *__progname; 129 130/* Server configuration options. */ 131ServerOptions options; 132 133/* Name of the server configuration file. */ 134const char *config_file_name = _PATH_SERVER_CONFIG_FILE; 135 136/* 137 * Debug mode flag. This can be set on the command line. If debug 138 * mode is enabled, extra debugging output will be sent to the system 139 * log, the daemon will not go to background, and will exit after processing 140 * the first connection. 141 */ 142int debug_flag = 0; 143 144/* Flag indicating that the daemon is being started from inetd. */ 145static int inetd_flag = 0; 146 147/* debug goes to stderr unless inetd_flag is set */ 148static int log_stderr = 0; 149 150/* Saved arguments to main(). */ 151static char **saved_argv; 152 153/* Daemon's agent connection */ 154int auth_sock = -1; 155static int have_agent = 0; 156 157/* 158 * Any really sensitive data in the application is contained in this 159 * structure. The idea is that this structure could be locked into memory so 160 * that the pages do not get written into swap. However, there are some 161 * problems. The private key contains BIGNUMs, and we do not (in principle) 162 * have access to the internals of them, and locking just the structure is 163 * not very useful. Currently, memory locking is not implemented. 164 */ 165struct { 166 u_int num_hostkeys; 167 struct sshkey **host_keys; /* all private host keys */ 168 struct sshkey **host_pubkeys; /* all public host keys */ 169 struct sshkey **host_certificates; /* all public host certificates */ 170} sensitive_data; 171 172/* record remote hostname or ip */ 173u_int utmp_len = HOST_NAME_MAX+1; 174 175static int startup_pipe = -1; /* in child */ 176 177/* variables used for privilege separation */ 178struct monitor *pmonitor = NULL; 179int privsep_is_preauth = 1; 180 181/* global connection state and authentication contexts */ 182Authctxt *the_authctxt = NULL; 183struct ssh *the_active_state; 184 185/* global key/cert auth options. XXX move to permanent ssh->authctxt? */ 186struct sshauthopt *auth_opts = NULL; 187 188/* sshd_config buffer */ 189struct sshbuf *cfg; 190 191/* Included files from the configuration file */ 192struct include_list includes = TAILQ_HEAD_INITIALIZER(includes); 193 194/* message to be displayed after login */ 195struct sshbuf *loginmsg; 196 197/* Prototypes for various functions defined later in this file. */ 198void destroy_sensitive_data(void); 199void demote_sensitive_data(void); 200static void do_ssh2_kex(struct ssh *); 201 202/* 203 * Signal handler for the alarm after the login grace period has expired. 204 * As usual, this may only take signal-safe actions, even though it is 205 * terminal. 206 */ 207__dead 208static void 209grace_alarm_handler(int sig) 210{ 211 pfilter_notify(1); 212 /* 213 * Try to kill any processes that we have spawned, E.g. authorized 214 * keys command helpers or privsep children. 215 */ 216 if (getpgid(0) == getpid()) { 217 struct sigaction sa; 218 219 /* mask all other signals while in handler */ 220 memset(&sa, 0, sizeof(sa)); 221 sa.sa_handler = SIG_IGN; 222 sigfillset(&sa.sa_mask); 223 sa.sa_flags = SA_RESTART; 224 (void)sigaction(SIGTERM, &sa, NULL); 225 kill(0, SIGTERM); 226 } 227 _exit(EXIT_LOGIN_GRACE); 228} 229 230/* Destroy the host and server keys. They will no longer be needed. */ 231void 232destroy_sensitive_data(void) 233{ 234 u_int i; 235 236 for (i = 0; i < options.num_host_key_files; i++) { 237 if (sensitive_data.host_keys[i]) { 238 sshkey_free(sensitive_data.host_keys[i]); 239 sensitive_data.host_keys[i] = NULL; 240 } 241 if (sensitive_data.host_certificates[i]) { 242 sshkey_free(sensitive_data.host_certificates[i]); 243 sensitive_data.host_certificates[i] = NULL; 244 } 245 } 246} 247 248/* Demote private to public keys for network child */ 249void 250demote_sensitive_data(void) 251{ 252 struct sshkey *tmp; 253 u_int i; 254 int r; 255 256 for (i = 0; i < options.num_host_key_files; i++) { 257 if (sensitive_data.host_keys[i]) { 258 if ((r = sshkey_from_private( 259 sensitive_data.host_keys[i], &tmp)) != 0) 260 fatal_r(r, "could not demote host %s key", 261 sshkey_type(sensitive_data.host_keys[i])); 262 sshkey_free(sensitive_data.host_keys[i]); 263 sensitive_data.host_keys[i] = tmp; 264 } 265 /* Certs do not need demotion */ 266 } 267} 268 269static void 270privsep_preauth_child(void) 271{ 272 gid_t gidset[1]; 273 struct passwd *pw; 274 275 /* Enable challenge-response authentication for privilege separation */ 276 privsep_challenge_enable(); 277 278#ifdef GSSAPI 279 /* Cache supported mechanism OIDs for later use */ 280 ssh_gssapi_prepare_supported_oids(); 281#endif 282 283 /* Demote the private keys to public keys. */ 284 demote_sensitive_data(); 285 286 /* Demote the child */ 287 if (getuid() == 0 || geteuid() == 0) { 288 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) 289 fatal("Privilege separation user %s does not exist", 290 SSH_PRIVSEP_USER); 291 pw = pwcopy(pw); /* Ensure mutable */ 292 endpwent(); 293 freezero(pw->pw_passwd, strlen(pw->pw_passwd)); 294 295 /* Change our root directory */ 296 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1) 297 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR, 298 strerror(errno)); 299 if (chdir("/") == -1) 300 fatal("chdir(\"/\"): %s", strerror(errno)); 301 302 /* 303 * Drop our privileges 304 * NB. Can't use setusercontext() after chroot. 305 */ 306 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid, 307 (u_int)pw->pw_gid); 308 gidset[0] = pw->pw_gid; 309 if (setgroups(1, gidset) == -1) 310 fatal("setgroups: %.100s", strerror(errno)); 311 permanently_set_uid(pw); 312 } 313} 314 315static int 316privsep_preauth(struct ssh *ssh) 317{ 318 int status, r; 319 pid_t pid; 320 struct ssh_sandbox *box = NULL; 321 322 /* Set up unprivileged child process to deal with network data */ 323 pmonitor = monitor_init(); 324 /* Store a pointer to the kex for later rekeying */ 325 pmonitor->m_pkex = &ssh->kex; 326 327 box = ssh_sandbox_init(); 328 pid = fork(); 329 if (pid == -1) { 330 fatal("fork of unprivileged child failed"); 331 } else if (pid != 0) { 332 debug2("Network child is on pid %ld", (long)pid); 333 334 pmonitor->m_pid = pid; 335 if (have_agent) { 336 r = ssh_get_authentication_socket(&auth_sock); 337 if (r != 0) { 338 error_r(r, "Could not get agent socket"); 339 have_agent = 0; 340 } 341 } 342 if (box != NULL) 343 ssh_sandbox_parent_preauth(box, pid); 344 monitor_child_preauth(ssh, pmonitor); 345 346 /* Wait for the child's exit status */ 347 while (waitpid(pid, &status, 0) == -1) { 348 if (errno == EINTR) 349 continue; 350 pmonitor->m_pid = -1; 351 fatal_f("waitpid: %s", strerror(errno)); 352 } 353 privsep_is_preauth = 0; 354 pmonitor->m_pid = -1; 355 if (WIFEXITED(status)) { 356 if (WEXITSTATUS(status) != 0) 357 fatal_f("preauth child exited with status %d", 358 WEXITSTATUS(status)); 359 } else if (WIFSIGNALED(status)) 360 fatal_f("preauth child terminated by signal %d", 361 WTERMSIG(status)); 362 if (box != NULL) 363 ssh_sandbox_parent_finish(box); 364 return 1; 365 } else { 366 /* child */ 367 close(pmonitor->m_sendfd); 368 close(pmonitor->m_log_recvfd); 369 370 /* Arrange for logging to be sent to the monitor */ 371 set_log_handler(mm_log_handler, pmonitor); 372 373 privsep_preauth_child(); 374 setproctitle("%s", "[net]"); 375 if (box != NULL) 376 ssh_sandbox_child(box); 377 378 return 0; 379 } 380} 381 382static void 383privsep_postauth(struct ssh *ssh, Authctxt *authctxt) 384{ 385 /* New socket pair */ 386 monitor_reinit(pmonitor); 387 388 pmonitor->m_pid = fork(); 389 if (pmonitor->m_pid == -1) 390 fatal("fork of unprivileged child failed"); 391 else if (pmonitor->m_pid != 0) { 392 verbose("User child is on pid %ld", (long)pmonitor->m_pid); 393 sshbuf_reset(loginmsg); 394 monitor_clear_keystate(ssh, pmonitor); 395 monitor_child_postauth(ssh, pmonitor); 396 397 /* NEVERREACHED */ 398 exit(0); 399 } 400 401 /* child */ 402 403 close(pmonitor->m_sendfd); 404 pmonitor->m_sendfd = -1; 405 406 /* Demote the private keys to public keys. */ 407 demote_sensitive_data(); 408 409 /* Drop privileges */ 410 do_setusercontext(authctxt->pw); 411 412 /* It is safe now to apply the key state */ 413 monitor_apply_keystate(ssh, pmonitor); 414 415 /* 416 * Tell the packet layer that authentication was successful, since 417 * this information is not part of the key state. 418 */ 419 ssh_packet_set_authenticated(ssh); 420} 421 422static void 423append_hostkey_type(struct sshbuf *b, const char *s) 424{ 425 int r; 426 427 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) { 428 debug3_f("%s key not permitted by HostkeyAlgorithms", s); 429 return; 430 } 431 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0) 432 fatal_fr(r, "sshbuf_putf"); 433} 434 435static char * 436list_hostkey_types(void) 437{ 438 struct sshbuf *b; 439 struct sshkey *key; 440 char *ret; 441 u_int i; 442 443 if ((b = sshbuf_new()) == NULL) 444 fatal_f("sshbuf_new failed"); 445 for (i = 0; i < options.num_host_key_files; i++) { 446 key = sensitive_data.host_keys[i]; 447 if (key == NULL) 448 key = sensitive_data.host_pubkeys[i]; 449 if (key == NULL) 450 continue; 451 switch (key->type) { 452 case KEY_RSA: 453 /* for RSA we also support SHA2 signatures */ 454 append_hostkey_type(b, "rsa-sha2-512"); 455 append_hostkey_type(b, "rsa-sha2-256"); 456 /* FALLTHROUGH */ 457 case KEY_DSA: 458 case KEY_ECDSA: 459 case KEY_ED25519: 460 case KEY_ECDSA_SK: 461 case KEY_ED25519_SK: 462 case KEY_XMSS: 463 append_hostkey_type(b, sshkey_ssh_name(key)); 464 break; 465 } 466 /* If the private key has a cert peer, then list that too */ 467 key = sensitive_data.host_certificates[i]; 468 if (key == NULL) 469 continue; 470 switch (key->type) { 471 case KEY_RSA_CERT: 472 /* for RSA we also support SHA2 signatures */ 473 append_hostkey_type(b, 474 "rsa-sha2-512-cert-v01@openssh.com"); 475 append_hostkey_type(b, 476 "rsa-sha2-256-cert-v01@openssh.com"); 477 /* FALLTHROUGH */ 478 case KEY_DSA_CERT: 479 case KEY_ECDSA_CERT: 480 case KEY_ED25519_CERT: 481 case KEY_ECDSA_SK_CERT: 482 case KEY_ED25519_SK_CERT: 483 case KEY_XMSS_CERT: 484 append_hostkey_type(b, sshkey_ssh_name(key)); 485 break; 486 } 487 } 488 if ((ret = sshbuf_dup_string(b)) == NULL) 489 fatal_f("sshbuf_dup_string failed"); 490 sshbuf_free(b); 491 debug_f("%s", ret); 492 return ret; 493} 494 495static struct sshkey * 496get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh) 497{ 498 u_int i; 499 struct sshkey *key; 500 501 for (i = 0; i < options.num_host_key_files; i++) { 502 switch (type) { 503 case KEY_RSA_CERT: 504 case KEY_DSA_CERT: 505 case KEY_ECDSA_CERT: 506 case KEY_ED25519_CERT: 507 case KEY_ECDSA_SK_CERT: 508 case KEY_ED25519_SK_CERT: 509 case KEY_XMSS_CERT: 510 key = sensitive_data.host_certificates[i]; 511 break; 512 default: 513 key = sensitive_data.host_keys[i]; 514 if (key == NULL && !need_private) 515 key = sensitive_data.host_pubkeys[i]; 516 break; 517 } 518 if (key == NULL || key->type != type) 519 continue; 520 switch (type) { 521 case KEY_ECDSA: 522 case KEY_ECDSA_SK: 523 case KEY_ECDSA_CERT: 524 case KEY_ECDSA_SK_CERT: 525 if (key->ecdsa_nid != nid) 526 continue; 527 /* FALLTHROUGH */ 528 default: 529 return need_private ? 530 sensitive_data.host_keys[i] : key; 531 } 532 } 533 return NULL; 534} 535 536struct sshkey * 537get_hostkey_public_by_type(int type, int nid, struct ssh *ssh) 538{ 539 return get_hostkey_by_type(type, nid, 0, ssh); 540} 541 542struct sshkey * 543get_hostkey_private_by_type(int type, int nid, struct ssh *ssh) 544{ 545 return get_hostkey_by_type(type, nid, 1, ssh); 546} 547 548struct sshkey * 549get_hostkey_by_index(int ind) 550{ 551 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 552 return (NULL); 553 return (sensitive_data.host_keys[ind]); 554} 555 556struct sshkey * 557get_hostkey_public_by_index(int ind, struct ssh *ssh) 558{ 559 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 560 return (NULL); 561 return (sensitive_data.host_pubkeys[ind]); 562} 563 564int 565get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh) 566{ 567 u_int i; 568 569 for (i = 0; i < options.num_host_key_files; i++) { 570 if (sshkey_is_cert(key)) { 571 if (key == sensitive_data.host_certificates[i] || 572 (compare && sensitive_data.host_certificates[i] && 573 sshkey_equal(key, 574 sensitive_data.host_certificates[i]))) 575 return (i); 576 } else { 577 if (key == sensitive_data.host_keys[i] || 578 (compare && sensitive_data.host_keys[i] && 579 sshkey_equal(key, sensitive_data.host_keys[i]))) 580 return (i); 581 if (key == sensitive_data.host_pubkeys[i] || 582 (compare && sensitive_data.host_pubkeys[i] && 583 sshkey_equal(key, sensitive_data.host_pubkeys[i]))) 584 return (i); 585 } 586 } 587 return (-1); 588} 589 590/* Inform the client of all hostkeys */ 591static void 592notify_hostkeys(struct ssh *ssh) 593{ 594 struct sshbuf *buf; 595 struct sshkey *key; 596 u_int i, nkeys; 597 int r; 598 char *fp; 599 600 /* Some clients cannot cope with the hostkeys message, skip those. */ 601 if (ssh->compat & SSH_BUG_HOSTKEYS) 602 return; 603 604 if ((buf = sshbuf_new()) == NULL) 605 fatal_f("sshbuf_new"); 606 for (i = nkeys = 0; i < options.num_host_key_files; i++) { 607 key = get_hostkey_public_by_index(i, ssh); 608 if (key == NULL || key->type == KEY_UNSPEC || 609 sshkey_is_cert(key)) 610 continue; 611 fp = sshkey_fingerprint(key, options.fingerprint_hash, 612 SSH_FP_DEFAULT); 613 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp); 614 free(fp); 615 if (nkeys == 0) { 616 /* 617 * Start building the request when we find the 618 * first usable key. 619 */ 620 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 621 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 || 622 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */ 623 sshpkt_fatal(ssh, r, "%s: start request", __func__); 624 } 625 /* Append the key to the request */ 626 sshbuf_reset(buf); 627 if ((r = sshkey_putb(key, buf)) != 0) 628 fatal_fr(r, "couldn't put hostkey %d", i); 629 if ((r = sshpkt_put_stringb(ssh, buf)) != 0) 630 sshpkt_fatal(ssh, r, "%s: append key", __func__); 631 nkeys++; 632 } 633 debug3_f("sent %u hostkeys", nkeys); 634 if (nkeys == 0) 635 fatal_f("no hostkeys"); 636 if ((r = sshpkt_send(ssh)) != 0) 637 sshpkt_fatal(ssh, r, "%s: send", __func__); 638 sshbuf_free(buf); 639} 640 641__dead static void 642usage(void) 643{ 644 fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION); 645 fprintf(stderr, 646"usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n" 647" [-E log_file] [-f config_file] [-g login_grace_time]\n" 648" [-h host_key_file] [-o option] [-p port] [-u len]\n" 649 ); 650 exit(1); 651} 652 653static void 654parse_hostkeys(struct sshbuf *hostkeys) 655{ 656 int r; 657 u_int num_keys = 0; 658 struct sshkey *k; 659 struct sshbuf *kbuf; 660 const u_char *cp; 661 size_t len; 662 663 while (sshbuf_len(hostkeys) != 0) { 664 if (num_keys > 2048) 665 fatal_f("too many hostkeys"); 666 sensitive_data.host_keys = xrecallocarray( 667 sensitive_data.host_keys, num_keys, num_keys + 1, 668 sizeof(*sensitive_data.host_pubkeys)); 669 sensitive_data.host_pubkeys = xrecallocarray( 670 sensitive_data.host_pubkeys, num_keys, num_keys + 1, 671 sizeof(*sensitive_data.host_pubkeys)); 672 sensitive_data.host_certificates = xrecallocarray( 673 sensitive_data.host_certificates, num_keys, num_keys + 1, 674 sizeof(*sensitive_data.host_certificates)); 675 /* private key */ 676 k = NULL; 677 if ((r = sshbuf_froms(hostkeys, &kbuf)) != 0) 678 fatal_fr(r, "extract privkey"); 679 if (sshbuf_len(kbuf) != 0 && 680 (r = sshkey_private_deserialize(kbuf, &k)) != 0) 681 fatal_fr(r, "parse pubkey"); 682 sensitive_data.host_keys[num_keys] = k; 683 sshbuf_free(kbuf); 684 if (k) 685 debug2_f("privkey %u: %s", num_keys, sshkey_ssh_name(k)); 686 /* public key */ 687 k = NULL; 688 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0) 689 fatal_fr(r, "extract pubkey"); 690 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0) 691 fatal_fr(r, "parse pubkey"); 692 sensitive_data.host_pubkeys[num_keys] = k; 693 if (k) 694 debug2_f("pubkey %u: %s", num_keys, sshkey_ssh_name(k)); 695 /* certificate */ 696 k = NULL; 697 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0) 698 fatal_fr(r, "extract pubkey"); 699 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0) 700 fatal_fr(r, "parse pubkey"); 701 sensitive_data.host_certificates[num_keys] = k; 702 if (k) 703 debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k)); 704 num_keys++; 705 } 706 sensitive_data.num_hostkeys = num_keys; 707} 708 709static void 710recv_rexec_state(int fd, struct sshbuf *conf, uint64_t *timing_secretp) 711{ 712 struct sshbuf *m, *inc, *hostkeys; 713 u_char *cp, ver; 714 size_t len; 715 int r; 716 struct include_item *item; 717 718 debug3_f("entering fd = %d", fd); 719 720 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL) 721 fatal_f("sshbuf_new failed"); 722 if (ssh_msg_recv(fd, m) == -1) 723 fatal_f("ssh_msg_recv failed"); 724 if ((r = sshbuf_get_u8(m, &ver)) != 0) 725 fatal_fr(r, "parse version"); 726 if (ver != 0) 727 fatal_f("rexec version mismatch"); 728 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 || /* XXX _direct */ 729 (r = sshbuf_get_u64(m, timing_secretp)) != 0 || 730 (r = sshbuf_froms(m, &hostkeys)) != 0 || 731 (r = sshbuf_get_stringb(m, inc)) != 0) 732 fatal_fr(r, "parse config"); 733 734 if (conf != NULL && (r = sshbuf_put(conf, cp, len))) 735 fatal_fr(r, "sshbuf_put"); 736 737 while (sshbuf_len(inc) != 0) { 738 item = xcalloc(1, sizeof(*item)); 739 if ((item->contents = sshbuf_new()) == NULL) 740 fatal_f("sshbuf_new failed"); 741 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 || 742 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 || 743 (r = sshbuf_get_stringb(inc, item->contents)) != 0) 744 fatal_fr(r, "parse includes"); 745 TAILQ_INSERT_TAIL(&includes, item, entry); 746 } 747 748 parse_hostkeys(hostkeys); 749 750 free(cp); 751 sshbuf_free(m); 752 sshbuf_free(hostkeys); 753 sshbuf_free(inc); 754 755 debug3_f("done"); 756} 757 758/* 759 * If IP options are supported, make sure there are none (log and 760 * return an error if any are found). Basically we are worried about 761 * source routing; it can be used to pretend you are somebody 762 * (ip-address) you are not. That itself may be "almost acceptable" 763 * under certain circumstances, but rhosts authentication is useless 764 * if source routing is accepted. Notice also that if we just dropped 765 * source routing here, the other side could use IP spoofing to do 766 * rest of the interaction and could still bypass security. So we 767 * exit here if we detect any IP options. 768 */ 769static void 770check_ip_options(struct ssh *ssh) 771{ 772 int sock_in = ssh_packet_get_connection_in(ssh); 773 struct sockaddr_storage from; 774 u_char opts[200]; 775 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from); 776 char text[sizeof(opts) * 3 + 1]; 777 778 memset(&from, 0, sizeof(from)); 779 if (getpeername(sock_in, (struct sockaddr *)&from, 780 &fromlen) == -1) 781 return; 782 if (from.ss_family != AF_INET) 783 return; 784 /* XXX IPv6 options? */ 785 786 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts, 787 &option_size) >= 0 && option_size != 0) { 788 text[0] = '\0'; 789 for (i = 0; i < option_size; i++) 790 snprintf(text + i*3, sizeof(text) - i*3, 791 " %2.2x", opts[i]); 792 fatal("Connection from %.100s port %d with IP opts: %.800s", 793 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text); 794 } 795 return; 796} 797 798#ifdef __OpenBSD__ 799/* Set the routing domain for this process */ 800static void 801set_process_rdomain(struct ssh *ssh, const char *name) 802{ 803 int rtable, ortable = getrtable(); 804 const char *errstr; 805 806 if (name == NULL) 807 return; /* default */ 808 809 if (strcmp(name, "%D") == 0) { 810 /* "expands" to routing domain of connection */ 811 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 812 return; 813 } 814 815 rtable = (int)strtonum(name, 0, 255, &errstr); 816 if (errstr != NULL) /* Shouldn't happen */ 817 fatal("Invalid routing domain \"%s\": %s", name, errstr); 818 if (rtable != ortable && setrtable(rtable) != 0) 819 fatal("Unable to set routing domain %d: %s", 820 rtable, strerror(errno)); 821 debug_f("set routing domain %d (was %d)", rtable, ortable); 822} 823#endif 824 825/* 826 * Main program for the daemon. 827 */ 828int 829main(int ac, char **av) 830{ 831 struct ssh *ssh = NULL; 832 extern char *optarg; 833 extern int optind; 834 int r, opt, on = 1, remote_port; 835 int sock_in = -1, sock_out = -1, rexeced_flag = 0, have_key = 0; 836 const char *remote_ip, *rdomain; 837 char *line, *laddr, *logfile = NULL; 838 u_int i; 839 u_int64_t ibytes, obytes; 840 mode_t new_umask; 841 Authctxt *authctxt; 842 struct connection_info *connection_info = NULL; 843 sigset_t sigmask; 844 uint64_t timing_secret = 0; 845 846 sigemptyset(&sigmask); 847 sigprocmask(SIG_SETMASK, &sigmask, NULL); 848 849 /* Save argv. */ 850 saved_argv = av; 851 852 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 853 sanitise_stdfd(); 854 855 /* Initialize configuration options to their default values. */ 856 initialize_server_options(&options); 857 858 /* Parse command-line arguments. */ 859 while ((opt = getopt(ac, av, 860 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) { 861 switch (opt) { 862 case '4': 863 options.address_family = AF_INET; 864 break; 865 case '6': 866 options.address_family = AF_INET6; 867 break; 868 case 'f': 869 config_file_name = optarg; 870 break; 871 case 'c': 872 servconf_add_hostcert("[command-line]", 0, 873 &options, optarg); 874 break; 875 case 'd': 876 if (debug_flag == 0) { 877 debug_flag = 1; 878 options.log_level = SYSLOG_LEVEL_DEBUG1; 879 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 880 options.log_level++; 881 break; 882 case 'D': 883 /* ignore */ 884 break; 885 case 'E': 886 logfile = optarg; 887 /* FALLTHROUGH */ 888 case 'e': 889 log_stderr = 1; 890 break; 891 case 'i': 892 inetd_flag = 1; 893 break; 894 case 'r': 895 /* ignore */ 896 break; 897 case 'R': 898 rexeced_flag = 1; 899 break; 900 case 'Q': 901 /* ignored */ 902 break; 903 case 'q': 904 options.log_level = SYSLOG_LEVEL_QUIET; 905 break; 906 case 'b': 907 /* protocol 1, ignored */ 908 break; 909 case 'p': 910 options.ports_from_cmdline = 1; 911 if (options.num_ports >= MAX_PORTS) { 912 fprintf(stderr, "too many ports.\n"); 913 exit(1); 914 } 915 options.ports[options.num_ports++] = a2port(optarg); 916 if (options.ports[options.num_ports-1] <= 0) { 917 fprintf(stderr, "Bad port number.\n"); 918 exit(1); 919 } 920 break; 921 case 'g': 922 if ((options.login_grace_time = convtime(optarg)) == -1) { 923 fprintf(stderr, "Invalid login grace time.\n"); 924 exit(1); 925 } 926 break; 927 case 'k': 928 /* protocol 1, ignored */ 929 break; 930 case 'h': 931 servconf_add_hostkey("[command-line]", 0, 932 &options, optarg, 1); 933 break; 934 case 't': 935 case 'T': 936 case 'G': 937 fatal("test/dump modes not supported"); 938 break; 939 case 'C': 940 connection_info = server_get_connection_info(ssh, 0, 0); 941 if (parse_server_match_testspec(connection_info, 942 optarg) == -1) 943 exit(1); 944 break; 945 case 'u': 946 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 947 if (utmp_len > HOST_NAME_MAX+1) { 948 fprintf(stderr, "Invalid utmp length.\n"); 949 exit(1); 950 } 951 break; 952 case 'o': 953 line = xstrdup(optarg); 954 if (process_server_config_line(&options, line, 955 "command-line", 0, NULL, NULL, &includes) != 0) 956 exit(1); 957 free(line); 958 break; 959 case 'V': 960 fprintf(stderr, "%s, %s\n", 961 SSH_VERSION, SSH_OPENSSL_VERSION); 962 exit(0); 963 default: 964 usage(); 965 break; 966 } 967 } 968 969 /* Check that there are no remaining arguments. */ 970 if (optind < ac) { 971 fprintf(stderr, "Extra argument %s.\n", av[optind]); 972 exit(1); 973 } 974 975#ifdef WITH_LDAP_PUBKEY 976 /* ldap_options_print(&options.lpk); */ 977 /* XXX initialize/check ldap connection and set *LD */ 978 if (options.lpk.on) { 979 if (options.lpk.l_conf && (ldap_parse_lconf(&options.lpk) < 0) ) 980 error("[LDAP] could not parse %s", options.lpk.l_conf); 981 if (ldap_xconnect(&options.lpk) < 0) 982 error("[LDAP] could not initialize ldap connection"); 983 } 984#endif 985 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 986 987 if (!rexeced_flag) 988 fatal("sshd-session should not be executed directly"); 989 990 closefrom(REEXEC_MIN_FREE_FD); 991 992#ifdef WITH_OPENSSL 993 OpenSSL_add_all_algorithms(); 994#endif 995 996 /* If requested, redirect the logs to the specified logfile. */ 997 if (logfile != NULL) { 998 char *cp, pid_s[32]; 999 1000 snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid()); 1001 cp = percent_expand(logfile, 1002 "p", pid_s, 1003 "P", "sshd-session", 1004 (char *)NULL); 1005 log_redirect_stderr_to(cp); 1006 free(cp); 1007 } 1008 1009 /* 1010 * Force logging to stderr until we have loaded the private host 1011 * key (unless started from inetd) 1012 */ 1013 log_init(__progname, 1014 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1015 SYSLOG_LEVEL_INFO : options.log_level, 1016 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1017 SYSLOG_FACILITY_AUTH : options.log_facility, 1018 log_stderr || !inetd_flag || debug_flag); 1019 1020 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 1021 1022 /* Fetch our configuration */ 1023 if ((cfg = sshbuf_new()) == NULL) 1024 fatal("sshbuf_new config buf failed"); 1025 setproctitle("%s", "[rexeced]"); 1026 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg, &timing_secret); 1027 close(REEXEC_CONFIG_PASS_FD); 1028 parse_server_config(&options, "rexec", cfg, &includes, NULL, 1); 1029 /* Fill in default values for those options not explicitly set. */ 1030 fill_default_server_options(&options); 1031 options.timing_secret = timing_secret; 1032 1033 if (!debug_flag) { 1034 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD); 1035 close(REEXEC_STARTUP_PIPE_FD); 1036 /* 1037 * Signal parent that this child is at a point where 1038 * they can go away if they have a SIGHUP pending. 1039 */ 1040 (void)atomicio(vwrite, startup_pipe, __UNCONST("\0"), 1); 1041 } 1042 1043 /* Check that options are sensible */ 1044 if (options.authorized_keys_command_user == NULL && 1045 (options.authorized_keys_command != NULL && 1046 strcasecmp(options.authorized_keys_command, "none") != 0)) 1047 fatal("AuthorizedKeysCommand set without " 1048 "AuthorizedKeysCommandUser"); 1049 if (options.authorized_principals_command_user == NULL && 1050 (options.authorized_principals_command != NULL && 1051 strcasecmp(options.authorized_principals_command, "none") != 0)) 1052 fatal("AuthorizedPrincipalsCommand set without " 1053 "AuthorizedPrincipalsCommandUser"); 1054 1055 /* 1056 * Check whether there is any path through configured auth methods. 1057 * Unfortunately it is not possible to verify this generally before 1058 * daemonisation in the presence of Match block, but this catches 1059 * and warns for trivial misconfigurations that could break login. 1060 */ 1061 if (options.num_auth_methods != 0) { 1062 for (i = 0; i < options.num_auth_methods; i++) { 1063 if (auth2_methods_valid(options.auth_methods[i], 1064 1) == 0) 1065 break; 1066 } 1067 if (i >= options.num_auth_methods) 1068 fatal("AuthenticationMethods cannot be satisfied by " 1069 "enabled authentication methods"); 1070 } 1071 1072#ifdef WITH_OPENSSL 1073 if (options.moduli_file != NULL) 1074 dh_set_moduli_file(options.moduli_file); 1075#endif 1076 1077 if (options.host_key_agent) { 1078 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1079 setenv(SSH_AUTHSOCKET_ENV_NAME, 1080 options.host_key_agent, 1); 1081 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1082 have_agent = 1; 1083 else 1084 error_r(r, "Could not connect to agent \"%s\"", 1085 options.host_key_agent); 1086 } 1087 1088 if (options.num_host_key_files != sensitive_data.num_hostkeys) { 1089 fatal("internal error: hostkeys confused (config %u recvd %u)", 1090 options.num_host_key_files, sensitive_data.num_hostkeys); 1091 } 1092 1093 for (i = 0; i < options.num_host_key_files; i++) { 1094 if (sensitive_data.host_keys[i] != NULL || 1095 (have_agent && sensitive_data.host_pubkeys[i] != NULL)) { 1096 have_key = 1; 1097 break; 1098 } 1099 } 1100 if (!have_key) 1101 fatal("internal error: monitor received no hostkeys"); 1102 1103 /* Ensure that umask disallows at least group and world write */ 1104 new_umask = umask(0077) | 0022; 1105 (void) umask(new_umask); 1106 1107 /* Initialize the log (it is reinitialized below in case we forked). */ 1108 if (debug_flag) 1109 log_stderr = 1; 1110 log_init(__progname, options.log_level, 1111 options.log_facility, log_stderr); 1112 for (i = 0; i < options.num_log_verbose; i++) 1113 log_verbose_add(options.log_verbose[i]); 1114 1115 /* Reinitialize the log (because of the fork above). */ 1116 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1117 1118 /* 1119 * Chdir to the root directory so that the current disk can be 1120 * unmounted if desired. 1121 */ 1122 if (chdir("/") == -1) 1123 error("chdir(\"/\"): %s", strerror(errno)); 1124 1125 /* ignore SIGPIPE */ 1126 ssh_signal(SIGPIPE, SIG_IGN); 1127 1128 /* Get a connection, either from inetd or rexec */ 1129 if (inetd_flag) { 1130 /* 1131 * NB. must be different fd numbers for the !socket case, 1132 * as packet_connection_is_on_socket() depends on this. 1133 */ 1134 sock_in = dup(STDIN_FILENO); 1135 sock_out = dup(STDOUT_FILENO); 1136 } else { 1137 /* rexec case; accept()ed socket in ancestor listener */ 1138 sock_in = sock_out = dup(STDIN_FILENO); 1139 } 1140 1141 /* 1142 * We intentionally do not close the descriptors 0, 1, and 2 1143 * as our code for setting the descriptors won't work if 1144 * ttyfd happens to be one of those. 1145 */ 1146 if (stdfd_devnull(1, 1, !log_stderr) == -1) 1147 error("stdfd_devnull failed"); 1148 debug("network sockets: %d, %d", sock_in, sock_out); 1149 1150 /* This is the child processing a new connection. */ 1151 setproctitle("%s", "[accepted]"); 1152 1153 /* Executed child processes don't need these. */ 1154 fcntl(sock_out, F_SETFD, FD_CLOEXEC); 1155 fcntl(sock_in, F_SETFD, FD_CLOEXEC); 1156 1157 /* We will not restart on SIGHUP since it no longer makes sense. */ 1158 ssh_signal(SIGALRM, SIG_DFL); 1159 ssh_signal(SIGHUP, SIG_DFL); 1160 ssh_signal(SIGTERM, SIG_DFL); 1161 ssh_signal(SIGQUIT, SIG_DFL); 1162 ssh_signal(SIGCHLD, SIG_DFL); 1163 1164 pfilter_init(); 1165 1166 /* 1167 * Register our connection. This turns encryption off because we do 1168 * not have a key. 1169 */ 1170 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL) 1171 fatal("Unable to create connection"); 1172 the_active_state = ssh; 1173 ssh_packet_set_server(ssh); 1174 1175 check_ip_options(ssh); 1176 1177 /* Prepare the channels layer */ 1178 channel_init_channels(ssh); 1179 channel_set_af(ssh, options.address_family); 1180 server_process_channel_timeouts(ssh); 1181 server_process_permitopen(ssh); 1182 1183 /* Set SO_KEEPALIVE if requested. */ 1184 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) && 1185 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) 1186 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 1187 1188 if ((remote_port = ssh_remote_port(ssh)) < 0) { 1189 debug("ssh_remote_port failed"); 1190 cleanup_exit(255); 1191 } 1192 1193 /* 1194 * The rest of the code depends on the fact that 1195 * ssh_remote_ipaddr() caches the remote ip, even if 1196 * the socket goes away. 1197 */ 1198 remote_ip = ssh_remote_ipaddr(ssh); 1199 1200 rdomain = ssh_packet_rdomain_in(ssh); 1201 1202 /* Log the connection. */ 1203 laddr = get_local_ipaddr(sock_in); 1204 verbose("Connection from %s port %d on %s port %d%s%s%s", 1205 remote_ip, remote_port, laddr, ssh_local_port(ssh), 1206 rdomain == NULL ? "" : " rdomain \"", 1207 rdomain == NULL ? "" : rdomain, 1208 rdomain == NULL ? "" : "\""); 1209 free(laddr); 1210 1211 /* 1212 * We don't want to listen forever unless the other side 1213 * successfully authenticates itself. So we set up an alarm which is 1214 * cleared after successful authentication. A limit of zero 1215 * indicates no limit. Note that we don't set the alarm in debugging 1216 * mode; it is just annoying to have the server exit just when you 1217 * are about to discover the bug. 1218 */ 1219 ssh_signal(SIGALRM, grace_alarm_handler); 1220 if (!debug_flag) 1221 alarm(options.login_grace_time); 1222 1223 if ((r = kex_exchange_identification(ssh, -1, 1224 options.version_addendum)) != 0) 1225 sshpkt_fatal(ssh, r, "banner exchange"); 1226 1227 ssh_packet_set_nonblocking(ssh); 1228 1229 /* allocate authentication context */ 1230 authctxt = xcalloc(1, sizeof(*authctxt)); 1231 ssh->authctxt = authctxt; 1232 1233 /* XXX global for cleanup, access from other modules */ 1234 the_authctxt = authctxt; 1235 1236 /* Set default key authentication options */ 1237 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL) 1238 fatal("allocation failed"); 1239 1240 /* prepare buffer to collect messages to display to user after login */ 1241 if ((loginmsg = sshbuf_new()) == NULL) 1242 fatal("sshbuf_new loginmsg failed"); 1243 auth_debug_reset(); 1244 1245 if (privsep_preauth(ssh) == 1) 1246 goto authenticated; 1247 1248 /* perform the key exchange */ 1249 /* authenticate user and start session */ 1250 do_ssh2_kex(ssh); 1251 do_authentication2(ssh); 1252 1253 /* 1254 * The unprivileged child now transfers the current keystate and exits. 1255 */ 1256 mm_send_keystate(ssh, pmonitor); 1257 ssh_packet_clear_keys(ssh); 1258 exit(0); 1259 1260 authenticated: 1261 /* 1262 * Cancel the alarm we set to limit the time taken for 1263 * authentication. 1264 */ 1265 alarm(0); 1266 ssh_signal(SIGALRM, SIG_DFL); 1267 authctxt->authenticated = 1; 1268 if (startup_pipe != -1) { 1269 /* signal listener that authentication completed successfully */ 1270 (void)atomicio(vwrite, startup_pipe, __UNCONST("\001"), 1); 1271 close(startup_pipe); 1272 startup_pipe = -1; 1273 } 1274 1275#ifdef __OpenBSD__ 1276 if (options.routing_domain != NULL) 1277 set_process_rdomain(ssh, options.routing_domain); 1278#endif 1279 1280#ifdef GSSAPI 1281 if (options.gss_authentication) { 1282 temporarily_use_uid(authctxt->pw); 1283 ssh_gssapi_storecreds(); 1284 restore_uid(); 1285 } 1286#endif 1287#ifdef USE_PAM 1288 if (options.use_pam) { 1289 do_pam_setcred(); 1290 do_pam_session(ssh); 1291 } 1292#endif 1293 1294 /* 1295 * In privilege separation, we fork another child and prepare 1296 * file descriptor passing. 1297 */ 1298 privsep_postauth(ssh, authctxt); 1299 /* the monitor process [priv] will not return */ 1300 1301 ssh_packet_set_timeout(ssh, options.client_alive_interval, 1302 options.client_alive_count_max); 1303 1304 /* Try to send all our hostkeys to the client */ 1305 notify_hostkeys(ssh); 1306 1307 /* Start session. */ 1308 do_authenticated(ssh, authctxt); 1309 1310 /* The connection has been terminated. */ 1311 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 1312 verbose("Transferred: sent %llu, received %llu bytes", 1313 (unsigned long long)obytes, (unsigned long long)ibytes); 1314 1315#ifdef USE_PAM 1316 if (options.use_pam) 1317 finish_pam(); 1318#endif /* USE_PAM */ 1319 1320 verbose("Closing connection to %.500s port %d", remote_ip, remote_port); 1321 ssh_packet_close(ssh); 1322 1323 mm_terminate(); 1324 1325 exit(0); 1326} 1327 1328int 1329sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey, 1330 struct sshkey *pubkey, u_char **signature, size_t *slenp, 1331 const u_char *data, size_t dlen, const char *alg) 1332{ 1333 if (privkey) { 1334 if (mm_sshkey_sign(ssh, privkey, signature, slenp, 1335 data, dlen, alg, options.sk_provider, NULL, 1336 ssh->compat) < 0) 1337 fatal_f("privkey sign failed"); 1338 } else { 1339 if (mm_sshkey_sign(ssh, pubkey, signature, slenp, 1340 data, dlen, alg, options.sk_provider, NULL, 1341 ssh->compat) < 0) 1342 fatal_f("pubkey sign failed"); 1343 } 1344 return 0; 1345} 1346 1347/* SSH2 key exchange */ 1348static void 1349do_ssh2_kex(struct ssh *ssh) 1350{ 1351 char *hkalgs = NULL, *myproposal[PROPOSAL_MAX]; 1352 const char *compression = NULL; 1353 struct kex *kex; 1354 int r; 1355 1356 if (options.rekey_limit || options.rekey_interval) 1357 ssh_packet_set_rekey_limits(ssh, options.rekey_limit, 1358 options.rekey_interval); 1359 1360 if (options.compression == COMP_NONE) 1361 compression = "none"; 1362 hkalgs = list_hostkey_types(); 1363 1364 kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms, 1365 options.ciphers, options.macs, compression, hkalgs); 1366 1367 free(hkalgs); 1368 1369 /* start key exchange */ 1370 if ((r = kex_setup(ssh, myproposal)) != 0) 1371 fatal_r(r, "kex_setup"); 1372 kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos); 1373 kex = ssh->kex; 1374 1375#ifdef WITH_OPENSSL 1376 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server; 1377 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server; 1378 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server; 1379 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server; 1380 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server; 1381 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; 1382 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; 1383 kex->kex[KEX_ECDH_SHA2] = kex_gen_server; 1384#endif 1385 kex->kex[KEX_C25519_SHA256] = kex_gen_server; 1386 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server; 1387 kex->load_host_public_key=&get_hostkey_public_by_type; 1388 kex->load_host_private_key=&get_hostkey_private_by_type; 1389 kex->host_key_index=&get_hostkey_index; 1390 kex->sign = sshd_hostkey_sign; 1391 1392 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done); 1393 kex_proposal_free_entries(myproposal); 1394 1395#ifdef DEBUG_KEXDH 1396 /* send 1st encrypted/maced/compressed message */ 1397 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 || 1398 (r = sshpkt_put_cstring(ssh, "markus")) != 0 || 1399 (r = sshpkt_send(ssh)) != 0 || 1400 (r = ssh_packet_write_wait(ssh)) != 0) 1401 fatal_fr(r, "send test"); 1402#endif 1403 debug("KEX done"); 1404} 1405 1406/* server specific fatal cleanup */ 1407void 1408cleanup_exit(int i) 1409{ 1410 extern int auth_attempted; /* monitor.c */ 1411 1412 if (i == 255) 1413 pfilter_notify(1); 1414 1415 if (the_active_state != NULL && the_authctxt != NULL) { 1416 do_cleanup(the_active_state, the_authctxt); 1417 if (privsep_is_preauth && 1418 pmonitor != NULL && pmonitor->m_pid > 1) { 1419 debug("Killing privsep child %d", pmonitor->m_pid); 1420 if (kill(pmonitor->m_pid, SIGKILL) != 0 && 1421 errno != ESRCH) { 1422 error_f("kill(%d): %s", pmonitor->m_pid, 1423 strerror(errno)); 1424 } 1425 } 1426 } 1427 /* Override default fatal exit value when auth was attempted */ 1428 if (i == 255 && auth_attempted) 1429 _exit(EXIT_AUTH_ATTEMPTED); 1430 _exit(i); 1431} 1432