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