1 /* $OpenBSD: sshd.c,v 1.614 2024/12/07 10:12:19 djm Exp $ */
3 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
4 * Copyright (c) 2002 Niels Provos. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #ifdef HAVE_SYS_STAT_H
33 # include <sys/stat.h>
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
38 #include "openbsd-compat/sys-tree.h"
39 #include "openbsd-compat/sys-queue.h"
62 #include <openssl/evp.h>
63 #include <openssl/rand.h>
64 #include "openbsd-compat/openssl-compat.h"
67 #ifdef HAVE_SECUREWARE
68 #include <sys/security.h>
83 #include "pathnames.h"
96 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
97 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
98 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
99 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
101 extern char *__progname
;
103 /* Server configuration options. */
104 ServerOptions options
;
107 * Debug mode flag. This can be set on the command line. If debug
108 * mode is enabled, extra debugging output will be sent to the system
109 * log, the daemon will not go to background, and will exit after processing
110 * the first connection.
114 /* Saved arguments to main(). */
115 static char **saved_argv
;
116 static int saved_argc
;
119 * The sockets that the server is listening; this is used in the SIGHUP
122 #define MAX_LISTEN_SOCKS 16
123 static int listen_socks
[MAX_LISTEN_SOCKS
];
124 static int num_listen_socks
= 0;
127 * Any really sensitive data in the application is contained in this
128 * structure. The idea is that this structure could be locked into memory so
129 * that the pages do not get written into swap. However, there are some
130 * problems. The private key contains BIGNUMs, and we do not (in principle)
131 * have access to the internals of them, and locking just the structure is
132 * not very useful. Currently, memory locking is not implemented.
135 struct sshkey
**host_keys
; /* all private host keys */
136 struct sshkey
**host_pubkeys
; /* all public host keys */
137 struct sshkey
**host_certificates
; /* all public host certificates */
141 /* This is set to true when a signal is received. */
142 static volatile sig_atomic_t received_siginfo
= 0;
143 static volatile sig_atomic_t received_sigchld
= 0;
144 static volatile sig_atomic_t received_sighup
= 0;
145 static volatile sig_atomic_t received_sigterm
= 0;
147 /* record remote hostname or ip */
148 u_int utmp_len
= HOST_NAME_MAX
+1;
151 * The early_child/children array below is used for tracking children of the
152 * listening sshd process early in their lifespans, before they have
153 * completed authentication. This tracking is needed for four things:
155 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
157 * 2) Avoiding a race condition for SIGHUP processing, where child processes
158 * may have listen_socks open that could collide with main listener process
160 * 3) Ensuring that rexec'd sshd processes have received their initial state
161 * from the parent listen process before handling SIGHUP.
162 * 4) Tracking and logging unsuccessful exits from the preauth sshd monitor,
163 * including and especially those for LoginGraceTime timeouts.
165 * Child processes signal that they have completed closure of the listen_socks
166 * and (if applicable) received their rexec state by sending a char over their
169 * Child processes signal that authentication has completed by sending a
170 * second char over the socket before closing it, otherwise the listener will
171 * continue tracking the child (and using up a MaxStartups slot) until the
172 * preauth subprocess exits, whereupon the listener will log its exit status.
173 * preauth processes will exit with a status of EXIT_LOGIN_GRACE to indicate
174 * they did not authenticate before the LoginGraceTime alarm fired.
178 int early
; /* Indicates child closed listener */
179 char *id
; /* human readable connection identifier */
183 int status
, have_status
;
185 static struct early_child
*children
;
186 static int children_active
;
187 static int startup_pipe
= -1; /* in child */
189 /* sshd_config buffer */
192 /* Included files from the configuration file */
193 struct include_list includes
= TAILQ_HEAD_INITIALIZER(includes
);
195 /* message to be displayed after login */
196 struct sshbuf
*loginmsg
;
198 /* Unprivileged user */
199 struct passwd
*privsep_pw
= NULL
;
201 static char *listener_proctitle
;
204 * Close all listening sockets
207 close_listen_socks(void)
211 for (i
= 0; i
< num_listen_socks
; i
++)
212 close(listen_socks
[i
]);
213 num_listen_socks
= 0;
216 /* Allocate and initialise the children array */
222 children
= xcalloc(options
.max_startups
, sizeof(*children
));
223 for (i
= 0; i
< options
.max_startups
; i
++) {
224 children
[i
].pipefd
= -1;
225 children
[i
].pid
= -1;
229 /* Register a new connection in the children array; child pid comes later */
230 static struct early_child
*
231 child_register(int pipefd
, int sockfd
)
234 char *laddr
= NULL
, *raddr
= NULL
;
235 struct early_child
*child
= NULL
;
236 struct sockaddr_storage addr
;
237 socklen_t addrlen
= sizeof(addr
);
238 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
240 for (i
= 0; i
< options
.max_startups
; i
++) {
241 if (children
[i
].pipefd
!= -1 || children
[i
].pid
> 0)
243 child
= &(children
[i
]);
247 fatal_f("error: accepted connection when all %d child "
248 " slots full", options
.max_startups
);
250 child
->pipefd
= pipefd
;
252 /* record peer address, if available */
253 if (getpeername(sockfd
, sa
, &addrlen
) == 0 &&
254 addr_sa_to_xaddr(sa
, addrlen
, &child
->addr
) == 0)
255 child
->have_addr
= 1;
256 /* format peer address string for logs */
257 if ((lport
= get_local_port(sockfd
)) == 0 ||
258 (rport
= get_peer_port(sockfd
)) == 0) {
259 /* Not a TCP socket */
260 raddr
= get_peer_ipaddr(sockfd
);
261 xasprintf(&child
->id
, "connection from %s", raddr
);
263 laddr
= get_local_ipaddr(sockfd
);
264 raddr
= get_peer_ipaddr(sockfd
);
265 xasprintf(&child
->id
, "connection from %s to %s", raddr
, laddr
);
269 if (++children_active
> options
.max_startups
)
270 fatal_f("internal error: more children than max_startups");
276 * Finally free a child entry. Don't call this directly.
279 child_finish(struct early_child
*child
)
281 if (children_active
== 0)
282 fatal_f("internal error: children_active underflow");
283 if (child
->pipefd
!= -1)
284 close(child
->pipefd
);
286 memset(child
, '\0', sizeof(*child
));
293 * Close a child's pipe. This will not stop tracking the child immediately
294 * (it will still be tracked for waitpid()) unless force_final is set, or
295 * child has already exited.
298 child_close(struct early_child
*child
, int force_final
, int quiet
)
301 debug_f("enter%s", force_final
? " (forcing)" : "");
302 if (child
->pipefd
!= -1) {
303 close(child
->pipefd
);
306 if (child
->pid
== -1 || force_final
)
310 /* Record a child exit. Safe to call from signal handlers */
312 child_exit(pid_t pid
, int status
)
316 if (children
== NULL
|| pid
<= 0)
318 for (i
= 0; i
< options
.max_startups
; i
++) {
319 if (children
[i
].pid
== pid
) {
320 children
[i
].have_status
= 1;
321 children
[i
].status
= status
;
328 * Reap a child entry that has exited, as previously flagged
329 * using child_exit().
330 * Handles logging of exit condition and will finalise the child if its pipe
331 * had already been closed.
334 child_reap(struct early_child
*child
)
336 LogLevel level
= SYSLOG_LEVEL_DEBUG1
;
337 int was_crash
, penalty_type
= SRCLIMIT_PENALTY_NONE
;
339 /* Log exit information */
340 if (WIFSIGNALED(child
->status
)) {
342 * Increase logging for signals potentially associated
343 * with serious conditions.
345 if ((was_crash
= signal_is_crash(WTERMSIG(child
->status
))))
346 level
= SYSLOG_LEVEL_ERROR
;
347 do_log2(level
, "session process %ld for %s killed by "
348 "signal %d%s", (long)child
->pid
, child
->id
,
349 WTERMSIG(child
->status
), child
->early
? " (early)" : "");
351 penalty_type
= SRCLIMIT_PENALTY_CRASH
;
352 } else if (!WIFEXITED(child
->status
)) {
353 penalty_type
= SRCLIMIT_PENALTY_CRASH
;
354 error("session process %ld for %s terminated abnormally, "
355 "status=0x%x%s", (long)child
->pid
, child
->id
, child
->status
,
356 child
->early
? " (early)" : "");
358 /* Normal exit. We care about the status */
359 switch (WEXITSTATUS(child
->status
)) {
361 debug3_f("preauth child %ld for %s completed "
362 "normally %s", (long)child
->pid
, child
->id
,
363 child
->early
? " (early)" : "");
365 case EXIT_LOGIN_GRACE
:
366 penalty_type
= SRCLIMIT_PENALTY_GRACE_EXCEEDED
;
367 logit("Timeout before authentication for %s, "
368 "pid = %ld%s", child
->id
, (long)child
->pid
,
369 child
->early
? " (early)" : "");
371 case EXIT_CHILD_CRASH
:
372 penalty_type
= SRCLIMIT_PENALTY_CRASH
;
373 logit("Session process %ld unpriv child crash for %s%s",
374 (long)child
->pid
, child
->id
,
375 child
->early
? " (early)" : "");
377 case EXIT_AUTH_ATTEMPTED
:
378 penalty_type
= SRCLIMIT_PENALTY_AUTHFAIL
;
379 debug_f("preauth child %ld for %s exited "
380 "after unsuccessful auth attempt %s",
381 (long)child
->pid
, child
->id
,
382 child
->early
? " (early)" : "");
384 case EXIT_CONFIG_REFUSED
:
385 penalty_type
= SRCLIMIT_PENALTY_REFUSECONNECTION
;
386 debug_f("preauth child %ld for %s prohibited by"
387 "RefuseConnection %s",
388 (long)child
->pid
, child
->id
,
389 child
->early
? " (early)" : "");
392 penalty_type
= SRCLIMIT_PENALTY_NOAUTH
;
393 debug_f("preauth child %ld for %s exited "
394 "with status %d%s", (long)child
->pid
, child
->id
,
395 WEXITSTATUS(child
->status
),
396 child
->early
? " (early)" : "");
401 if (child
->have_addr
)
402 srclimit_penalise(&child
->addr
, penalty_type
);
405 child
->have_status
= 0;
406 if (child
->pipefd
== -1)
410 /* Reap all children that have exited; called after SIGCHLD */
412 child_reap_all_exited(void)
418 if (children
== NULL
)
422 if ((pid
= waitpid(-1, &status
, WNOHANG
)) == 0)
424 else if (pid
== -1) {
425 if (errno
== EINTR
|| errno
== EAGAIN
)
428 error_f("waitpid: %s", strerror(errno
));
431 child_exit(pid
, status
);
434 for (i
= 0; i
< options
.max_startups
; i
++) {
435 if (!children
[i
].have_status
)
437 child_reap(&(children
[i
]));
442 close_startup_pipes(void)
446 if (children
== NULL
)
448 for (i
= 0; i
< options
.max_startups
; i
++) {
449 if (children
[i
].pipefd
!= -1)
450 child_close(&(children
[i
]), 1, 1);
454 /* Called after SIGINFO */
460 /* XXX print listening sockets here too */
461 if (children
== NULL
)
463 logit("%d active startups", children_active
);
464 for (i
= 0; i
< options
.max_startups
; i
++) {
465 if (children
[i
].pipefd
== -1 && children
[i
].pid
<= 0)
467 logit("child %d: fd=%d pid=%ld %s%s", i
, children
[i
].pipefd
,
468 (long)children
[i
].pid
, children
[i
].id
,
469 children
[i
].early
? " (early)" : "");
471 srclimit_penalty_info();
475 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
476 * the effect is to reread the configuration file (and to regenerate
481 sighup_handler(int sig
)
487 * Called from the main program after receiving SIGHUP.
488 * Restarts the server.
493 logit("Received SIGHUP; restarting.");
494 if (options
.pid_file
!= NULL
)
495 unlink(options
.pid_file
);
496 platform_pre_restart();
497 close_listen_socks();
498 close_startup_pipes();
499 ssh_signal(SIGHUP
, SIG_IGN
); /* will be restored after exec */
500 execv(saved_argv
[0], saved_argv
);
501 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv
[0],
507 * Generic signal handler for terminating signals in the master daemon.
510 sigterm_handler(int sig
)
512 received_sigterm
= sig
;
517 siginfo_handler(int sig
)
519 received_siginfo
= 1;
524 main_sigchld_handler(int sig
)
526 received_sigchld
= 1;
530 * returns 1 if connection should be dropped, 0 otherwise.
531 * dropping starts at connection #max_startups_begin with a probability
532 * of (max_startups_rate/100). the probability increases linearly until
533 * all connections are dropped for startups > max_startups
536 should_drop_connection(int startups
)
540 if (startups
< options
.max_startups_begin
)
542 if (startups
>= options
.max_startups
)
544 if (options
.max_startups_rate
== 100)
547 p
= 100 - options
.max_startups_rate
;
548 p
*= startups
- options
.max_startups_begin
;
549 p
/= options
.max_startups
- options
.max_startups_begin
;
550 p
+= options
.max_startups_rate
;
551 r
= arc4random_uniform(100);
553 debug_f("p %d, r %d", p
, r
);
554 return (r
< p
) ? 1 : 0;
558 * Check whether connection should be accepted by MaxStartups or for penalty.
559 * Returns 0 if the connection is accepted. If the connection is refused,
560 * returns 1 and attempts to send notification to client.
561 * Logs when the MaxStartups condition is entered or exited, and periodically
562 * while in that state.
565 drop_connection(int sock
, int startups
, int notify_pipe
)
567 static struct log_ratelimit_ctx ratelimit_maxstartups
;
568 static struct log_ratelimit_ctx ratelimit_penalty
;
569 static int init_done
;
571 const char *reason
= NULL
, *subreason
= NULL
;
572 const char msg
[] = "Not allowed at this time\r\n";
573 struct log_ratelimit_ctx
*rl
= NULL
;
579 log_ratelimit_init(&ratelimit_maxstartups
, 4, 60, 20, 5*60);
580 log_ratelimit_init(&ratelimit_penalty
, 8, 60, 30, 2*60);
583 /* PerSourcePenalties */
584 if (!srclimit_penalty_check_allow(sock
, &subreason
)) {
585 reason
= "PerSourcePenalties";
586 rl
= &ratelimit_penalty
;
589 if (!should_drop_connection(startups
) &&
590 srclimit_check_allow(sock
, notify_pipe
) == 1)
592 reason
= "Maxstartups";
593 rl
= &ratelimit_maxstartups
;
596 laddr
= get_local_ipaddr(sock
);
597 raddr
= get_peer_ipaddr(sock
);
598 ratelimited
= log_ratelimit(rl
, time(NULL
), NULL
, &ndropped
);
599 do_log2(ratelimited
? SYSLOG_LEVEL_DEBUG3
: SYSLOG_LEVEL_INFO
,
600 "drop connection #%d from [%s]:%d on [%s]:%d %s",
602 raddr
, get_peer_port(sock
),
603 laddr
, get_local_port(sock
),
604 subreason
!= NULL
? subreason
: reason
);
608 logit("%s logging rate-limited: additional %u connections "
609 "dropped", reason
, ndropped
);
612 /* best-effort notification to client */
613 (void)write(sock
, msg
, sizeof(msg
) - 1);
620 fprintf(stderr
, "%s, %s\n", SSH_RELEASE
, SSH_OPENSSL_VERSION
);
622 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
623 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
624 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
629 static struct sshbuf
*
632 struct sshbuf
*keybuf
= NULL
, *hostkeys
= NULL
;
636 if ((keybuf
= sshbuf_new()) == NULL
||
637 (hostkeys
= sshbuf_new()) == NULL
)
638 fatal_f("sshbuf_new failed");
640 /* pack hostkeys into a string. Empty key slots get empty strings */
641 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
643 sshbuf_reset(keybuf
);
644 if (sensitive_data
.host_keys
[i
] != NULL
&&
645 (r
= sshkey_private_serialize(sensitive_data
.host_keys
[i
],
647 fatal_fr(r
, "serialize hostkey private");
648 if ((r
= sshbuf_put_stringb(hostkeys
, keybuf
)) != 0)
649 fatal_fr(r
, "compose hostkey private");
651 if (sensitive_data
.host_pubkeys
[i
] != NULL
) {
652 if ((r
= sshkey_puts(sensitive_data
.host_pubkeys
[i
],
654 fatal_fr(r
, "compose hostkey public");
656 if ((r
= sshbuf_put_string(hostkeys
, NULL
, 0)) != 0)
657 fatal_fr(r
, "compose hostkey empty public");
660 if (sensitive_data
.host_certificates
[i
] != NULL
) {
661 if ((r
= sshkey_puts(
662 sensitive_data
.host_certificates
[i
],
664 fatal_fr(r
, "compose host cert");
666 if ((r
= sshbuf_put_string(hostkeys
, NULL
, 0)) != 0)
667 fatal_fr(r
, "compose host cert empty");
676 send_rexec_state(int fd
, struct sshbuf
*conf
)
678 struct sshbuf
*m
= NULL
, *inc
= NULL
, *hostkeys
= NULL
;
679 struct include_item
*item
= NULL
;
682 debug3_f("entering fd = %d config len %zu", fd
,
685 if ((m
= sshbuf_new()) == NULL
||
686 (inc
= sshbuf_new()) == NULL
)
687 fatal_f("sshbuf_new failed");
689 /* pack includes into a string */
690 TAILQ_FOREACH(item
, &includes
, entry
) {
691 if ((r
= sshbuf_put_cstring(inc
, item
->selector
)) != 0 ||
692 (r
= sshbuf_put_cstring(inc
, item
->filename
)) != 0 ||
693 (r
= sshbuf_put_stringb(inc
, item
->contents
)) != 0)
694 fatal_fr(r
, "compose includes");
697 hostkeys
= pack_hostkeys();
700 * Protocol from reexec master to child:
701 * string configuration
702 * uint64 timing_secret
703 * string host_keys[] {
708 * string included_files[] {
714 if ((r
= sshbuf_put_stringb(m
, conf
)) != 0 ||
715 (r
= sshbuf_put_u64(m
, options
.timing_secret
)) != 0 ||
716 (r
= sshbuf_put_stringb(m
, hostkeys
)) != 0 ||
717 (r
= sshbuf_put_stringb(m
, inc
)) != 0)
718 fatal_fr(r
, "compose config");
720 /* We need to fit the entire message inside the socket send buffer */
721 sz
= ROUNDUP(sshbuf_len(m
) + 5, 16*1024);
722 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &sz
, sizeof sz
) == -1)
723 fatal_f("setsockopt SO_SNDBUF: %s", strerror(errno
));
725 if (ssh_msg_send(fd
, 0, m
) == -1)
726 error_f("ssh_msg_send failed");
730 sshbuf_free(hostkeys
);
736 * Listen for TCP connections
739 listen_on_addrs(struct listenaddr
*la
)
741 int ret
, listen_sock
;
743 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
745 for (ai
= la
->addrs
; ai
; ai
= ai
->ai_next
) {
746 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
748 if (num_listen_socks
>= MAX_LISTEN_SOCKS
)
749 fatal("Too many listen sockets. "
750 "Enlarge MAX_LISTEN_SOCKS");
751 if ((ret
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
752 ntop
, sizeof(ntop
), strport
, sizeof(strport
),
753 NI_NUMERICHOST
|NI_NUMERICSERV
)) != 0) {
754 error("getnameinfo failed: %.100s",
755 ssh_gai_strerror(ret
));
758 /* Create socket for listening. */
759 listen_sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
761 if (listen_sock
== -1) {
762 /* kernel may not support ipv6 */
763 verbose("socket: %.100s", strerror(errno
));
766 if (set_nonblock(listen_sock
) == -1) {
770 if (fcntl(listen_sock
, F_SETFD
, FD_CLOEXEC
) == -1) {
771 verbose("socket: CLOEXEC: %s", strerror(errno
));
776 set_reuseaddr(listen_sock
);
777 if (la
->rdomain
!= NULL
&&
778 set_rdomain(listen_sock
, la
->rdomain
) == -1) {
783 /* Only communicate in IPv6 over AF_INET6 sockets. */
784 if (ai
->ai_family
== AF_INET6
)
785 sock_set_v6only(listen_sock
);
787 debug("Bind to port %s on %s.", strport
, ntop
);
789 /* Bind the socket to the desired port. */
790 if (bind(listen_sock
, ai
->ai_addr
, ai
->ai_addrlen
) == -1) {
791 error("Bind to port %s on %s failed: %.200s.",
792 strport
, ntop
, strerror(errno
));
796 listen_socks
[num_listen_socks
] = listen_sock
;
799 /* Start listening on the port. */
800 if (listen(listen_sock
, SSH_LISTEN_BACKLOG
) == -1)
801 fatal("listen on [%s]:%s: %.100s",
802 ntop
, strport
, strerror(errno
));
803 logit("Server listening on %s port %s%s%s.",
805 la
->rdomain
== NULL
? "" : " rdomain ",
806 la
->rdomain
== NULL
? "" : la
->rdomain
);
815 /* Initialise per-source limit tracking. */
816 srclimit_init(options
.max_startups
,
817 options
.per_source_max_startups
,
818 options
.per_source_masklen_ipv4
,
819 options
.per_source_masklen_ipv6
,
820 &options
.per_source_penalty
,
821 options
.per_source_penalty_exempt
);
823 for (i
= 0; i
< options
.num_listen_addrs
; i
++) {
824 listen_on_addrs(&options
.listen_addrs
[i
]);
825 freeaddrinfo(options
.listen_addrs
[i
].addrs
);
826 free(options
.listen_addrs
[i
].rdomain
);
827 memset(&options
.listen_addrs
[i
], 0,
828 sizeof(options
.listen_addrs
[i
]));
830 free(options
.listen_addrs
);
831 options
.listen_addrs
= NULL
;
832 options
.num_listen_addrs
= 0;
834 if (!num_listen_socks
)
835 fatal("Cannot bind any address.");
839 * The main TCP accept loop. Note that, for the non-debug case, returns
840 * from this function are in a forked subprocess.
843 server_accept_loop(int *sock_in
, int *sock_out
, int *newsock
, int *config_s
,
846 struct pollfd
*pfd
= NULL
;
848 int oactive
= -1, listening
= 0, lameduck
= 0;
849 int startup_p
[2] = { -1 , -1 }, *startup_pollfd
;
851 struct sockaddr_storage from
;
852 struct early_child
*child
;
855 sigset_t nsigset
, osigset
;
857 /* pipes connected to unauthenticated child sshd processes */
859 startup_pollfd
= xcalloc(options
.max_startups
, sizeof(int));
862 * Prepare signal mask that we use to block signals that might set
863 * received_sigterm/hup/chld/info, so that we are guaranteed
864 * to immediately wake up the ppoll if a signal is received after
865 * the flag is checked.
867 sigemptyset(&nsigset
);
868 sigaddset(&nsigset
, SIGHUP
);
869 sigaddset(&nsigset
, SIGCHLD
);
871 sigaddset(&nsigset
, SIGINFO
);
873 sigaddset(&nsigset
, SIGTERM
);
874 sigaddset(&nsigset
, SIGQUIT
);
876 /* sized for worst-case */
877 pfd
= xcalloc(num_listen_socks
+ options
.max_startups
,
878 sizeof(struct pollfd
));
881 * Stay listening for connections until the system crashes or
882 * the daemon is killed with a signal.
885 sigprocmask(SIG_BLOCK
, &nsigset
, &osigset
);
886 if (received_sigterm
) {
887 logit("Received signal %d; terminating.",
888 (int) received_sigterm
);
889 close_listen_socks();
890 if (options
.pid_file
!= NULL
)
891 unlink(options
.pid_file
);
892 exit(received_sigterm
== SIGTERM
? 0 : 255);
894 if (received_sigchld
) {
895 child_reap_all_exited();
896 received_sigchld
= 0;
898 if (received_siginfo
) {
900 received_siginfo
= 0;
902 if (oactive
!= children_active
) {
903 setproctitle("%s [listener] %d of %d-%d startups",
904 listener_proctitle
, children_active
,
905 options
.max_startups_begin
, options
.max_startups
);
906 oactive
= children_active
;
908 if (received_sighup
) {
910 debug("Received SIGHUP; waiting for children");
911 close_listen_socks();
914 if (listening
<= 0) {
915 sigprocmask(SIG_SETMASK
, &osigset
, NULL
);
920 for (i
= 0; i
< num_listen_socks
; i
++) {
921 pfd
[i
].fd
= listen_socks
[i
];
922 pfd
[i
].events
= POLLIN
;
924 npfd
= num_listen_socks
;
925 for (i
= 0; i
< options
.max_startups
; i
++) {
926 startup_pollfd
[i
] = -1;
927 if (children
[i
].pipefd
!= -1) {
928 pfd
[npfd
].fd
= children
[i
].pipefd
;
929 pfd
[npfd
].events
= POLLIN
;
930 startup_pollfd
[i
] = npfd
++;
934 /* Wait until a connection arrives or a child exits. */
935 ret
= ppoll(pfd
, npfd
, NULL
, &osigset
);
936 if (ret
== -1 && errno
!= EINTR
) {
937 error("ppoll: %.100s", strerror(errno
));
939 cleanup_exit(1); /* can't recover */
941 sigprocmask(SIG_SETMASK
, &osigset
, NULL
);
945 for (i
= 0; i
< options
.max_startups
; i
++) {
946 if (children
[i
].pipefd
== -1 ||
947 startup_pollfd
[i
] == -1 ||
948 !(pfd
[startup_pollfd
[i
]].revents
& (POLLIN
|POLLHUP
)))
950 switch (read(children
[i
].pipefd
, &c
, sizeof(c
))) {
952 if (errno
== EINTR
|| errno
== EAGAIN
)
954 if (errno
!= EPIPE
) {
955 error_f("startup pipe %d (fd=%d): "
956 "read %s", i
, children
[i
].pipefd
,
961 /* child exited preauth */
962 if (children
[i
].early
)
964 srclimit_done(children
[i
].pipefd
);
965 child_close(&(children
[i
]), 0, 0);
968 if (children
[i
].early
&& c
== '\0') {
969 /* child has finished preliminaries */
971 children
[i
].early
= 0;
972 debug2_f("child %lu for %s received "
973 "config", (long)children
[i
].pid
,
975 } else if (!children
[i
].early
&& c
== '\001') {
976 /* child has completed auth */
977 debug2_f("child %lu for %s auth done",
978 (long)children
[i
].pid
,
980 child_close(&(children
[i
]), 1, 0);
982 error_f("unexpected message 0x%02x "
983 "child %ld for %s in state %d",
984 (int)c
, (long)children
[i
].pid
,
985 children
[i
].id
, children
[i
].early
);
990 for (i
= 0; i
< num_listen_socks
; i
++) {
991 if (!(pfd
[i
].revents
& POLLIN
))
993 fromlen
= sizeof(from
);
994 *newsock
= accept(listen_socks
[i
],
995 (struct sockaddr
*)&from
, &fromlen
);
996 if (*newsock
== -1) {
997 if (errno
!= EINTR
&& errno
!= EWOULDBLOCK
&&
998 errno
!= ECONNABORTED
&& errno
!= EAGAIN
)
999 error("accept: %.100s",
1001 if (errno
== EMFILE
|| errno
== ENFILE
)
1005 if (unset_nonblock(*newsock
) == -1) {
1009 if (pipe(startup_p
) == -1) {
1010 error_f("pipe(startup_p): %s", strerror(errno
));
1014 if (drop_connection(*newsock
,
1015 children_active
, startup_p
[0])) {
1017 close(startup_p
[0]);
1018 close(startup_p
[1]);
1022 if (socketpair(AF_UNIX
,
1023 SOCK_STREAM
, 0, config_s
) == -1) {
1024 error("reexec socketpair: %s",
1027 close(startup_p
[0]);
1028 close(startup_p
[1]);
1033 * Got connection. Fork a child to handle it, unless
1034 * we are in debugging mode.
1038 * In debugging mode. Close the listening
1039 * socket, and start processing the
1040 * connection without forking.
1042 debug("Server will not fork when running in debugging mode.");
1043 close_listen_socks();
1044 *sock_in
= *newsock
;
1045 *sock_out
= *newsock
;
1046 close(startup_p
[0]);
1047 close(startup_p
[1]);
1049 send_rexec_state(config_s
[0], cfg
);
1056 * Normal production daemon. Fork, and have
1057 * the child process the connection. The
1058 * parent continues listening.
1060 platform_pre_fork();
1062 child
= child_register(startup_p
[0], *newsock
);
1063 if ((child
->pid
= fork()) == 0) {
1065 * Child. Close the listening and
1066 * max_startup sockets. Start using
1067 * the accepted socket. Reinitialize
1068 * logging (since our pid has changed).
1069 * We return from this function to handle
1072 platform_post_fork_child();
1073 startup_pipe
= startup_p
[1];
1074 close_startup_pipes();
1075 close_listen_socks();
1076 *sock_in
= *newsock
;
1077 *sock_out
= *newsock
;
1078 log_init(__progname
,
1080 options
.log_facility
,
1087 /* Parent. Stay in the loop. */
1088 platform_post_fork_parent(child
->pid
);
1089 if (child
->pid
== -1)
1090 error("fork: %.100s", strerror(errno
));
1092 debug("Forked child %ld.", (long)child
->pid
);
1094 close(startup_p
[1]);
1097 send_rexec_state(config_s
[0], cfg
);
1102 * Ensure that our random state differs
1103 * from that of the child
1106 arc4random_buf(rnd
, sizeof(rnd
));
1108 RAND_seed(rnd
, sizeof(rnd
));
1109 if ((RAND_bytes((u_char
*)rnd
, 1)) != 1)
1110 fatal("%s: RAND_bytes failed", __func__
);
1112 explicit_bzero(rnd
, sizeof(rnd
));
1118 accumulate_host_timing_secret(struct sshbuf
*server_cfg
,
1121 static struct ssh_digest_ctx
*ctx
;
1127 if (ctx
== NULL
&& (ctx
= ssh_digest_start(SSH_DIGEST_SHA512
)) == NULL
)
1128 fatal_f("ssh_digest_start");
1129 if (key
== NULL
) { /* finalize */
1130 /* add server config in case we are using agent for host keys */
1131 if (ssh_digest_update(ctx
, sshbuf_ptr(server_cfg
),
1132 sshbuf_len(server_cfg
)) != 0)
1133 fatal_f("ssh_digest_update");
1134 len
= ssh_digest_bytes(SSH_DIGEST_SHA512
);
1135 hash
= xmalloc(len
);
1136 if (ssh_digest_final(ctx
, hash
, len
) != 0)
1137 fatal_f("ssh_digest_final");
1138 options
.timing_secret
= PEEK_U64(hash
);
1139 freezero(hash
, len
);
1140 ssh_digest_free(ctx
);
1144 if ((buf
= sshbuf_new()) == NULL
)
1145 fatal_f("could not allocate buffer");
1146 if ((r
= sshkey_private_serialize(key
, buf
)) != 0)
1147 fatal_fr(r
, "encode %s key", sshkey_ssh_name(key
));
1148 if (ssh_digest_update(ctx
, sshbuf_ptr(buf
), sshbuf_len(buf
)) != 0)
1149 fatal_f("ssh_digest_update");
1155 prepare_proctitle(int ac
, char **av
)
1160 for (i
= 0; i
< ac
; i
++)
1161 xextendf(&ret
, " ", "%s", av
[i
]);
1166 print_config(struct connection_info
*connection_info
)
1168 connection_info
->test
= 1;
1169 parse_server_match_config(&options
, &includes
, connection_info
);
1170 dump_config(&options
);
1175 * Main program for the daemon.
1178 main(int ac
, char **av
)
1180 extern char *optarg
;
1182 int log_stderr
= 0, inetd_flag
= 0, test_flag
= 0, no_daemon_flag
= 0;
1183 char *config_file_name
= _PATH_SERVER_CONFIG_FILE
;
1184 int r
, opt
, do_dump_cfg
= 0, keytype
, already_daemon
, have_agent
= 0;
1185 int sock_in
= -1, sock_out
= -1, newsock
= -1, rexec_argc
= 0;
1186 int devnull
, config_s
[2] = { -1 , -1 }, have_connection_info
= 0;
1187 int need_chroot
= 1;
1188 char *fp
, *line
, *logfile
= NULL
, **rexec_argv
= NULL
;
1193 struct sshkey
*pubkey
;
1194 struct connection_info connection_info
;
1197 memset(&connection_info
, 0, sizeof(connection_info
));
1198 #ifdef HAVE_SECUREWARE
1199 (void)set_auth_parameters(ac
, av
);
1201 __progname
= ssh_get_progname(av
[0]);
1203 sigemptyset(&sigmask
);
1204 sigprocmask(SIG_SETMASK
, &sigmask
, NULL
);
1206 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1209 saved_argv
= xcalloc(ac
+ 1, sizeof(*saved_argv
));
1210 for (i
= 0; (int)i
< ac
; i
++)
1211 saved_argv
[i
] = xstrdup(av
[i
]);
1212 saved_argv
[i
] = NULL
;
1214 #ifndef HAVE_SETPROCTITLE
1215 /* Prepare for later setproctitle emulation */
1216 compat_init_setproctitle(ac
, av
);
1220 if (geteuid() == 0 && setgroups(0, NULL
) == -1)
1221 debug("setgroups(): %.200s", strerror(errno
));
1223 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1226 /* Initialize configuration options to their default values. */
1227 initialize_server_options(&options
);
1229 /* Parse command-line arguments. */
1230 while ((opt
= getopt(ac
, av
,
1231 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1234 options
.address_family
= AF_INET
;
1237 options
.address_family
= AF_INET6
;
1240 config_file_name
= optarg
;
1243 servconf_add_hostcert("[command-line]", 0,
1247 if (debug_flag
== 0) {
1249 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
1250 } else if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
1251 options
.log_level
++;
1269 logit("-r option is deprecated");
1272 fatal("-R not supported here");
1278 options
.log_level
= SYSLOG_LEVEL_QUIET
;
1281 /* protocol 1, ignored */
1284 options
.ports_from_cmdline
= 1;
1285 if (options
.num_ports
>= MAX_PORTS
) {
1286 fprintf(stderr
, "too many ports.\n");
1289 options
.ports
[options
.num_ports
++] = a2port(optarg
);
1290 if (options
.ports
[options
.num_ports
-1] <= 0) {
1291 fprintf(stderr
, "Bad port number.\n");
1296 if ((options
.login_grace_time
= convtime(optarg
)) == -1) {
1297 fprintf(stderr
, "Invalid login grace time.\n");
1302 /* protocol 1, ignored */
1305 servconf_add_hostkey("[command-line]", 0,
1306 &options
, optarg
, 1);
1315 if (parse_server_match_testspec(&connection_info
,
1318 have_connection_info
= 1;
1321 utmp_len
= (u_int
)strtonum(optarg
, 0, HOST_NAME_MAX
+1+1, NULL
);
1322 if (utmp_len
> HOST_NAME_MAX
+1) {
1323 fprintf(stderr
, "Invalid utmp length.\n");
1328 line
= xstrdup(optarg
);
1329 if (process_server_config_line(&options
, line
,
1330 "command-line", 0, NULL
, NULL
, &includes
) != 0)
1335 fprintf(stderr
, "%s, %s\n",
1336 SSH_RELEASE
, SSH_OPENSSL_VERSION
);
1343 if (!test_flag
&& !inetd_flag
&& !do_dump_cfg
&& !path_absolute(av
[0]))
1344 fatal("sshd requires execution with an absolute path");
1346 closefrom(STDERR_FILENO
+ 1);
1348 /* Reserve fds we'll need later for reexec things */
1349 if ((devnull
= open(_PATH_DEVNULL
, O_RDWR
)) == -1)
1350 fatal("open %s: %s", _PATH_DEVNULL
, strerror(errno
));
1351 while (devnull
< REEXEC_MIN_FREE_FD
) {
1352 if ((devnull
= dup(devnull
)) == -1)
1353 fatal("dup %s: %s", _PATH_DEVNULL
, strerror(errno
));
1358 /* If requested, redirect the logs to the specified logfile. */
1359 if (logfile
!= NULL
) {
1360 char *cp
, pid_s
[32];
1362 snprintf(pid_s
, sizeof(pid_s
), "%ld", (unsigned long)getpid());
1363 cp
= percent_expand(logfile
,
1367 log_redirect_stderr_to(cp
);
1372 * Force logging to stderr until we have loaded the private host
1373 * key (unless started from inetd)
1375 log_init(__progname
,
1376 options
.log_level
== SYSLOG_LEVEL_NOT_SET
?
1377 SYSLOG_LEVEL_INFO
: options
.log_level
,
1378 options
.log_facility
== SYSLOG_FACILITY_NOT_SET
?
1379 SYSLOG_FACILITY_AUTH
: options
.log_facility
,
1380 log_stderr
|| !inetd_flag
|| debug_flag
);
1383 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1384 * root's environment
1386 if (getenv("KRB5CCNAME") != NULL
)
1387 (void) unsetenv("KRB5CCNAME");
1389 sensitive_data
.have_ssh2_key
= 0;
1392 * If we're not doing an extended test do not silently ignore connection
1395 if (test_flag
< 2 && have_connection_info
)
1396 fatal("Config test connection parameter (-C) provided without "
1399 /* Fetch our configuration */
1400 if ((cfg
= sshbuf_new()) == NULL
)
1401 fatal("sshbuf_new config failed");
1402 if (strcasecmp(config_file_name
, "none") != 0)
1403 load_server_config(config_file_name
, cfg
);
1405 parse_server_config(&options
, config_file_name
, cfg
,
1406 &includes
, NULL
, 0);
1408 /* Fill in default values for those options not explicitly set. */
1409 fill_default_server_options(&options
);
1411 /* Check that options are sensible */
1412 if (options
.authorized_keys_command_user
== NULL
&&
1413 (options
.authorized_keys_command
!= NULL
&&
1414 strcasecmp(options
.authorized_keys_command
, "none") != 0))
1415 fatal("AuthorizedKeysCommand set without "
1416 "AuthorizedKeysCommandUser");
1417 if (options
.authorized_principals_command_user
== NULL
&&
1418 (options
.authorized_principals_command
!= NULL
&&
1419 strcasecmp(options
.authorized_principals_command
, "none") != 0))
1420 fatal("AuthorizedPrincipalsCommand set without "
1421 "AuthorizedPrincipalsCommandUser");
1424 * Check whether there is any path through configured auth methods.
1425 * Unfortunately it is not possible to verify this generally before
1426 * daemonisation in the presence of Match blocks, but this catches
1427 * and warns for trivial misconfigurations that could break login.
1429 if (options
.num_auth_methods
!= 0) {
1430 for (i
= 0; i
< options
.num_auth_methods
; i
++) {
1431 if (auth2_methods_valid(options
.auth_methods
[i
],
1435 if (i
>= options
.num_auth_methods
)
1436 fatal("AuthenticationMethods cannot be satisfied by "
1437 "enabled authentication methods");
1440 /* Check that there are no remaining arguments. */
1442 fprintf(stderr
, "Extra argument %s.\n", av
[optind
]);
1446 debug("sshd version %s, %s", SSH_VERSION
, SSH_OPENSSL_VERSION
);
1449 print_config(&connection_info
);
1451 /* load host keys */
1452 sensitive_data
.host_keys
= xcalloc(options
.num_host_key_files
,
1453 sizeof(struct sshkey
*));
1454 sensitive_data
.host_pubkeys
= xcalloc(options
.num_host_key_files
,
1455 sizeof(struct sshkey
*));
1457 if (options
.host_key_agent
) {
1458 if (strcmp(options
.host_key_agent
, SSH_AUTHSOCKET_ENV_NAME
))
1459 setenv(SSH_AUTHSOCKET_ENV_NAME
,
1460 options
.host_key_agent
, 1);
1461 if ((r
= ssh_get_authentication_socket(NULL
)) == 0)
1464 error_r(r
, "Could not connect to agent \"%s\"",
1465 options
.host_key_agent
);
1468 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
1469 int ll
= options
.host_key_file_userprovided
[i
] ?
1470 SYSLOG_LEVEL_ERROR
: SYSLOG_LEVEL_DEBUG1
;
1472 if (options
.host_key_files
[i
] == NULL
)
1474 if ((r
= sshkey_load_private(options
.host_key_files
[i
], "",
1475 &key
, NULL
)) != 0 && r
!= SSH_ERR_SYSTEM_ERROR
)
1476 do_log2_r(r
, ll
, "Unable to load host key \"%s\"",
1477 options
.host_key_files
[i
]);
1478 if (sshkey_is_sk(key
) &&
1479 key
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
) {
1480 debug("host key %s requires user presence, ignoring",
1481 options
.host_key_files
[i
]);
1482 key
->sk_flags
&= ~SSH_SK_USER_PRESENCE_REQD
;
1484 if (r
== 0 && key
!= NULL
&&
1485 (r
= sshkey_shield_private(key
)) != 0) {
1486 do_log2_r(r
, ll
, "Unable to shield host key \"%s\"",
1487 options
.host_key_files
[i
]);
1491 if ((r
= sshkey_load_public(options
.host_key_files
[i
],
1492 &pubkey
, NULL
)) != 0 && r
!= SSH_ERR_SYSTEM_ERROR
)
1493 do_log2_r(r
, ll
, "Unable to load host key \"%s\"",
1494 options
.host_key_files
[i
]);
1495 if (pubkey
!= NULL
&& key
!= NULL
) {
1496 if (!sshkey_equal(pubkey
, key
)) {
1497 error("Public key for %s does not match "
1498 "private key", options
.host_key_files
[i
]);
1499 sshkey_free(pubkey
);
1503 if (pubkey
== NULL
&& key
!= NULL
) {
1504 if ((r
= sshkey_from_private(key
, &pubkey
)) != 0)
1505 fatal_r(r
, "Could not demote key: \"%s\"",
1506 options
.host_key_files
[i
]);
1508 if (pubkey
!= NULL
&& (r
= sshkey_check_rsa_length(pubkey
,
1509 options
.required_rsa_size
)) != 0) {
1510 error_fr(r
, "Host key %s", options
.host_key_files
[i
]);
1511 sshkey_free(pubkey
);
1515 sensitive_data
.host_keys
[i
] = key
;
1516 sensitive_data
.host_pubkeys
[i
] = pubkey
;
1518 if (key
== NULL
&& pubkey
!= NULL
&& have_agent
) {
1519 debug("will rely on agent for hostkey %s",
1520 options
.host_key_files
[i
]);
1521 keytype
= pubkey
->type
;
1522 } else if (key
!= NULL
) {
1523 keytype
= key
->type
;
1524 accumulate_host_timing_secret(cfg
, key
);
1526 do_log2(ll
, "Unable to load host key: %s",
1527 options
.host_key_files
[i
]);
1528 sensitive_data
.host_keys
[i
] = NULL
;
1529 sensitive_data
.host_pubkeys
[i
] = NULL
;
1539 case KEY_ED25519_SK
:
1541 if (have_agent
|| key
!= NULL
)
1542 sensitive_data
.have_ssh2_key
= 1;
1545 if ((fp
= sshkey_fingerprint(pubkey
, options
.fingerprint_hash
,
1546 SSH_FP_DEFAULT
)) == NULL
)
1547 fatal("sshkey_fingerprint failed");
1548 debug("%s host key #%d: %s %s",
1549 key
? "private" : "agent", i
, sshkey_ssh_name(pubkey
), fp
);
1552 accumulate_host_timing_secret(cfg
, NULL
);
1553 if (!sensitive_data
.have_ssh2_key
) {
1554 logit("sshd: no hostkeys available -- exiting.");
1559 * Load certificates. They are stored in an array at identical
1560 * indices to the public keys that they relate to.
1562 sensitive_data
.host_certificates
= xcalloc(options
.num_host_key_files
,
1563 sizeof(struct sshkey
*));
1564 for (i
= 0; i
< options
.num_host_key_files
; i
++)
1565 sensitive_data
.host_certificates
[i
] = NULL
;
1567 for (i
= 0; i
< options
.num_host_cert_files
; i
++) {
1568 if (options
.host_cert_files
[i
] == NULL
)
1570 if ((r
= sshkey_load_public(options
.host_cert_files
[i
],
1571 &key
, NULL
)) != 0) {
1572 error_r(r
, "Could not load host certificate \"%s\"",
1573 options
.host_cert_files
[i
]);
1576 if (!sshkey_is_cert(key
)) {
1577 error("Certificate file is not a certificate: %s",
1578 options
.host_cert_files
[i
]);
1582 /* Find matching private key */
1583 for (j
= 0; j
< options
.num_host_key_files
; j
++) {
1584 if (sshkey_equal_public(key
,
1585 sensitive_data
.host_pubkeys
[j
])) {
1586 sensitive_data
.host_certificates
[j
] = key
;
1590 if (j
>= options
.num_host_key_files
) {
1591 error("No matching private key for certificate: %s",
1592 options
.host_cert_files
[i
]);
1596 sensitive_data
.host_certificates
[j
] = key
;
1597 debug("host certificate: #%u type %d %s", j
, key
->type
,
1601 /* Ensure privsep directory is correctly configured. */
1602 need_chroot
= ((getuid() == 0 || geteuid() == 0) ||
1603 options
.kerberos_authentication
);
1604 if ((getpwnam(SSH_PRIVSEP_USER
)) == NULL
&& need_chroot
) {
1605 fatal("Privilege separation user %s does not exist",
1611 if ((stat(_PATH_PRIVSEP_CHROOT_DIR
, &sb
) == -1) ||
1612 (S_ISDIR(sb
.st_mode
) == 0))
1613 fatal("Missing privilege separation directory: %s",
1614 _PATH_PRIVSEP_CHROOT_DIR
);
1616 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR
) &&
1617 (sb
.st_uid
!= getuid () ||
1618 (sb
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0))
1620 if (sb
.st_uid
!= 0 || (sb
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0)
1622 fatal("%s must be owned by root and not group or "
1623 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR
);
1627 print_config(&connection_info
);
1629 /* Configuration looks good, so exit if in test mode. */
1634 * Clear out any supplemental groups we may have inherited. This
1635 * prevents inadvertent creation of files with bad modes (in the
1636 * portable version at least, it's certainly possible for PAM
1637 * to create a file, and we can't control the code in every
1638 * module which might be used).
1640 if (setgroups(0, NULL
) < 0)
1641 debug("setgroups() failed: %.200s", strerror(errno
));
1643 /* Prepare arguments for sshd-session */
1645 fatal("rexec_argc %d < 0", rexec_argc
);
1646 rexec_argv
= xcalloc(rexec_argc
+ 3, sizeof(char *));
1647 /* Point to the sshd-session binary instead of sshd */
1648 rexec_argv
[0] = options
.sshd_session_path
;
1649 for (i
= 1; i
< (u_int
)rexec_argc
; i
++) {
1650 debug("rexec_argv[%d]='%s'", i
, saved_argv
[i
]);
1651 rexec_argv
[i
] = saved_argv
[i
];
1653 rexec_argv
[rexec_argc
++] = "-R";
1654 rexec_argv
[rexec_argc
] = NULL
;
1655 if (stat(rexec_argv
[0], &sb
) != 0 || !(sb
.st_mode
& (S_IXOTH
|S_IXUSR
)))
1656 fatal("%s does not exist or is not executable", rexec_argv
[0]);
1657 debug3("using %s for re-exec", rexec_argv
[0]);
1659 /* Ensure that the privsep binary exists now too. */
1660 if (stat(options
.sshd_auth_path
, &sb
) != 0 ||
1661 !(sb
.st_mode
& (S_IXOTH
|S_IXUSR
))) {
1662 fatal("%s does not exist or is not executable",
1663 options
.sshd_auth_path
);
1666 listener_proctitle
= prepare_proctitle(ac
, av
);
1668 /* Ensure that umask disallows at least group and world write */
1669 new_umask
= umask(0077) | 0022;
1670 (void) umask(new_umask
);
1672 /* Initialize the log (it is reinitialized below in case we forked). */
1673 if (debug_flag
&& !inetd_flag
)
1675 log_init(__progname
, options
.log_level
,
1676 options
.log_facility
, log_stderr
);
1677 for (i
= 0; i
< options
.num_log_verbose
; i
++)
1678 log_verbose_add(options
.log_verbose
[i
]);
1681 * If not in debugging mode, not started from inetd and not already
1682 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1683 * terminal, and fork. The original process exits.
1685 already_daemon
= daemonized();
1686 if (!(debug_flag
|| inetd_flag
|| no_daemon_flag
|| already_daemon
)) {
1688 if (daemon(0, 0) == -1)
1689 fatal("daemon() failed: %.200s", strerror(errno
));
1691 disconnect_controlling_tty();
1693 /* Reinitialize the log (because of the fork above). */
1694 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1697 * Chdir to the root directory so that the current disk can be
1698 * unmounted if desired.
1700 if (chdir("/") == -1)
1701 error("chdir(\"/\"): %s", strerror(errno
));
1703 /* ignore SIGPIPE */
1704 ssh_signal(SIGPIPE
, SIG_IGN
);
1706 /* Get a connection, either from inetd or a listening TCP socket */
1708 /* Send configuration to ancestor sshd-session process */
1709 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, config_s
) == -1)
1710 fatal("socketpair: %s", strerror(errno
));
1711 send_rexec_state(config_s
[0], cfg
);
1714 platform_pre_listen();
1717 ssh_signal(SIGHUP
, sighup_handler
);
1718 ssh_signal(SIGCHLD
, main_sigchld_handler
);
1719 ssh_signal(SIGTERM
, sigterm_handler
);
1720 ssh_signal(SIGQUIT
, sigterm_handler
);
1722 ssh_signal(SIGINFO
, siginfo_handler
);
1725 platform_post_listen();
1728 * Write out the pid file after the sigterm handler
1729 * is setup and the listen sockets are bound
1731 if (options
.pid_file
!= NULL
&& !debug_flag
) {
1732 FILE *f
= fopen(options
.pid_file
, "w");
1735 error("Couldn't create pid file \"%s\": %s",
1736 options
.pid_file
, strerror(errno
));
1738 fprintf(f
, "%ld\n", (long) getpid());
1743 /* Accept a connection and return in a forked child */
1744 server_accept_loop(&sock_in
, &sock_out
,
1745 &newsock
, config_s
, log_stderr
);
1748 /* This is the child processing a new connection. */
1749 setproctitle("%s", "[accepted]");
1752 * Create a new session and process group since the 4.4BSD
1753 * setlogin() affects the entire process group. We don't
1754 * want the child to be able to affect the parent.
1756 if (!debug_flag
&& !inetd_flag
&& setsid() == -1)
1757 error("setsid: %.100s", strerror(errno
));
1759 debug("rexec start in %d out %d newsock %d pipe %d sock %d/%d",
1760 sock_in
, sock_out
, newsock
, startup_pipe
, config_s
[0], config_s
[1]);
1762 if (dup2(newsock
, STDIN_FILENO
) == -1)
1763 fatal("dup2 stdin: %s", strerror(errno
));
1764 if (dup2(STDIN_FILENO
, STDOUT_FILENO
) == -1)
1765 fatal("dup2 stdout: %s", strerror(errno
));
1766 if (newsock
> STDOUT_FILENO
)
1769 if (config_s
[1] != REEXEC_CONFIG_PASS_FD
) {
1770 if (dup2(config_s
[1], REEXEC_CONFIG_PASS_FD
) == -1)
1771 fatal("dup2 config_s: %s", strerror(errno
));
1774 if (startup_pipe
== -1)
1775 close(REEXEC_STARTUP_PIPE_FD
);
1776 else if (startup_pipe
!= REEXEC_STARTUP_PIPE_FD
) {
1777 if (dup2(startup_pipe
, REEXEC_STARTUP_PIPE_FD
) == -1)
1778 fatal("dup2 startup_p: %s", strerror(errno
));
1779 close(startup_pipe
);
1781 log_redirect_stderr_to(NULL
);
1782 closefrom(REEXEC_MIN_FREE_FD
);
1784 ssh_signal(SIGHUP
, SIG_IGN
); /* avoid reset to SIG_DFL */
1785 execv(rexec_argv
[0], rexec_argv
);
1787 fatal("rexec of %s failed: %s", rexec_argv
[0], strerror(errno
));
1790 /* server specific fatal cleanup */