1 /*        $NetBSD: sshd.c,v 1.55 2025/04/09 15:49:33 christos Exp $   */
2 /* $OpenBSD: sshd.c,v 1.617 2025/04/07 08:12:22 dtucker Exp $ */
3 
4 /*
5  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
6  * Copyright (c) 2002 Niels Provos.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include "includes.h"
30 __RCSID("$NetBSD: sshd.c,v 1.55 2025/04/09 15:49:33 christos Exp $");
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/ioctl.h>
34 #include <sys/wait.h>
35 #include <sys/tree.h>
36 #include <sys/stat.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #include <sys/queue.h>
40 #include <sys/utsname.h>
41 
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <paths.h>
46 #include <poll.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <stdarg.h>
53 #include <time.h>
54 #include <unistd.h>
55 #include <limits.h>
56 
57 #ifdef WITH_OPENSSL
58 #include <openssl/bn.h>
59 #include <openssl/evp.h>
60 #endif
61 
62 #include "xmalloc.h"
63 #include "ssh.h"
64 #include "sshpty.h"
65 #include "log.h"
66 #include "sshbuf.h"
67 #include "misc.h"
68 #include "servconf.h"
69 #include "compat.h"
70 #include "digest.h"
71 #include "sshkey.h"
72 #include "authfile.h"
73 #include "pathnames.h"
74 #include "canohost.h"
75 #include "hostfile.h"
76 #include "auth.h"
77 #include "authfd.h"
78 #include "misc.h"
79 #include "msg.h"
80 #include "version.h"
81 #include "ssherr.h"
82 #include "sk-api.h"
83 #include "addr.h"
84 #include "srclimit.h"
85 #include "atomicio.h"
86 
87 #ifdef LIBWRAP
88 #include <tcpd.h>
89 #include <syslog.h>
90 int allow_severity = LOG_INFO;
91 int deny_severity = LOG_WARNING;
92 #endif /* LIBWRAP */
93 
94 #ifdef WITH_LDAP_PUBKEY
95 #include "ldapauth.h"
96 #endif
97 
98 #ifndef HOST_NAME_MAX
99 #define HOST_NAME_MAX MAXHOSTNAMELEN
100 #endif
101 
102 /* Re-exec fds */
103 #define REEXEC_DEVCRYPTO_RESERVED_FD    (STDERR_FILENO + 1)
104 #define REEXEC_CONFIG_PASS_FD           (STDERR_FILENO + 2)
105 #define REEXEC_MIN_FREE_FD              (STDERR_FILENO + 3)
106 
107 extern char *__progname;
108 
109 /* Server configuration options. */
110 ServerOptions options;
111 
112 /*
113  * Debug mode flag.  This can be set on the command line.  If debug
114  * mode is enabled, extra debugging output will be sent to the system
115  * log, the daemon will not go to background, and will exit after processing
116  * the first connection.
117  */
118 int debug_flag = 0;
119 
120 /* Saved arguments to main(). */
121 static char **saved_argv;
122 
123 /*
124  * The sockets that the server is listening; this is used in the SIGHUP
125  * signal handler.
126  */
127 #define   MAX_LISTEN_SOCKS    16
128 static int listen_socks[MAX_LISTEN_SOCKS];
129 static int num_listen_socks = 0;
130 
131 /*
132  * Any really sensitive data in the application is contained in this
133  * structure. The idea is that this structure could be locked into memory so
134  * that the pages do not get written into swap.  However, there are some
135  * problems. The private key contains BIGNUMs, and we do not (in principle)
136  * have access to the internals of them, and locking just the structure is
137  * not very useful.  Currently, memory locking is not implemented.
138  */
139 struct {
140           struct sshkey       **host_keys;                  /* all private host keys */
141           struct sshkey       **host_pubkeys;               /* all public host keys */
142           struct sshkey       **host_certificates;          /* all public host certificates */
143           int                 have_ssh2_key;
144 } sensitive_data;
145 
146 /* This is set to true when a signal is received. */
147 static volatile sig_atomic_t received_siginfo = 0;
148 static volatile sig_atomic_t received_sigchld = 0;
149 static volatile sig_atomic_t received_sighup = 0;
150 static volatile sig_atomic_t received_sigterm = 0;
151 
152 /* record remote hostname or ip */
153 u_int utmp_len = HOST_NAME_MAX+1;
154 
155 /*
156  * The early_child/children array below is used for tracking children of the
157  * listening sshd process early in their lifespans, before they have
158  * completed authentication. This tracking is needed for four things:
159  *
160  * 1) Implementing the MaxStartups limit of concurrent unauthenticated
161  *    connections.
162  * 2) Avoiding a race condition for SIGHUP processing, where child processes
163  *    may have listen_socks open that could collide with main listener process
164  *    after it restarts.
165  * 3) Ensuring that rexec'd sshd processes have received their initial state
166  *    from the parent listen process before handling SIGHUP.
167  * 4) Tracking and logging unsuccessful exits from the preauth sshd monitor,
168  *    including and especially those for LoginGraceTime timeouts.
169  *
170  * Child processes signal that they have completed closure of the listen_socks
171  * and (if applicable) received their rexec state by sending a char over their
172  * sock.
173  *
174  * Child processes signal that authentication has completed by sending a
175  * second char over the socket before closing it, otherwise the listener will
176  * continue tracking the child (and using up a MaxStartups slot) until the
177  * preauth subprocess exits, whereupon the listener will log its exit status.
178  * preauth processes will exit with a status of EXIT_LOGIN_GRACE to indicate
179  * they did not authenticate before the LoginGraceTime alarm fired.
180  */
181 struct early_child {
182           int pipefd;
183           int early;                    /* Indicates child closed listener */
184           char *id;           /* human readable connection identifier */
185           pid_t pid;
186           struct xaddr addr;
187           int have_addr;
188           int status, have_status;
189           struct sshbuf *config;
190           struct sshbuf *keys;
191 };
192 static struct early_child *children;
193 static int children_active;
194 
195 /* sshd_config buffer */
196 struct sshbuf *cfg;
197 struct sshbuf *config;        /* packed */
198 
199 /* Included files from the configuration file */
200 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
201 
202 /* message to be displayed after login */
203 struct sshbuf *loginmsg;
204 
205 static char *listener_proctitle;
206 
207 /*
208  * Close all listening sockets
209  */
210 static void
close_listen_socks(void)211 close_listen_socks(void)
212 {
213           int i;
214 
215           for (i = 0; i < num_listen_socks; i++)
216                     close(listen_socks[i]);
217           num_listen_socks = 0;
218 }
219 
220 /* Allocate and initialise the children array */
221 static void
child_alloc(void)222 child_alloc(void)
223 {
224           int i;
225 
226           children = xcalloc(options.max_startups, sizeof(*children));
227           for (i = 0; i < options.max_startups; i++) {
228                     children[i].pipefd = -1;
229                     children[i].pid = -1;
230           }
231 }
232 
233 /* Register a new connection in the children array; child pid comes later */
234 static struct early_child *
child_register(int pipefd,int sockfd)235 child_register(int pipefd, int sockfd)
236 {
237           int i, lport, rport;
238           char *laddr = NULL, *raddr = NULL;
239           struct early_child *child = NULL;
240           struct sockaddr_storage addr;
241           socklen_t addrlen = sizeof(addr);
242           struct sockaddr *sa = (struct sockaddr *)&addr;
243 
244           for (i = 0; i < options.max_startups; i++) {
245                     if (children[i].pipefd != -1 ||
246                         children[i].config != NULL ||
247                         children[i].keys != NULL ||
248                         children[i].pid > 0)
249                               continue;
250                     child = &(children[i]);
251                     break;
252           }
253           if (child == NULL) {
254                     fatal_f("error: accepted connection when all %d child "
255                         " slots full", options.max_startups);
256           }
257           child->pipefd = pipefd;
258           child->early = 1;
259           if ((child->config = sshbuf_fromb(config)) == NULL)
260                     fatal_f("sshbuf_fromb failed");
261           /* record peer address, if available */
262           if (getpeername(sockfd, sa, &addrlen) == 0 &&
263              addr_sa_to_xaddr(sa, addrlen, &child->addr) == 0)
264                     child->have_addr = 1;
265           /* format peer address string for logs */
266           if ((lport = get_local_port(sockfd)) == 0 ||
267               (rport = get_peer_port(sockfd)) == 0) {
268                     /* Not a TCP socket */
269                     raddr = get_peer_ipaddr(sockfd);
270                     xasprintf(&child->id, "connection from %s", raddr);
271           } else {
272                     laddr = get_local_ipaddr(sockfd);
273                     raddr = get_peer_ipaddr(sockfd);
274                     xasprintf(&child->id, "connection from %s to %s", raddr, laddr);
275           }
276           free(laddr);
277           free(raddr);
278           if (++children_active > options.max_startups)
279                     fatal_f("internal error: more children than max_startups");
280 
281           return child;
282 }
283 
284 /*
285  * Finally free a child entry. Don't call this directly.
286  */
287 static void
child_finish(struct early_child * child)288 child_finish(struct early_child *child)
289 {
290           if (children_active == 0)
291                     fatal_f("internal error: children_active underflow");
292           if (child->pipefd != -1)
293                     close(child->pipefd);
294           sshbuf_free(child->config);
295           sshbuf_free(child->keys);
296           free(child->id);
297           memset(child, '\0', sizeof(*child));
298           child->pipefd = -1;
299           child->pid = -1;
300           children_active--;
301 }
302 
303 /*
304  * Close a child's pipe. This will not stop tracking the child immediately
305  * (it will still be tracked for waitpid()) unless force_final is set, or
306  * child has already exited.
307  */
308 static void
child_close(struct early_child * child,int force_final,int quiet)309 child_close(struct early_child *child, int force_final, int quiet)
310 {
311           if (!quiet)
312                     debug_f("enter%s", force_final ? " (forcing)" : "");
313           if (child->pipefd != -1) {
314                     close(child->pipefd);
315                     child->pipefd = -1;
316           }
317           if (child->pid == -1 || force_final)
318                     child_finish(child);
319 }
320 
321 /* Record a child exit. Safe to call from signal handlers */
322 static void
child_exit(pid_t pid,int status)323 child_exit(pid_t pid, int status)
324 {
325           int i;
326 
327           if (children == NULL || pid <= 0)
328                     return;
329           for (i = 0; i < options.max_startups; i++) {
330                     if (children[i].pid == pid) {
331                               children[i].have_status = 1;
332                               children[i].status = status;
333                               break;
334                     }
335           }
336 }
337 
338 /*
339  * Reap a child entry that has exited, as previously flagged
340  * using child_exit().
341  * Handles logging of exit condition and will finalise the child if its pipe
342  * had already been closed.
343  */
344 static void
child_reap(struct early_child * child)345 child_reap(struct early_child *child)
346 {
347           LogLevel level = SYSLOG_LEVEL_DEBUG1;
348           int was_crash, penalty_type = SRCLIMIT_PENALTY_NONE;
349           const char *child_status;
350 
351           if (child->config)
352                     child_status = " (sending config)";
353           else if (child->keys)
354                     child_status = " (sending keys)";
355           else if (child->early)
356                     child_status = " (early)";
357           else
358                     child_status = "";
359 
360           /* Log exit information */
361           if (WIFSIGNALED(child->status)) {
362                     /*
363                      * Increase logging for signals potentially associated
364                      * with serious conditions.
365                      */
366                     if ((was_crash = signal_is_crash(WTERMSIG(child->status))))
367                               level = SYSLOG_LEVEL_ERROR;
368                     do_log2(level, "session process %ld for %s killed by "
369                         "signal %d%s", (long)child->pid, child->id,
370                         WTERMSIG(child->status), child_status);
371                     if (was_crash)
372                               penalty_type = SRCLIMIT_PENALTY_CRASH;
373           } else if (!WIFEXITED(child->status)) {
374                     penalty_type = SRCLIMIT_PENALTY_CRASH;
375                     error("session process %ld for %s terminated abnormally, "
376                         "status=0x%x%s", (long)child->pid, child->id, child->status,
377                         child_status);
378           } else {
379                     /* Normal exit. We care about the status */
380                     switch (WEXITSTATUS(child->status)) {
381                     case 0:
382                               debug3_f("preauth child %ld for %s completed "
383                                   "normally%s", (long)child->pid, child->id,
384                                   child_status);
385                               break;
386                     case EXIT_LOGIN_GRACE:
387                               penalty_type = SRCLIMIT_PENALTY_GRACE_EXCEEDED;
388                               logit("Timeout before authentication for %s, "
389                                   "pid = %ld%s", child->id, (long)child->pid,
390                                   child_status);
391                               break;
392                     case EXIT_CHILD_CRASH:
393                               penalty_type = SRCLIMIT_PENALTY_CRASH;
394                               logit("Session process %ld unpriv child crash for %s%s",
395                                   (long)child->pid, child->id, child_status);
396                               break;
397                     case EXIT_AUTH_ATTEMPTED:
398                               penalty_type = SRCLIMIT_PENALTY_AUTHFAIL;
399                               debug_f("preauth child %ld for %s exited "
400                                   "after unsuccessful auth attempt%s",
401                                   (long)child->pid, child->id, child_status);
402                               break;
403                     case EXIT_CONFIG_REFUSED:
404                               penalty_type = SRCLIMIT_PENALTY_REFUSECONNECTION;
405                               debug_f("preauth child %ld for %s prohibited by"
406                                   "RefuseConnection%s",
407                                   (long)child->pid, child->id, child_status);
408                               break;
409                     default:
410                               penalty_type = SRCLIMIT_PENALTY_NOAUTH;
411                               debug_f("preauth child %ld for %s exited "
412                                   "with status %d%s", (long)child->pid, child->id,
413                                   WEXITSTATUS(child->status), child_status);
414                               break;
415                     }
416           }
417 
418           if (child->have_addr)
419                     srclimit_penalise(&child->addr, penalty_type);
420 
421           child->pid = -1;
422           child->have_status = 0;
423           if (child->pipefd == -1)
424                     child_finish(child);
425 }
426 
427 /* Reap all children that have exited; called after SIGCHLD */
428 static void
child_reap_all_exited(void)429 child_reap_all_exited(void)
430 {
431           int i;
432           pid_t pid;
433           int status;
434 
435           if (children == NULL)
436                     return;
437 
438           for (;;) {
439                     if ((pid = waitpid(-1, &status, WNOHANG)) == 0)
440                               break;
441                     else if (pid == -1) {
442                               if (errno == EINTR || errno == EAGAIN)
443                                         continue;
444                               if (errno != ECHILD)
445                                         error_f("waitpid: %s", strerror(errno));
446                               break;
447                     }
448                     child_exit(pid, status);
449           }
450 
451           for (i = 0; i < options.max_startups; i++) {
452                     if (!children[i].have_status)
453                               continue;
454                     child_reap(&(children[i]));
455           }
456 }
457 
458 static void
close_startup_pipes(void)459 close_startup_pipes(void)
460 {
461           int i;
462 
463           if (children == NULL)
464                     return;
465           for (i = 0; i < options.max_startups; i++) {
466                     if (children[i].pipefd != -1)
467                               child_close(&(children[i]), 1, 1);
468           }
469 }
470 
471 /* Called after SIGINFO */
472 static void
show_info(void)473 show_info(void)
474 {
475           int i;
476           const char *child_status;
477 
478           /* XXX print listening sockets here too */
479           if (children == NULL)
480                     return;
481           logit("%d active startups", children_active);
482           for (i = 0; i < options.max_startups; i++) {
483                     if (children[i].pipefd == -1 && children[i].pid <= 0)
484                               continue;
485                     if (children[i].config)
486                               child_status = " (sending config)";
487                     else if (children[i].keys)
488                               child_status = " (sending keys)";
489                     else if (children[i].early)
490                               child_status = " (early)";
491                     else
492                               child_status = "";
493                     logit("child %d: fd=%d pid=%ld %s%s", i, children[i].pipefd,
494                         (long)children[i].pid, children[i].id, child_status);
495           }
496           srclimit_penalty_info();
497 }
498 
499 /*
500  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
501  * the effect is to reread the configuration file (and to regenerate
502  * the server key).
503  */
504 
505 static void
sighup_handler(int sig)506 sighup_handler(int sig)
507 {
508           received_sighup = 1;
509 }
510 
511 /*
512  * Called from the main program after receiving SIGHUP.
513  * Restarts the server.
514  */
515 __dead
516 static void
sighup_restart(void)517 sighup_restart(void)
518 {
519           logit("Received SIGHUP; restarting.");
520           if (options.pid_file != NULL)
521                     unlink(options.pid_file);
522           close_listen_socks();
523           close_startup_pipes();
524           ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
525           execv(saved_argv[0], saved_argv);
526           logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
527               strerror(errno));
528           exit(1);
529 }
530 
531 /*
532  * Generic signal handler for terminating signals in the master daemon.
533  */
534 static void
sigterm_handler(int sig)535 sigterm_handler(int sig)
536 {
537           received_sigterm = sig;
538 }
539 
540 static void
siginfo_handler(int sig)541 siginfo_handler(int sig)
542 {
543           received_siginfo = 1;
544 }
545 
546 static void
main_sigchld_handler(int sig)547 main_sigchld_handler(int sig)
548 {
549           received_sigchld = 1;
550 }
551 
552 /*
553  * returns 1 if connection should be dropped, 0 otherwise.
554  * dropping starts at connection #max_startups_begin with a probability
555  * of (max_startups_rate/100). the probability increases linearly until
556  * all connections are dropped for startups > max_startups
557  */
558 static int
should_drop_connection(int startups)559 should_drop_connection(int startups)
560 {
561           int p, r;
562 
563           if (startups < options.max_startups_begin)
564                     return 0;
565           if (startups >= options.max_startups)
566                     return 1;
567           if (options.max_startups_rate == 100)
568                     return 1;
569 
570           p  = 100 - options.max_startups_rate;
571           p *= startups - options.max_startups_begin;
572           p /= options.max_startups - options.max_startups_begin;
573           p += options.max_startups_rate;
574           r = arc4random_uniform(100);
575 
576           debug_f("p %d, r %d", p, r);
577           return (r < p) ? 1 : 0;
578 }
579 
580 /*
581  * Check whether connection should be accepted by MaxStartups or for penalty.
582  * Returns 0 if the connection is accepted. If the connection is refused,
583  * returns 1 and attempts to send notification to client.
584  * Logs when the MaxStartups condition is entered or exited, and periodically
585  * while in that state.
586  */
587 static int
drop_connection(int sock,int startups,int notify_pipe)588 drop_connection(int sock, int startups, int notify_pipe)
589 {
590           static struct log_ratelimit_ctx ratelimit_maxstartups;
591           static struct log_ratelimit_ctx ratelimit_penalty;
592           static int init_done;
593           char *laddr, *raddr;
594           const char *reason = NULL, *subreason = NULL;
595           const char msg[] = "Not allowed at this time\r\n";
596           struct log_ratelimit_ctx *rl = NULL;
597           int ratelimited;
598           u_int ndropped;
599 
600           if (!init_done) {
601                     init_done = 1;
602                     log_ratelimit_init(&ratelimit_maxstartups, 4, 60, 20, 5*60);
603                     log_ratelimit_init(&ratelimit_penalty, 8, 60, 30, 2*60);
604           }
605 
606           /* PerSourcePenalties */
607           if (!srclimit_penalty_check_allow(sock, &subreason)) {
608                     reason = "PerSourcePenalties";
609                     rl = &ratelimit_penalty;
610           } else {
611                     /* MaxStartups */
612                     if (!should_drop_connection(startups) &&
613                         srclimit_check_allow(sock, notify_pipe) == 1)
614                               return 0;
615                     reason = "Maxstartups";
616                     rl = &ratelimit_maxstartups;
617           }
618 
619           laddr = get_local_ipaddr(sock);
620           raddr = get_peer_ipaddr(sock);
621           ratelimited = log_ratelimit(rl, time(NULL), NULL, &ndropped);
622           do_log2(ratelimited ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
623               "drop connection #%d from [%s]:%d on [%s]:%d %s",
624               startups,
625               raddr, get_peer_port(sock),
626               laddr, get_local_port(sock),
627               subreason != NULL ? subreason : reason);
628           free(laddr);
629           free(raddr);
630           if (ndropped != 0) {
631                     logit("%s logging rate-limited: additional %u connections "
632                         "dropped", reason, ndropped);
633           }
634 
635           /* best-effort notification to client */
636           (void)write(sock, msg, sizeof(msg) - 1);
637           return 1;
638 }
639 
640 __dead static void
usage(void)641 usage(void)
642 {
643           fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION);
644           fprintf(stderr,
645 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
646 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
647 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
648           );
649           exit(1);
650 }
651 
652 static struct sshbuf *
pack_hostkeys(void)653 pack_hostkeys(void)
654 {
655           struct sshbuf *m = NULL, *keybuf = NULL, *hostkeys = NULL;
656           int r;
657           u_int i;
658           size_t len;
659 
660           if ((m = sshbuf_new()) == NULL ||
661               (keybuf = sshbuf_new()) == NULL ||
662               (hostkeys = sshbuf_new()) == NULL)
663                     fatal_f("sshbuf_new failed");
664 
665           /* pack hostkeys into a string. Empty key slots get empty strings */
666           for (i = 0; i < options.num_host_key_files; i++) {
667                     /* private key */
668                     sshbuf_reset(keybuf);
669                     if (sensitive_data.host_keys[i] != NULL &&
670                         (r = sshkey_private_serialize(sensitive_data.host_keys[i],
671                         keybuf)) != 0)
672                               fatal_fr(r, "serialize hostkey private");
673                     if ((r = sshbuf_put_stringb(hostkeys, keybuf)) != 0)
674                               fatal_fr(r, "compose hostkey private");
675                     /* public key */
676                     if (sensitive_data.host_pubkeys[i] != NULL) {
677                               if ((r = sshkey_puts(sensitive_data.host_pubkeys[i],
678                                   hostkeys)) != 0)
679                                         fatal_fr(r, "compose hostkey public");
680                     } else {
681                               if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
682                                         fatal_fr(r, "compose hostkey empty public");
683                     }
684                     /* cert */
685                     if (sensitive_data.host_certificates[i] != NULL) {
686                               if ((r = sshkey_puts(
687                                   sensitive_data.host_certificates[i],
688                                   hostkeys)) != 0)
689                                         fatal_fr(r, "compose host cert");
690                     } else {
691                               if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
692                                         fatal_fr(r, "compose host cert empty");
693                     }
694           }
695 
696           if ((r = sshbuf_put_u32(m, 0)) != 0 ||
697               (r = sshbuf_put_u8(m, 0)) != 0 ||
698               (r = sshbuf_put_stringb(m, hostkeys)) != 0)
699                     fatal_fr(r, "compose message");
700           if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff)
701                     fatal_f("bad length %zu", len);
702           POKE_U32(sshbuf_mutable_ptr(m), len - 4);
703 
704           sshbuf_free(keybuf);
705           sshbuf_free(hostkeys);
706           return m;
707 }
708 
709 static struct sshbuf *
pack_config(struct sshbuf * conf)710 pack_config(struct sshbuf *conf)
711 {
712           struct sshbuf *m = NULL, *inc = NULL;
713           struct include_item *item = NULL;
714           size_t len;
715           int r;
716 
717           debug3_f("d config len %zu", sshbuf_len(conf));
718 
719           if ((m = sshbuf_new()) == NULL ||
720               (inc = sshbuf_new()) == NULL)
721                     fatal_f("sshbuf_new failed");
722 
723           /* pack includes into a string */
724           TAILQ_FOREACH(item, &includes, entry) {
725                     if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
726                         (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
727                         (r = sshbuf_put_stringb(inc, item->contents)) != 0)
728                               fatal_fr(r, "compose includes");
729           }
730 
731           if ((r = sshbuf_put_u32(m, 0)) != 0 ||
732               (r = sshbuf_put_u8(m, 0)) != 0 ||
733               (r = sshbuf_put_stringb(m, conf)) != 0 ||
734               (r = sshbuf_put_u64(m, options.timing_secret)) != 0 ||
735               (r = sshbuf_put_stringb(m, inc)) != 0)
736                     fatal_fr(r, "compose config");
737 
738           if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff)
739                     fatal_f("bad length %zu", len);
740           POKE_U32(sshbuf_mutable_ptr(m), len - 4);
741 
742           sshbuf_free(inc);
743 
744           debug3_f("done");
745           return m;
746 }
747 
748 /*
749  * Protocol from reexec master to child:
750  *        uint32  size
751  *        uint8   type (ignored)
752  *        string    configuration
753  *        uint64    timing_secret
754  *        string    included_files[] {
755  *                  string    selector
756  *                  string    filename
757  *                  string    contents
758  *        }
759  * Second message
760  *        uint32  size
761  *        uint8   type (ignored)
762  *        string    host_keys[] {
763  *                  string private_key
764  *                  string public_key
765  *                  string certificate
766  *        }
767  */
768 /*
769  * This function is used only if inet_flag or debug_flag is set,
770  * otherwise the data is sent from the main poll loop.
771  * It sends the config from a child process back to the parent.
772  * The parent will read the config after exec.
773  */
774 static void
send_rexec_state(int fd)775 send_rexec_state(int fd)
776 {
777           struct sshbuf *keys;
778           u_int mlen;
779           pid_t pid;
780 
781           if ((pid = fork()) == -1)
782                     fatal_f("fork failed: %s", strerror(errno));
783           if (pid != 0)
784                     return;
785 
786           debug3_f("entering fd = %d config len %zu", fd,
787               sshbuf_len(config));
788 
789           mlen = sshbuf_len(config);
790           if (atomicio(vwrite, fd, sshbuf_mutable_ptr(config), mlen) != mlen)
791                     error_f("write: %s", strerror(errno));
792 
793           keys = pack_hostkeys();
794           mlen = sshbuf_len(keys);
795           if (atomicio(vwrite, fd, sshbuf_mutable_ptr(keys), mlen) != mlen)
796                     error_f("write: %s", strerror(errno));
797 
798           sshbuf_free(keys);
799           debug3_f("done");
800           exit(0);
801 }
802 
803 /*
804  * Listen for TCP connections
805  */
806 static void
listen_on_addrs(struct listenaddr * la)807 listen_on_addrs(struct listenaddr *la)
808 {
809           int ret, listen_sock;
810           struct addrinfo *ai;
811           char ntop[NI_MAXHOST], strport[NI_MAXSERV];
812           int socksize;
813           socklen_t socksizelen = sizeof(int);
814 
815           for (ai = la->addrs; ai; ai = ai->ai_next) {
816                     if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
817                               continue;
818                     if (num_listen_socks >= MAX_LISTEN_SOCKS)
819                               fatal("Too many listen sockets. "
820                                   "Enlarge MAX_LISTEN_SOCKS");
821                     if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
822                         ntop, sizeof(ntop), strport, sizeof(strport),
823                         NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
824                               error("getnameinfo failed: %.100s",
825                                   ssh_gai_strerror(ret));
826                               continue;
827                     }
828                     /* Create socket for listening. */
829                     listen_sock = socket(ai->ai_family, ai->ai_socktype,
830                         ai->ai_protocol);
831                     if (listen_sock == -1) {
832                               /* kernel may not support ipv6 */
833                               verbose("socket: %.100s", strerror(errno));
834                               continue;
835                     }
836                     if (set_nonblock(listen_sock) == -1) {
837                               close(listen_sock);
838                               continue;
839                     }
840                     if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
841                               verbose("socket: CLOEXEC: %s", strerror(errno));
842                               close(listen_sock);
843                               continue;
844                     }
845                     /* Socket options */
846                     set_reuseaddr(listen_sock);
847                     if (la->rdomain != NULL &&
848                         set_rdomain(listen_sock, la->rdomain) == -1) {
849                               close(listen_sock);
850                               continue;
851                     }
852 
853                     debug("Bind to port %s on %s.", strport, ntop);
854 
855                     getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
856                                            &socksize, &socksizelen);
857                     debug("Server TCP RWIN socket size: %d", socksize);
858                     debug("HPN Buffer Size: %d", options.hpn_buffer_size);
859 
860                     /* Bind the socket to the desired port. */
861                     if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
862                               error("Bind to port %s on %s failed: %.200s.",
863                                   strport, ntop, strerror(errno));
864                               close(listen_sock);
865                               continue;
866                     }
867                     listen_socks[num_listen_socks] = listen_sock;
868                     num_listen_socks++;
869 
870                     /* Start listening on the port. */
871                     if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
872                               fatal("listen on [%s]:%s: %.100s",
873                                   ntop, strport, strerror(errno));
874                     logit("Server listening on %s port %s%s%s.",
875                         ntop, strport,
876                         la->rdomain == NULL ? "" : " rdomain ",
877                         la->rdomain == NULL ? "" : la->rdomain);
878           }
879 }
880 
881 static void
server_listen(void)882 server_listen(void)
883 {
884           u_int i;
885 
886           /* Initialise per-source limit tracking. */
887           srclimit_init(options.max_startups,
888               options.per_source_max_startups,
889               options.per_source_masklen_ipv4,
890               options.per_source_masklen_ipv6,
891               &options.per_source_penalty,
892               options.per_source_penalty_exempt);
893 
894           for (i = 0; i < options.num_listen_addrs; i++) {
895                     listen_on_addrs(&options.listen_addrs[i]);
896                     freeaddrinfo(options.listen_addrs[i].addrs);
897                     free(options.listen_addrs[i].rdomain);
898                     memset(&options.listen_addrs[i], 0,
899                         sizeof(options.listen_addrs[i]));
900           }
901           free(options.listen_addrs);
902           options.listen_addrs = NULL;
903           options.num_listen_addrs = 0;
904 
905           if (!num_listen_socks)
906                     fatal("Cannot bind any address.");
907 }
908 
909 /*
910  * The main TCP accept loop. Note that, for the non-debug case, returns
911  * from this function are in a forked subprocess.
912  */
913 static void
server_accept_loop(int * sock_in,int * sock_out,int * newsock,int * config_s,int log_stderr)914 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s,
915     int log_stderr)
916 {
917           struct pollfd *pfd = NULL;
918           int i, ret, npfd, r;
919           int oactive = -1, listening = 0, lameduck = 0;
920           int *startup_pollfd;
921           ssize_t len;
922           const u_char *ptr;
923           char c = 0;
924           struct sockaddr_storage from;
925           struct early_child *child;
926           struct sshbuf *buf;
927           socklen_t fromlen;
928           sigset_t nsigset, osigset;
929 
930           /* setup fd set for accept */
931           /* pipes connected to unauthenticated child sshd processes */
932           child_alloc();
933           startup_pollfd = xcalloc(options.max_startups, sizeof(int));
934 
935           /*
936            * Prepare signal mask that we use to block signals that might set
937            * received_sigterm/hup/chld/info, so that we are guaranteed
938            * to immediately wake up the ppoll if a signal is received after
939            * the flag is checked.
940            */
941           sigemptyset(&nsigset);
942           sigaddset(&nsigset, SIGHUP);
943           sigaddset(&nsigset, SIGCHLD);
944           sigaddset(&nsigset, SIGINFO);
945           sigaddset(&nsigset, SIGTERM);
946           sigaddset(&nsigset, SIGQUIT);
947 
948           /* sized for worst-case */
949           pfd = xcalloc(num_listen_socks + options.max_startups,
950               sizeof(struct pollfd));
951 
952           /*
953            * Stay listening for connections until the system crashes or
954            * the daemon is killed with a signal.
955            */
956           for (;;) {
957                     sigprocmask(SIG_BLOCK, &nsigset, &osigset);
958                     if (received_sigterm) {
959                               logit("Received signal %d; terminating.",
960                                   (int) received_sigterm);
961                               close_listen_socks();
962                               if (options.pid_file != NULL)
963                                         unlink(options.pid_file);
964                               exit(received_sigterm == SIGTERM ? 0 : 255);
965                     }
966                     if (received_sigchld) {
967                               child_reap_all_exited();
968                               received_sigchld = 0;
969                     }
970                     if (received_siginfo) {
971                               show_info();
972                               received_siginfo = 0;
973                     }
974                     if (oactive != children_active) {
975                               setproctitle("%s [listener] %d of %d-%d startups",
976                                   listener_proctitle, children_active,
977                                   options.max_startups_begin, options.max_startups);
978                               oactive = children_active;
979                     }
980                     if (received_sighup) {
981                               if (!lameduck) {
982                                         debug("Received SIGHUP; waiting for children");
983                                         close_listen_socks();
984                                         lameduck = 1;
985                               }
986                               if (listening <= 0) {
987                                         sigprocmask(SIG_SETMASK, &osigset, NULL);
988                                         sighup_restart();
989                               }
990                     }
991 
992                     for (i = 0; i < num_listen_socks; i++) {
993                               pfd[i].fd = listen_socks[i];
994                               pfd[i].events = POLLIN;
995                     }
996                     npfd = num_listen_socks;
997                     for (i = 0; i < options.max_startups; i++) {
998                               startup_pollfd[i] = -1;
999                               if (children[i].pipefd != -1) {
1000                                         pfd[npfd].fd = children[i].pipefd;
1001                                         pfd[npfd].events = POLLIN;
1002                                         if (children[i].config != NULL ||
1003                                             children[i].keys != NULL)
1004                                                   pfd[npfd].events |= POLLOUT;
1005                                         startup_pollfd[i] = npfd++;
1006                               }
1007                     }
1008 
1009                     /* Wait until a connection arrives or a child exits. */
1010                     ret = ppoll(pfd, npfd, NULL, &osigset);
1011                     if (ret == -1 && errno != EINTR) {
1012                               error("ppoll: %.100s", strerror(errno));
1013                               if (errno == EINVAL)
1014                                         cleanup_exit(1); /* can't recover */
1015                     }
1016                     sigprocmask(SIG_SETMASK, &osigset, NULL);
1017                     if (ret == -1)
1018                               continue;
1019 
1020                     for (i = 0; i < options.max_startups; i++) {
1021                               if (children[i].pipefd == -1 ||
1022                                   startup_pollfd[i] == -1 ||
1023                                   !(pfd[startup_pollfd[i]].revents & POLLOUT))
1024                                         continue;
1025                               if (children[i].config)
1026                                         buf = children[i].config;
1027                               else if (children[i].keys)
1028                                         buf = children[i].keys;
1029                               else {
1030                                         error_f("no buffer to send");
1031                                         continue;
1032                               }
1033                               ptr = sshbuf_ptr(buf);
1034                               len = sshbuf_len(buf);
1035                               ret = write(children[i].pipefd, ptr, len);
1036                               if (ret == -1 && (errno == EINTR || errno == EAGAIN))
1037                                         continue;
1038                               if (ret <= 0) {
1039                                         if (children[i].early)
1040                                                   listening--;
1041                                         srclimit_done(children[i].pipefd);
1042                                         child_close(&(children[i]), 0, 0);
1043                                         continue;
1044                               }
1045                               if (ret == len) {
1046                                         /* finished sending buffer */
1047                                         sshbuf_free(buf);
1048                                         if (children[i].config == buf) {
1049                                                   /* sent config, now send keys */
1050                                                   children[i].config = NULL;
1051                                                   children[i].keys = pack_hostkeys();
1052                                         } else if (children[i].keys == buf) {
1053                                                   /* sent both config and keys */
1054                                                   children[i].keys = NULL;
1055                                         } else {
1056                                                   fatal("config buf not set");
1057                                         }
1058 
1059                               } else {
1060                                         if ((r = sshbuf_consume(buf, ret)) != 0)
1061                                                   fatal_fr(r, "config buf inconsistent");
1062                               }
1063                     }
1064                     for (i = 0; i < options.max_startups; i++) {
1065                               if (children[i].pipefd == -1 ||
1066                                   startup_pollfd[i] == -1 ||
1067                                   !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
1068                                         continue;
1069                               switch (read(children[i].pipefd, &c, sizeof(c))) {
1070                               case -1:
1071                                         if (errno == EINTR || errno == EAGAIN)
1072                                                   continue;
1073                                         if (errno != EPIPE) {
1074                                                   error_f("startup pipe %d (fd=%d): "
1075                                                       "read %s", i, children[i].pipefd,
1076                                                       strerror(errno));
1077                                         }
1078                                         /* FALLTHROUGH */
1079                               case 0:
1080                                         /* child exited preauth */
1081                                         if (children[i].early)
1082                                                   listening--;
1083                                         srclimit_done(children[i].pipefd);
1084                                         child_close(&(children[i]), 0, 0);
1085                                         break;
1086                               case 1:
1087                                         if (children[i].config) {
1088                                                   error_f("startup pipe %d (fd=%d)"
1089                                                       " early read", i, children[i].pipefd);
1090                                                   if (children[i].early)
1091                                                             listening--;
1092                                                   if (children[i].pid > 0)
1093                                                             kill(children[i].pid, SIGTERM);
1094                                                   srclimit_done(children[i].pipefd);
1095                                                   child_close(&(children[i]), 0, 0);
1096                                                   break;
1097                                         }
1098                                         if (children[i].early && c == '\0') {
1099                                                   /* child has finished preliminaries */
1100                                                   listening--;
1101                                                   children[i].early = 0;
1102                                                   debug2_f("child %lu for %s received "
1103                                                       "config", (long)children[i].pid,
1104                                                       children[i].id);
1105                                         } else if (!children[i].early && c == '\001') {
1106                                                   /* child has completed auth */
1107                                                   debug2_f("child %lu for %s auth done",
1108                                                       (long)children[i].pid,
1109                                                       children[i].id);
1110                                                   child_close(&(children[i]), 1, 0);
1111                                         } else {
1112                                                   error_f("unexpected message 0x%02x "
1113                                                       "child %ld for %s in state %d",
1114                                                       (int)c, (long)children[i].pid,
1115                                                       children[i].id, children[i].early);
1116                                         }
1117                                         break;
1118                               }
1119                     }
1120                     for (i = 0; i < num_listen_socks; i++) {
1121                               if (!(pfd[i].revents & POLLIN))
1122                                         continue;
1123                               fromlen = sizeof(from);
1124                               *newsock = accept(listen_socks[i],
1125                                   (struct sockaddr *)&from, &fromlen);
1126                               if (*newsock == -1) {
1127                                         if (errno != EINTR && errno != EWOULDBLOCK &&
1128                                             errno != ECONNABORTED)
1129                                                   error("accept: %.100s",
1130                                                       strerror(errno));
1131                                         if (errno == EMFILE || errno == ENFILE)
1132                                                   usleep(100 * 1000);
1133                                         continue;
1134                               }
1135                               if (unset_nonblock(*newsock) == -1) {
1136                                         close(*newsock);
1137                                         continue;
1138                               }
1139                               if (socketpair(AF_UNIX,
1140                                   SOCK_STREAM, 0, config_s) == -1) {
1141                                         error("reexec socketpair: %s",
1142                                             strerror(errno));
1143                                         close(*newsock);
1144                                         continue;
1145                               }
1146                               if (drop_connection(*newsock,
1147                                   children_active, config_s[0])) {
1148                                         close(*newsock);
1149                                         close(config_s[0]);
1150                                         close(config_s[1]);
1151                                         continue;
1152                               }
1153 
1154                               /*
1155                                * Got connection.  Fork a child to handle it, unless
1156                                * we are in debugging mode.
1157                                */
1158                               if (debug_flag) {
1159                                         /*
1160                                          * In debugging mode.  Close the listening
1161                                          * socket, and start processing the
1162                                          * connection without forking.
1163                                          */
1164                                         debug("Server will not fork when running in debugging mode.");
1165                                         close_listen_socks();
1166                                         *sock_in = *newsock;
1167                                         *sock_out = *newsock;
1168                                         send_rexec_state(config_s[0]);
1169                                         close(config_s[0]);
1170                                         free(pfd);
1171                                         return;
1172                               }
1173 
1174                               /*
1175                                * Normal production daemon.  Fork, and have
1176                                * the child process the connection. The
1177                                * parent continues listening.
1178                                */
1179                               set_nonblock(config_s[0]);
1180                               listening++;
1181                               child = child_register(config_s[0], *newsock);
1182                               if ((child->pid = fork()) == 0) {
1183                                         /*
1184                                          * Child.  Close the listening and
1185                                          * max_startup sockets.  Start using
1186                                          * the accepted socket. Reinitialize
1187                                          * logging (since our pid has changed).
1188                                          * We return from this function to handle
1189                                          * the connection.
1190                                          */
1191                                         close_startup_pipes();
1192                                         close_listen_socks();
1193                                         *sock_in = *newsock;
1194                                         *sock_out = *newsock;
1195                                         log_init(__progname,
1196                                             options.log_level,
1197                                             options.log_facility,
1198                                             log_stderr);
1199                                         close(config_s[0]);
1200                                         free(pfd);
1201                                         return;
1202                               }
1203 
1204                               /* Parent.  Stay in the loop. */
1205                               if (child->pid == -1)
1206                                         error("fork: %.100s", strerror(errno));
1207                               else
1208                                         debug("Forked child %ld.", (long)child->pid);
1209 
1210                               close(config_s[1]);
1211                               close(*newsock);
1212                     }
1213           }
1214 }
1215 
1216 static void
accumulate_host_timing_secret(struct sshbuf * server_cfg,struct sshkey * key)1217 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1218     struct sshkey *key)
1219 {
1220           static struct ssh_digest_ctx *ctx;
1221           u_char *hash;
1222           size_t len;
1223           struct sshbuf *buf;
1224           int r;
1225 
1226           if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1227                     fatal_f("ssh_digest_start");
1228           if (key == NULL) { /* finalize */
1229                     /* add server config in case we are using agent for host keys */
1230                     if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1231                         sshbuf_len(server_cfg)) != 0)
1232                               fatal_f("ssh_digest_update");
1233                     len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1234                     hash = xmalloc(len);
1235                     if (ssh_digest_final(ctx, hash, len) != 0)
1236                               fatal_f("ssh_digest_final");
1237                     options.timing_secret = PEEK_U64(hash);
1238                     freezero(hash, len);
1239                     ssh_digest_free(ctx);
1240                     ctx = NULL;
1241                     return;
1242           }
1243           if ((buf = sshbuf_new()) == NULL)
1244                     fatal_f("could not allocate buffer");
1245           if ((r = sshkey_private_serialize(key, buf)) != 0)
1246                     fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
1247           if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1248                     fatal_f("ssh_digest_update");
1249           sshbuf_reset(buf);
1250           sshbuf_free(buf);
1251 }
1252 
1253 static char *
prepare_proctitle(int ac,char ** av)1254 prepare_proctitle(int ac, char **av)
1255 {
1256           char *ret = NULL;
1257           int i;
1258 
1259           for (i = 0; i < ac; i++)
1260                     xextendf(&ret, " ", "%s", av[i]);
1261           return ret;
1262 }
1263 
1264 __dead static void
print_config(struct connection_info * connection_info)1265 print_config(struct connection_info *connection_info)
1266 {
1267           connection_info->test = 1;
1268           parse_server_match_config(&options, &includes, connection_info);
1269           dump_config(&options);
1270           exit(0);
1271 }
1272 
1273 /*
1274  * Main program for the daemon.
1275  */
1276 int
main(int ac,char ** av)1277 main(int ac, char **av)
1278 {
1279           extern char *optarg;
1280           extern int optind;
1281           int log_stderr = 0, inetd_flag = 0, test_flag = 0, no_daemon_flag = 0;
1282           const char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1283           int r, opt, do_dump_cfg = 0, keytype, already_daemon, have_agent = 0;
1284           int sock_in = -1, sock_out = -1, newsock = -1, rexec_argc = 0;
1285           int devnull, config_s[2] = { -1 , -1 }, have_connection_info = 0;
1286           char *args, *fp, *line, *logfile = NULL, **rexec_argv = NULL;
1287           struct stat sb;
1288           u_int i, j;
1289           mode_t new_umask;
1290           struct sshkey *key;
1291           struct sshkey *pubkey;
1292           struct utsname utsname;
1293           struct connection_info connection_info;
1294           sigset_t sigmask;
1295 
1296           memset(&connection_info, 0, sizeof(connection_info));
1297 
1298           sigemptyset(&sigmask);
1299           sigprocmask(SIG_SETMASK, &sigmask, NULL);
1300 
1301           /* Save argv. */
1302           saved_argv = av;
1303           rexec_argc = ac;
1304 
1305           /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1306           sanitise_stdfd();
1307 
1308           /* Initialize configuration options to their default values. */
1309           initialize_server_options(&options);
1310 
1311           /* Parse command-line arguments. */
1312           args = argv_assemble(ac, av); /* logged later */
1313           while ((opt = getopt(ac, av,
1314               "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1315                     switch (opt) {
1316                     case '4':
1317                               options.address_family = AF_INET;
1318                               break;
1319                     case '6':
1320                               options.address_family = AF_INET6;
1321                               break;
1322                     case 'f':
1323                               config_file_name = optarg;
1324                               break;
1325                     case 'c':
1326                               servconf_add_hostcert("[command-line]", 0,
1327                                   &options, optarg);
1328                               break;
1329                     case 'd':
1330                               if (debug_flag == 0) {
1331                                         debug_flag = 1;
1332                                         options.log_level = SYSLOG_LEVEL_DEBUG1;
1333                               } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1334                                         options.log_level++;
1335                               break;
1336                     case 'D':
1337                               no_daemon_flag = 1;
1338                               break;
1339                     case 'G':
1340                               do_dump_cfg = 1;
1341                               break;
1342                     case 'E':
1343                               logfile = optarg;
1344                               /* FALLTHROUGH */
1345                     case 'e':
1346                               log_stderr = 1;
1347                               break;
1348                     case 'i':
1349                               inetd_flag = 1;
1350                               break;
1351                     case 'r':
1352                               logit("-r option is deprecated");
1353                               break;
1354                     case 'R':
1355                               fatal("-R not supported here");
1356                               break;
1357                     case 'Q':
1358                               /* ignored */
1359                               break;
1360                     case 'q':
1361                               options.log_level = SYSLOG_LEVEL_QUIET;
1362                               break;
1363                     case 'b':
1364                               /* protocol 1, ignored */
1365                               break;
1366                     case 'p':
1367                               options.ports_from_cmdline = 1;
1368                               if (options.num_ports >= MAX_PORTS) {
1369                                         fprintf(stderr, "too many ports.\n");
1370                                         exit(1);
1371                               }
1372                               options.ports[options.num_ports++] = a2port(optarg);
1373                               if (options.ports[options.num_ports-1] <= 0) {
1374                                         fprintf(stderr, "Bad port number.\n");
1375                                         exit(1);
1376                               }
1377                               break;
1378                     case 'g':
1379                               if ((options.login_grace_time = convtime(optarg)) == -1) {
1380                                         fprintf(stderr, "Invalid login grace time.\n");
1381                                         exit(1);
1382                               }
1383                               break;
1384                     case 'k':
1385                               /* protocol 1, ignored */
1386                               break;
1387                     case 'h':
1388                               servconf_add_hostkey("[command-line]", 0,
1389                                   &options, optarg, 1);
1390                               break;
1391                     case 't':
1392                               test_flag = 1;
1393                               break;
1394                     case 'T':
1395                               test_flag = 2;
1396                               break;
1397                     case 'C':
1398                               if (parse_server_match_testspec(&connection_info,
1399                                   optarg) == -1)
1400                                         exit(1);
1401                               have_connection_info = 1;
1402                               break;
1403                     case 'u':
1404                               utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1405                               if (utmp_len > HOST_NAME_MAX+1) {
1406                                         fprintf(stderr, "Invalid utmp length.\n");
1407                                         exit(1);
1408                               }
1409                               break;
1410                     case 'o':
1411                               line = xstrdup(optarg);
1412                               if (process_server_config_line(&options, line,
1413                                   "command-line", 0, NULL, NULL, &includes) != 0)
1414                                         exit(1);
1415                               free(line);
1416                               break;
1417                     case 'V':
1418                               fprintf(stderr, "%s, %s\n",
1419                                   SSH_VERSION, SSH_OPENSSL_VERSION);
1420                               exit(0);
1421                     default:
1422                               usage();
1423                               break;
1424                     }
1425           }
1426           if (!test_flag && !inetd_flag && !do_dump_cfg && !path_absolute(av[0]))
1427                     fatal("sshd requires execution with an absolute path");
1428 
1429           closefrom(STDERR_FILENO + 1);
1430 
1431           /* Reserve fds we'll need later for reexec things */
1432           if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
1433                     fatal("open %s: %s", _PATH_DEVNULL, strerror(errno));
1434           while (devnull < REEXEC_MIN_FREE_FD) {
1435                     if ((devnull = dup(devnull)) == -1)
1436                               fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno));
1437           }
1438 
1439 #ifdef WITH_OPENSSL
1440           OpenSSL_add_all_algorithms();
1441 #endif
1442 
1443           /* If requested, redirect the logs to the specified logfile. */
1444           if (logfile != NULL) {
1445                     char *cp, pid_s[32];
1446 
1447                     snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
1448                     cp = percent_expand(logfile,
1449                         "p", pid_s,
1450                         "P", "sshd",
1451                         (char *)NULL);
1452                     log_redirect_stderr_to(cp);
1453                     free(cp);
1454           }
1455 
1456           /*
1457            * Force logging to stderr until we have loaded the private host
1458            * key (unless started from inetd)
1459            */
1460           log_init(__progname,
1461               options.log_level == SYSLOG_LEVEL_NOT_SET ?
1462               SYSLOG_LEVEL_INFO : options.log_level,
1463               options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1464               SYSLOG_FACILITY_AUTH : options.log_facility,
1465               log_stderr || !inetd_flag || debug_flag);
1466 
1467           sensitive_data.have_ssh2_key = 0;
1468 
1469           /*
1470            * If we're not doing an extended test do not silently ignore connection
1471            * test params.
1472            */
1473           if (test_flag < 2 && have_connection_info)
1474                     fatal("Config test connection parameter (-C) provided without "
1475                         "test mode (-T)");
1476 
1477           debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1478           if (uname(&utsname) != 0) {
1479                     memset(&utsname, 0, sizeof(utsname));
1480                     strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname));
1481           }
1482           debug3("Running on %s %s %s %s", utsname.sysname, utsname.release,
1483               utsname.version, utsname.machine);
1484           debug3("Started with: %s", args);
1485           free(args);
1486 
1487           /* Fetch our configuration */
1488           if ((cfg = sshbuf_new()) == NULL)
1489                     fatal("sshbuf_new config failed");
1490           if (strcasecmp(config_file_name, "none") != 0)
1491                     load_server_config(config_file_name, cfg);
1492 
1493           parse_server_config(&options, config_file_name, cfg,
1494               &includes, NULL, 0);
1495 
1496           /* Fill in default values for those options not explicitly set. */
1497           fill_default_server_options(&options);
1498 
1499           /* Check that options are sensible */
1500           if (options.authorized_keys_command_user == NULL &&
1501               (options.authorized_keys_command != NULL &&
1502               strcasecmp(options.authorized_keys_command, "none") != 0))
1503                     fatal("AuthorizedKeysCommand set without "
1504                         "AuthorizedKeysCommandUser");
1505           if (options.authorized_principals_command_user == NULL &&
1506               (options.authorized_principals_command != NULL &&
1507               strcasecmp(options.authorized_principals_command, "none") != 0))
1508                     fatal("AuthorizedPrincipalsCommand set without "
1509                         "AuthorizedPrincipalsCommandUser");
1510 
1511           /*
1512            * Check whether there is any path through configured auth methods.
1513            * Unfortunately it is not possible to verify this generally before
1514            * daemonisation in the presence of Match blocks, but this catches
1515            * and warns for trivial misconfigurations that could break login.
1516            */
1517           if (options.num_auth_methods != 0) {
1518                     for (i = 0; i < options.num_auth_methods; i++) {
1519                               if (auth2_methods_valid(options.auth_methods[i],
1520                                   1) == 0)
1521                                         break;
1522                     }
1523                     if (i >= options.num_auth_methods)
1524                               fatal("AuthenticationMethods cannot be satisfied by "
1525                                   "enabled authentication methods");
1526           }
1527 
1528           /* Check that there are no remaining arguments. */
1529           if (optind < ac) {
1530                     fprintf(stderr, "Extra argument %s.\n", av[optind]);
1531                     exit(1);
1532           }
1533 
1534           if (do_dump_cfg)
1535                     print_config(&connection_info);
1536 
1537           /* load host keys */
1538           sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1539               sizeof(struct sshkey *));
1540           sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1541               sizeof(struct sshkey *));
1542 
1543           if (options.host_key_agent) {
1544                     if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1545                               setenv(SSH_AUTHSOCKET_ENV_NAME,
1546                                   options.host_key_agent, 1);
1547                     if ((r = ssh_get_authentication_socket(NULL)) == 0)
1548                               have_agent = 1;
1549                     else
1550                               error_r(r, "Could not connect to agent \"%s\"",
1551                                   options.host_key_agent);
1552           }
1553 
1554           for (i = 0; i < options.num_host_key_files; i++) {
1555                     int ll = options.host_key_file_userprovided[i] ?
1556                         SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1557 
1558                     if (options.host_key_files[i] == NULL)
1559                               continue;
1560                     if ((r = sshkey_load_private(options.host_key_files[i], "",
1561                         &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1562                               do_log2_r(r, ll, "Unable to load host key \"%s\"",
1563                                   options.host_key_files[i]);
1564                     if (sshkey_is_sk(key) &&
1565                         key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1566                               debug("host key %s requires user presence, ignoring",
1567                                   options.host_key_files[i]);
1568                               key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1569                     }
1570                     if (r == 0 && key != NULL &&
1571                         (r = sshkey_shield_private(key)) != 0) {
1572                               do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1573                                   options.host_key_files[i]);
1574                               sshkey_free(key);
1575                               key = NULL;
1576                     }
1577                     if ((r = sshkey_load_public(options.host_key_files[i],
1578                         &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1579                               do_log2_r(r, ll, "Unable to load host key \"%s\"",
1580                                   options.host_key_files[i]);
1581                     if (pubkey != NULL && key != NULL) {
1582                               if (!sshkey_equal(pubkey, key)) {
1583                                         error("Public key for %s does not match "
1584                                             "private key", options.host_key_files[i]);
1585                                         sshkey_free(pubkey);
1586                                         pubkey = NULL;
1587                               }
1588                     }
1589                     if (pubkey == NULL && key != NULL) {
1590                               if ((r = sshkey_from_private(key, &pubkey)) != 0)
1591                                         fatal_r(r, "Could not demote key: \"%s\"",
1592                                             options.host_key_files[i]);
1593                     }
1594                     if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1595                         options.required_rsa_size)) != 0) {
1596                               error_fr(r, "Host key %s", options.host_key_files[i]);
1597                               sshkey_free(pubkey);
1598                               sshkey_free(key);
1599                               continue;
1600                     }
1601                     sensitive_data.host_keys[i] = key;
1602                     sensitive_data.host_pubkeys[i] = pubkey;
1603 
1604                     if (key == NULL && pubkey != NULL && have_agent) {
1605                               debug("will rely on agent for hostkey %s",
1606                                   options.host_key_files[i]);
1607                               keytype = pubkey->type;
1608                     } else if (key != NULL) {
1609                               keytype = key->type;
1610                               accumulate_host_timing_secret(cfg, key);
1611                     } else {
1612                               do_log2(ll, "Unable to load host key: %s",
1613                                   options.host_key_files[i]);
1614                               sensitive_data.host_keys[i] = NULL;
1615                               sensitive_data.host_pubkeys[i] = NULL;
1616                               continue;
1617                     }
1618 
1619                     switch (keytype) {
1620                     case KEY_RSA:
1621                     case KEY_DSA:
1622                     case KEY_ECDSA:
1623                     case KEY_ED25519:
1624                     case KEY_ECDSA_SK:
1625                     case KEY_ED25519_SK:
1626                     case KEY_XMSS:
1627                               if (have_agent || key != NULL)
1628                                         sensitive_data.have_ssh2_key = 1;
1629                               break;
1630                     }
1631                     if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1632                         SSH_FP_DEFAULT)) == NULL)
1633                               fatal("sshkey_fingerprint failed");
1634                     debug("%s host key #%d: %s %s",
1635                         key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1636                     free(fp);
1637           }
1638           accumulate_host_timing_secret(cfg, NULL);
1639           if (!sensitive_data.have_ssh2_key) {
1640                     logit("sshd: no hostkeys available -- exiting.");
1641                     exit(1);
1642           }
1643 
1644           /*
1645            * Load certificates. They are stored in an array at identical
1646            * indices to the public keys that they relate to.
1647            */
1648           sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1649               sizeof(struct sshkey *));
1650           for (i = 0; i < options.num_host_key_files; i++)
1651                     sensitive_data.host_certificates[i] = NULL;
1652 
1653           for (i = 0; i < options.num_host_cert_files; i++) {
1654                     if (options.host_cert_files[i] == NULL)
1655                               continue;
1656                     if ((r = sshkey_load_public(options.host_cert_files[i],
1657                         &key, NULL)) != 0) {
1658                               error_r(r, "Could not load host certificate \"%s\"",
1659                                   options.host_cert_files[i]);
1660                               continue;
1661                     }
1662                     if (!sshkey_is_cert(key)) {
1663                               error("Certificate file is not a certificate: %s",
1664                                   options.host_cert_files[i]);
1665                               sshkey_free(key);
1666                               continue;
1667                     }
1668                     /* Find matching private key */
1669                     for (j = 0; j < options.num_host_key_files; j++) {
1670                               if (sshkey_equal_public(key,
1671                                   sensitive_data.host_pubkeys[j])) {
1672                                         sensitive_data.host_certificates[j] = key;
1673                                         break;
1674                               }
1675                     }
1676                     if (j >= options.num_host_key_files) {
1677                               error("No matching private key for certificate: %s",
1678                                   options.host_cert_files[i]);
1679                               sshkey_free(key);
1680                               continue;
1681                     }
1682                     sensitive_data.host_certificates[j] = key;
1683                     debug("host certificate: #%u type %d %s", j, key->type,
1684                         sshkey_type(key));
1685           }
1686 
1687           /* Ensure privsep directory is correctly configured. */
1688           if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1689                     fatal("Privilege separation user %s does not exist",
1690                         SSH_PRIVSEP_USER);
1691           endpwent();
1692           if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &sb) == -1) ||
1693               (S_ISDIR(sb.st_mode) == 0))
1694                     fatal("Missing privilege separation directory: %s",
1695                         _PATH_PRIVSEP_CHROOT_DIR);
1696           if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1697                     fatal("%s must be owned by root and not group or "
1698                         "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1699 
1700           if (test_flag > 1)
1701                     print_config(&connection_info);
1702 
1703           /* Configuration looks good, so exit if in test mode. */
1704           if (test_flag)
1705                     exit(0);
1706 
1707           /* Prepare arguments for sshd-session */
1708           if (rexec_argc < 0)
1709                     fatal("rexec_argc %d < 0", rexec_argc);
1710           rexec_argv = xcalloc(rexec_argc + 3, sizeof(char *));
1711           /* Point to the sshd-session binary instead of sshd */
1712           rexec_argv[0] = options.sshd_session_path;
1713           for (i = 1; i < (u_int)rexec_argc; i++) {
1714                     debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1715                     rexec_argv[i] = saved_argv[i];
1716           }
1717           rexec_argv[rexec_argc++] = __UNCONST("-R");
1718           rexec_argv[rexec_argc] = NULL;
1719           if (stat(rexec_argv[0], &sb) != 0 || !(sb.st_mode & (S_IXOTH|S_IXUSR)))
1720                     fatal("%s does not exist or is not executable", rexec_argv[0]);
1721           debug3("using %s for re-exec", rexec_argv[0]);
1722 
1723           /* Ensure that the privsep binary exists now too. */
1724           if (stat(options.sshd_auth_path, &sb) != 0 ||
1725               !(sb.st_mode & (S_IXOTH|S_IXUSR))) {
1726                     fatal("%s does not exist or is not executable",
1727                         options.sshd_auth_path);
1728           }
1729 
1730           listener_proctitle = prepare_proctitle(ac, av);
1731 
1732           /* Ensure that umask disallows at least group and world write */
1733           new_umask = umask(0077) | 0022;
1734           (void) umask(new_umask);
1735 
1736           /* Initialize the log (it is reinitialized below in case we forked). */
1737           if (debug_flag && !inetd_flag)
1738                     log_stderr = 1;
1739           log_init(__progname, options.log_level,
1740               options.log_facility, log_stderr);
1741           for (i = 0; i < options.num_log_verbose; i++)
1742                     log_verbose_add(options.log_verbose[i]);
1743 
1744           /*
1745            * If not in debugging mode, not started from inetd and not already
1746            * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1747            * terminal, and fork.  The original process exits.
1748            */
1749           already_daemon = daemonized();
1750           if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1751 
1752                     if (daemon(0, 0) == -1)
1753                               fatal("daemon() failed: %.200s", strerror(errno));
1754 
1755                     disconnect_controlling_tty();
1756           }
1757           /* Reinitialize the log (because of the fork above). */
1758           log_init(__progname, options.log_level, options.log_facility, log_stderr);
1759 
1760           /*
1761            * Chdir to the root directory so that the current disk can be
1762            * unmounted if desired.
1763            */
1764           if (chdir("/") == -1)
1765                     error("chdir(\"/\"): %s", strerror(errno));
1766 
1767           /* ignore SIGPIPE */
1768           ssh_signal(SIGPIPE, SIG_IGN);
1769 
1770           config = pack_config(cfg);
1771 
1772           /* Get a connection, either from inetd or a listening TCP socket */
1773           if (inetd_flag) {
1774                     /* Send configuration to ancestor sshd-session process */
1775                     if (socketpair(AF_UNIX, SOCK_STREAM, 0, config_s) == -1)
1776                               fatal("socketpair: %s", strerror(errno));
1777                     send_rexec_state(config_s[0]);
1778                     close(config_s[0]);
1779           } else {
1780                     server_listen();
1781 
1782                     ssh_signal(SIGHUP, sighup_handler);
1783                     ssh_signal(SIGCHLD, main_sigchld_handler);
1784                     ssh_signal(SIGTERM, sigterm_handler);
1785                     ssh_signal(SIGQUIT, sigterm_handler);
1786                     ssh_signal(SIGINFO, siginfo_handler);
1787 
1788                     /*
1789                      * Write out the pid file after the sigterm handler
1790                      * is setup and the listen sockets are bound
1791                      */
1792                     if (options.pid_file != NULL && !debug_flag) {
1793                               FILE *f = fopen(options.pid_file, "w");
1794 
1795                               if (f == NULL) {
1796                                         error("Couldn't create pid file \"%s\": %s",
1797                                             options.pid_file, strerror(errno));
1798                               } else {
1799                                         fprintf(f, "%ld\n", (long) getpid());
1800                                         fclose(f);
1801                               }
1802                     }
1803 
1804                     /* Accept a connection and return in a forked child */
1805                     server_accept_loop(&sock_in, &sock_out,
1806                         &newsock, config_s, log_stderr);
1807           }
1808 
1809           /* This is the child processing a new connection. */
1810           setproctitle("%s", "[accepted]");
1811 
1812           /*
1813            * Create a new session and process group since the 4.4BSD
1814            * setlogin() affects the entire process group.  We don't
1815            * want the child to be able to affect the parent.
1816            */
1817           if (!debug_flag && !inetd_flag && setsid() == -1)
1818                     error("setsid: %.100s", strerror(errno));
1819 
1820           debug("rexec start in %d out %d newsock %d config_s %d/%d",
1821               sock_in, sock_out, newsock, config_s[0], config_s[1]);
1822           if (!inetd_flag) {
1823                     if (dup2(newsock, STDIN_FILENO) == -1)
1824                               fatal("dup2 stdin: %s", strerror(errno));
1825                     if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
1826                               fatal("dup2 stdout: %s", strerror(errno));
1827                     if (newsock > STDOUT_FILENO)
1828                               close(newsock);
1829           }
1830           if (config_s[1] != REEXEC_CONFIG_PASS_FD) {
1831                     if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
1832                               fatal("dup2 config_s: %s", strerror(errno));
1833                     close(config_s[1]);
1834           }
1835           log_redirect_stderr_to(NULL);
1836           closefrom(REEXEC_MIN_FREE_FD);
1837 
1838           ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
1839           execv(rexec_argv[0], rexec_argv);
1840 
1841           fatal("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1842 }
1843 
1844 /* server specific fatal cleanup */
1845 void
cleanup_exit(int i)1846 cleanup_exit(int i)
1847 {
1848           _exit(i);
1849 }
1850