sshd-auth.c revision 1.3.4.2 1 /* $NetBSD: sshd-auth.c,v 1.3.4.2 2025/08/02 05:18:49 perseant Exp $ */
2 /* $OpenBSD: sshd-auth.c,v 1.3 2025/01/16 06:37:10 dtucker Exp $ */
3
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-auth.c,v 1.3.4.2 2025/08/02 05:18:49 perseant Exp $");
34
35 #include <sys/param.h>
36 #include <sys/types.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 "xmalloc.h"
64 #include "ssh.h"
65 #include "ssh2.h"
66 #include "sshpty.h"
67 #include "packet.h"
68 #include "log.h"
69 #include "sshbuf.h"
70 #include "misc.h"
71 #include "match.h"
72 #include "servconf.h"
73 #include "uidswap.h"
74 #include "compat.h"
75 #include "cipher.h"
76 #include "digest.h"
77 #include "sshkey.h"
78 #include "kex.h"
79 #include "authfile.h"
80 #include "pathnames.h"
81 #include "atomicio.h"
82 #include "canohost.h"
83 #include "hostfile.h"
84 #include "auth.h"
85 #include "authfd.h"
86 #include "msg.h"
87 #include "dispatch.h"
88 #include "channels.h"
89 #include "session.h"
90 #include "monitor.h"
91 #ifdef GSSAPI
92 #include "ssh-gss.h"
93 #endif
94 #include "monitor_wrap.h"
95 #include "auth-options.h"
96 #include "version.h"
97 #include "ssherr.h"
98 #include "sk-api.h"
99 #include "srclimit.h"
100 #include "dh.h"
101
102 /* Privsep fds */
103 #define PRIVSEP_MONITOR_FD (STDERR_FILENO + 1)
104 #define PRIVSEP_LOG_FD (STDERR_FILENO + 2)
105 #define PRIVSEP_MIN_FREE_FD (STDERR_FILENO + 3)
106
107 #ifdef LIBWRAP
108 #include <syslog.h>
109 int allow_severity = LOG_INFO;
110 int deny_severity = LOG_WARNING;
111 #endif
112
113 extern char *__progname;
114
115 /* Server configuration options. */
116 ServerOptions options;
117
118 /* Name of the server configuration file. */
119 const char *config_file_name = _PATH_SERVER_CONFIG_FILE;
120
121 /*
122 * Debug mode flag. This can be set on the command line. If debug
123 * mode is enabled, extra debugging output will be sent to the system
124 * log, the daemon will not go to background, and will exit after processing
125 * the first connection.
126 */
127 int debug_flag = 0;
128
129 /* Flag indicating that the daemon is being started from inetd. */
130 static int inetd_flag = 0;
131
132 /* Saved arguments to main(). */
133 static char **saved_argv;
134
135 /* Daemon's agent connection */
136 int auth_sock = -1;
137 static int have_agent = 0;
138
139 u_int num_hostkeys;
140 struct sshkey **host_pubkeys; /* all public host keys */
141 struct sshkey **host_certificates; /* all public host certificates */
142
143 /* record remote hostname or ip */
144 #ifndef HOST_NAME_MAX
145 #define HOST_NAME_MAX MAXHOSTNAMELEN
146 #endif
147 u_int utmp_len = HOST_NAME_MAX+1;
148
149 /* variables used for privilege separation */
150 struct monitor *pmonitor = NULL;
151 int privsep_is_preauth = 1;
152
153 /* global connection state and authentication contexts */
154 Authctxt *the_authctxt = NULL;
155 struct ssh *the_active_state;
156
157 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
158 struct sshauthopt *auth_opts = NULL;
159
160 /* sshd_config buffer */
161 struct sshbuf *cfg;
162
163 /* Included files from the configuration file */
164 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
165
166 /* message to be displayed after login */
167 struct sshbuf *loginmsg;
168
169 /* Prototypes for various functions defined later in this file. */
170 static void do_ssh2_kex(struct ssh *);
171
172 /* XXX stub */
173 int
174 mm_is_monitor(void)
175 {
176 return 0;
177 }
178
179 static void
180 privsep_child_demote(void)
181 {
182 gid_t gidset[1];
183 struct passwd *pw;
184
185 /* Demote the child */
186 if (getuid() == 0 || geteuid() == 0) {
187 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
188 fatal("Privilege separation user %s does not exist",
189 SSH_PRIVSEP_USER);
190 pw = pwcopy(pw); /* Ensure mutable */
191 endpwent();
192 freezero(pw->pw_passwd, strlen(pw->pw_passwd));
193
194 /* Change our root directory */
195 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
196 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
197 strerror(errno));
198 if (chdir("/") == -1)
199 fatal("chdir(\"/\"): %s", strerror(errno));
200
201 /*
202 * Drop our privileges
203 * NB. Can't use setusercontext() after chroot.
204 */
205 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
206 (u_int)pw->pw_gid);
207 gidset[0] = pw->pw_gid;
208 if (setgroups(1, gidset) == -1)
209 fatal("setgroups: %.100s", strerror(errno));
210 permanently_set_uid(pw);
211 }
212
213 /* sandbox ourselves */
214 #ifdef __OpenBSD__
215 if (pledge("stdio", NULL) == -1)
216 fatal_f("pledge()");
217 #endif
218 }
219
220 static void
221 append_hostkey_type(struct sshbuf *b, const char *s)
222 {
223 int r;
224
225 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
226 debug3_f("%s key not permitted by HostkeyAlgorithms", s);
227 return;
228 }
229 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
230 fatal_fr(r, "sshbuf_putf");
231 }
232
233 static char *
234 list_hostkey_types(void)
235 {
236 struct sshbuf *b;
237 struct sshkey *key;
238 char *ret;
239 u_int i;
240
241 if ((b = sshbuf_new()) == NULL)
242 fatal_f("sshbuf_new failed");
243 for (i = 0; i < options.num_host_key_files; i++) {
244 key = host_pubkeys[i];
245 if (key == NULL)
246 continue;
247 switch (key->type) {
248 case KEY_RSA:
249 /* for RSA we also support SHA2 signatures */
250 append_hostkey_type(b, "rsa-sha2-512");
251 append_hostkey_type(b, "rsa-sha2-256");
252 /* FALLTHROUGH */
253 case KEY_DSA:
254 case KEY_ECDSA:
255 case KEY_ED25519:
256 case KEY_ECDSA_SK:
257 case KEY_ED25519_SK:
258 case KEY_XMSS:
259 append_hostkey_type(b, sshkey_ssh_name(key));
260 break;
261 }
262 /* If the private key has a cert peer, then list that too */
263 key = host_certificates[i];
264 if (key == NULL)
265 continue;
266 switch (key->type) {
267 case KEY_RSA_CERT:
268 /* for RSA we also support SHA2 signatures */
269 append_hostkey_type(b,
270 "rsa-sha2-512-cert-v01 (at) openssh.com");
271 append_hostkey_type(b,
272 "rsa-sha2-256-cert-v01 (at) openssh.com");
273 /* FALLTHROUGH */
274 case KEY_DSA_CERT:
275 case KEY_ECDSA_CERT:
276 case KEY_ED25519_CERT:
277 case KEY_ECDSA_SK_CERT:
278 case KEY_ED25519_SK_CERT:
279 case KEY_XMSS_CERT:
280 append_hostkey_type(b, sshkey_ssh_name(key));
281 break;
282 }
283 }
284 if ((ret = sshbuf_dup_string(b)) == NULL)
285 fatal_f("sshbuf_dup_string failed");
286 sshbuf_free(b);
287 debug_f("%s", ret);
288 return ret;
289 }
290
291 struct sshkey *
292 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
293 {
294 u_int i;
295 struct sshkey *key;
296
297 for (i = 0; i < options.num_host_key_files; i++) {
298 switch (type) {
299 case KEY_RSA_CERT:
300 case KEY_DSA_CERT:
301 case KEY_ECDSA_CERT:
302 case KEY_ED25519_CERT:
303 case KEY_ECDSA_SK_CERT:
304 case KEY_ED25519_SK_CERT:
305 case KEY_XMSS_CERT:
306 key = host_certificates[i];
307 break;
308 default:
309 key = host_pubkeys[i];
310 break;
311 }
312 if (key == NULL || key->type != type)
313 continue;
314 switch (type) {
315 case KEY_ECDSA:
316 case KEY_ECDSA_SK:
317 case KEY_ECDSA_CERT:
318 case KEY_ECDSA_SK_CERT:
319 if (key->ecdsa_nid != nid)
320 continue;
321 /* FALLTHROUGH */
322 default:
323 return key;
324 }
325 }
326 return NULL;
327 }
328
329 /* XXX remove */
330 struct sshkey *
331 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
332 {
333 return NULL;
334 }
335
336 /* XXX remove */
337 struct sshkey *
338 get_hostkey_by_index(int ind)
339 {
340 return NULL;
341 }
342
343 struct sshkey *
344 get_hostkey_public_by_index(int ind, struct ssh *ssh)
345 {
346 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
347 return (NULL);
348 return host_pubkeys[ind];
349 }
350
351 int
352 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
353 {
354 u_int i;
355
356 for (i = 0; i < options.num_host_key_files; i++) {
357 if (sshkey_is_cert(key)) {
358 if (key == host_certificates[i] ||
359 (compare && host_certificates[i] &&
360 sshkey_equal(key, host_certificates[i])))
361 return (i);
362 } else {
363 if (key == host_pubkeys[i] ||
364 (compare && host_pubkeys[i] &&
365 sshkey_equal(key, host_pubkeys[i])))
366 return (i);
367 }
368 }
369 return (-1);
370 }
371
372 __attribute__((__noreturn__))
373 static void
374 usage(void)
375 {
376 fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION);
377 fprintf(stderr,
378 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
379 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
380 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
381 );
382 exit(1);
383 }
384
385 static void
386 parse_hostkeys(struct sshbuf *hostkeys)
387 {
388 int r;
389 u_int num_keys = 0;
390 struct sshkey *k;
391 const u_char *cp;
392 size_t len;
393
394 while (sshbuf_len(hostkeys) != 0) {
395 if (num_keys > 2048)
396 fatal_f("too many hostkeys");
397 host_pubkeys = xrecallocarray(host_pubkeys,
398 num_keys, num_keys + 1, sizeof(*host_pubkeys));
399 host_certificates = xrecallocarray(host_certificates,
400 num_keys, num_keys + 1, sizeof(*host_certificates));
401 /* public key */
402 k = NULL;
403 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
404 fatal_fr(r, "extract pubkey");
405 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
406 fatal_fr(r, "parse pubkey");
407 host_pubkeys[num_keys] = k;
408 if (k)
409 debug2_f("key %u: %s", num_keys, sshkey_ssh_name(k));
410 /* certificate */
411 k = NULL;
412 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
413 fatal_fr(r, "extract pubkey");
414 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
415 fatal_fr(r, "parse pubkey");
416 host_certificates[num_keys] = k;
417 if (k)
418 debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k));
419 num_keys++;
420 }
421 num_hostkeys = num_keys;
422 }
423
424 static void
425 recv_privsep_state(struct ssh *ssh, struct sshbuf *conf,
426 uint64_t *timing_secretp)
427 {
428 struct sshbuf *hostkeys;
429
430 debug3_f("begin");
431
432 mm_get_state(ssh, &includes, conf, NULL, timing_secretp,
433 &hostkeys, NULL, NULL, NULL, NULL);
434 parse_hostkeys(hostkeys);
435
436 sshbuf_free(hostkeys);
437
438 debug3_f("done");
439 }
440
441 /*
442 * Main program for the daemon.
443 */
444 int
445 main(int ac, char **av)
446 {
447 struct ssh *ssh = NULL;
448 extern char *optarg;
449 extern int optind;
450 int r, opt, have_key = 0;
451 int sock_in = -1, sock_out = -1, rexeced_flag = 0;
452 char *line, *logfile = NULL;
453 u_int i;
454 mode_t new_umask;
455 Authctxt *authctxt;
456 struct connection_info *connection_info = NULL;
457 sigset_t sigmask;
458 uint64_t timing_secret = 0;
459
460 closefrom(PRIVSEP_MIN_FREE_FD);
461 sigemptyset(&sigmask);
462 sigprocmask(SIG_SETMASK, &sigmask, NULL);
463
464 /* Save argv. */
465 saved_argv = av;
466
467 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
468 sanitise_stdfd();
469
470 /* Initialize configuration options to their default values. */
471 initialize_server_options(&options);
472
473 /* Parse command-line arguments. */
474 while ((opt = getopt(ac, av,
475 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
476 switch (opt) {
477 case '4':
478 options.address_family = AF_INET;
479 break;
480 case '6':
481 options.address_family = AF_INET6;
482 break;
483 case 'f':
484 config_file_name = optarg;
485 break;
486 case 'c':
487 servconf_add_hostcert("[command-line]", 0,
488 &options, optarg);
489 break;
490 case 'd':
491 if (debug_flag == 0) {
492 debug_flag = 1;
493 options.log_level = SYSLOG_LEVEL_DEBUG1;
494 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
495 options.log_level++;
496 break;
497 case 'D':
498 /* ignore */
499 break;
500 case 'E':
501 logfile = optarg;
502 /* FALLTHROUGH */
503 case 'e':
504 /* ignore */
505 break;
506 case 'i':
507 inetd_flag = 1;
508 break;
509 case 'r':
510 /* ignore */
511 break;
512 case 'R':
513 rexeced_flag = 1;
514 break;
515 case 'Q':
516 /* ignored */
517 break;
518 case 'q':
519 options.log_level = SYSLOG_LEVEL_QUIET;
520 break;
521 case 'b':
522 /* protocol 1, ignored */
523 break;
524 case 'p':
525 options.ports_from_cmdline = 1;
526 if (options.num_ports >= MAX_PORTS) {
527 fprintf(stderr, "too many ports.\n");
528 exit(1);
529 }
530 options.ports[options.num_ports++] = a2port(optarg);
531 if (options.ports[options.num_ports-1] <= 0) {
532 fprintf(stderr, "Bad port number.\n");
533 exit(1);
534 }
535 break;
536 case 'g':
537 if ((options.login_grace_time = convtime(optarg)) == -1) {
538 fprintf(stderr, "Invalid login grace time.\n");
539 exit(1);
540 }
541 break;
542 case 'k':
543 /* protocol 1, ignored */
544 break;
545 case 'h':
546 servconf_add_hostkey("[command-line]", 0,
547 &options, optarg, 1);
548 break;
549 case 't':
550 case 'T':
551 case 'G':
552 fatal("test/dump modes not supported");
553 break;
554 case 'C':
555 connection_info = server_get_connection_info(ssh, 0, 0);
556 if (parse_server_match_testspec(connection_info,
557 optarg) == -1)
558 exit(1);
559 break;
560 case 'u':
561 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
562 if (utmp_len > HOST_NAME_MAX+1) {
563 fprintf(stderr, "Invalid utmp length.\n");
564 exit(1);
565 }
566 break;
567 case 'o':
568 line = xstrdup(optarg);
569 if (process_server_config_line(&options, line,
570 "command-line", 0, NULL, NULL, &includes) != 0)
571 exit(1);
572 free(line);
573 break;
574 case 'V':
575 fprintf(stderr, "%s, %s\n",
576 SSH_VERSION, SSH_OPENSSL_VERSION);
577 exit(0);
578 default:
579 usage();
580 break;
581 }
582 }
583
584 if (!rexeced_flag)
585 fatal("sshd-auth should not be executed directly");
586
587 #ifdef WITH_OPENSSL
588 OpenSSL_add_all_algorithms();
589 #endif
590
591 /* If requested, redirect the logs to the specified logfile. */
592 if (logfile != NULL) {
593 char *cp, pid_s[32];
594
595 snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
596 cp = percent_expand(logfile,
597 "p", pid_s,
598 "P", "sshd-auth",
599 (char *)NULL);
600 log_redirect_stderr_to(cp);
601 free(cp);
602 }
603
604 log_init(__progname,
605 options.log_level == SYSLOG_LEVEL_NOT_SET ?
606 SYSLOG_LEVEL_INFO : options.log_level,
607 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
608 SYSLOG_FACILITY_AUTH : options.log_facility, 1);
609
610 /* XXX can't use monitor_init(); it makes fds */
611 pmonitor = xcalloc(1, sizeof(*pmonitor));
612 pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
613 pmonitor->m_recvfd = PRIVSEP_MONITOR_FD;
614 pmonitor->m_log_sendfd = PRIVSEP_LOG_FD;
615 set_log_handler(mm_log_handler, pmonitor);
616
617 /* Check that there are no remaining arguments. */
618 if (optind < ac) {
619 fprintf(stderr, "Extra argument %s.\n", av[optind]);
620 exit(1);
621 }
622
623 /* Connection passed by stdin/out */
624 if (inetd_flag) {
625 /*
626 * NB. must be different fd numbers for the !socket case,
627 * as packet_connection_is_on_socket() depends on this.
628 */
629 sock_in = dup(STDIN_FILENO);
630 sock_out = dup(STDOUT_FILENO);
631 } else {
632 /* rexec case; accept()ed socket in ancestor listener */
633 sock_in = sock_out = dup(STDIN_FILENO);
634 }
635
636 if (stdfd_devnull(1, 1, 0) == -1)
637 error("stdfd_devnull failed");
638 debug("network sockets: %d, %d", sock_in, sock_out);
639
640 /*
641 * Register our connection. This turns encryption off because we do
642 * not have a key.
643 */
644 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
645 fatal("Unable to create connection");
646 the_active_state = ssh;
647 ssh_packet_set_server(ssh);
648 pmonitor->m_pkex = &ssh->kex;
649
650 /* Fetch our configuration */
651 if ((cfg = sshbuf_new()) == NULL)
652 fatal("sshbuf_new config buf failed");
653 setproctitle("%s", "[session-auth early]");
654 recv_privsep_state(ssh, cfg, &timing_secret);
655 parse_server_config(&options, "rexec", cfg, &includes, NULL, 1);
656 /* Fill in default values for those options not explicitly set. */
657 fill_default_server_options(&options);
658 options.timing_secret = timing_secret; /* XXX eliminate from unpriv */
659
660 /* Reinit logging in case config set Level, Facility or Verbose. */
661 log_init(__progname, options.log_level, options.log_facility, 1);
662
663 debug("sshd-auth version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
664
665 #ifdef WITH_OPENSSL
666 if (options.moduli_file != NULL)
667 dh_set_moduli_file(options.moduli_file);
668 #endif
669
670 if (options.host_key_agent) {
671 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
672 setenv(SSH_AUTHSOCKET_ENV_NAME,
673 options.host_key_agent, 1);
674 if ((r = ssh_get_authentication_socket(NULL)) == 0)
675 have_agent = 1;
676 else
677 error_r(r, "Could not connect to agent \"%s\"",
678 options.host_key_agent);
679 }
680
681 if (options.num_host_key_files != num_hostkeys) {
682 fatal("internal error: hostkeys confused (config %u recvd %u)",
683 options.num_host_key_files, num_hostkeys);
684 }
685
686 for (i = 0; i < options.num_host_key_files; i++) {
687 if (host_pubkeys[i] != NULL) {
688 have_key = 1;
689 break;
690 }
691 }
692 if (!have_key)
693 fatal("internal error: received no hostkeys");
694
695 /* Ensure that umask disallows at least group and world write */
696 new_umask = umask(0077) | 0022;
697 (void) umask(new_umask);
698
699 /* Initialize the log (it is reinitialized below in case we forked). */
700 log_init(__progname, options.log_level, options.log_facility, 1);
701 set_log_handler(mm_log_handler, pmonitor);
702 for (i = 0; i < options.num_log_verbose; i++)
703 log_verbose_add(options.log_verbose[i]);
704
705 /*
706 * Chdir to the root directory so that the current disk can be
707 * unmounted if desired.
708 */
709 if (chdir("/") == -1)
710 error("chdir(\"/\"): %s", strerror(errno));
711
712 /* This is the child authenticating a new connection. */
713 setproctitle("%s", "[session-auth]");
714
715 /* Executed child processes don't need these. */
716 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
717 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
718
719 ssh_signal(SIGPIPE, SIG_IGN);
720 ssh_signal(SIGALRM, SIG_DFL);
721 ssh_signal(SIGHUP, SIG_DFL);
722 ssh_signal(SIGTERM, SIG_DFL);
723 ssh_signal(SIGQUIT, SIG_DFL);
724 ssh_signal(SIGCHLD, SIG_DFL);
725
726 /* Prepare the channels layer */
727 channel_init_channels(ssh);
728 channel_set_af(ssh, options.address_family);
729 server_process_channel_timeouts(ssh);
730 server_process_permitopen(ssh);
731
732 ssh_packet_set_nonblocking(ssh);
733
734 /* allocate authentication context */
735 authctxt = xcalloc(1, sizeof(*authctxt));
736 ssh->authctxt = authctxt;
737
738 /* XXX global for cleanup, access from other modules */
739 the_authctxt = authctxt;
740
741 /* Set default key authentication options */
742 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
743 fatal("allocation failed");
744
745 /* prepare buffer to collect messages to display to user after login */
746 if ((loginmsg = sshbuf_new()) == NULL)
747 fatal("sshbuf_new loginmsg failed");
748 auth_debug_reset();
749
750 /* Enable challenge-response authentication for privilege separation */
751 privsep_challenge_enable();
752
753 #ifdef GSSAPI
754 /* Cache supported mechanism OIDs for later use */
755 ssh_gssapi_prepare_supported_oids();
756 #endif
757
758 privsep_child_demote();
759
760 /* perform the key exchange */
761 /* authenticate user and start session */
762 do_ssh2_kex(ssh);
763 do_authentication2(ssh);
764
765 /*
766 * The unprivileged child now transfers the current keystate and exits.
767 */
768 mm_send_keystate(ssh, pmonitor);
769 ssh_packet_clear_keys(ssh);
770 exit(0);
771 }
772
773 int
774 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
775 struct sshkey *pubkey, u_char **signature, size_t *slenp,
776 const u_char *data, size_t dlen, const char *alg)
777 {
778 if (privkey) {
779 if (mm_sshkey_sign(ssh, privkey, signature, slenp,
780 data, dlen, alg, options.sk_provider, NULL,
781 ssh->compat) < 0)
782 fatal_f("privkey sign failed");
783 } else {
784 if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
785 data, dlen, alg, options.sk_provider, NULL,
786 ssh->compat) < 0)
787 fatal_f("pubkey sign failed");
788 }
789 return 0;
790 }
791
792 /* SSH2 key exchange */
793 static void
794 do_ssh2_kex(struct ssh *ssh)
795 {
796 char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
797 const char *compression = NULL;
798 struct kex *kex;
799 int r;
800
801 if (options.rekey_limit || options.rekey_interval)
802 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
803 options.rekey_interval);
804
805 if (options.compression == COMP_NONE)
806 compression = "none";
807 hkalgs = list_hostkey_types();
808
809 kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
810 options.ciphers, options.macs, compression, hkalgs);
811
812 free(hkalgs);
813
814 /* start key exchange */
815 if ((r = kex_setup(ssh, myproposal)) != 0)
816 fatal_r(r, "kex_setup");
817 kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos);
818 kex = ssh->kex;
819
820 #ifdef WITH_OPENSSL
821 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
822 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
823 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
824 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
825 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
826 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
827 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
828 kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
829 #endif
830 kex->kex[KEX_C25519_SHA256] = kex_gen_server;
831 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
832 kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
833 kex->load_host_public_key=&get_hostkey_public_by_type;
834 kex->load_host_private_key=&get_hostkey_private_by_type;
835 kex->host_key_index=&get_hostkey_index;
836 kex->sign = sshd_hostkey_sign;
837
838 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
839 kex_proposal_free_entries(myproposal);
840
841 #ifdef DEBUG_KEXDH
842 /* send 1st encrypted/maced/compressed message */
843 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
844 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
845 (r = sshpkt_send(ssh)) != 0 ||
846 (r = ssh_packet_write_wait(ssh)) != 0)
847 fatal_fr(r, "send test");
848 #endif
849 debug("KEX done");
850 }
851
852 /* server specific fatal cleanup */
853 void
854 cleanup_exit(int i)
855 {
856 _exit(i);
857 }
858