1 /* $OpenBSD: sshd-session.c,v 1.9 2024/09/09 02:39:57 djm Exp $ */
4 * Privilege Separation:
6 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
7 * Copyright (c) 2002 Niels Provos. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
41 #include "openbsd-compat/sys-tree.h"
42 #include "openbsd-compat/sys-queue.h"
62 #include <openssl/bn.h>
63 #include <openssl/evp.h>
64 #include <openssl/rand.h>
65 #include "openbsd-compat/openssl-compat.h"
68 #ifdef HAVE_SECUREWARE
69 #include <sys/security.h>
90 #include "pathnames.h"
104 #include "monitor_wrap.h"
105 #include "auth-options.h"
109 #include "srclimit.h"
113 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
114 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
115 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
116 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
119 #define PRIVSEP_MONITOR_FD (STDERR_FILENO + 1)
120 #define PRIVSEP_LOG_FD (STDERR_FILENO + 2)
121 #define PRIVSEP_MIN_FREE_FD (STDERR_FILENO + 3)
123 extern char *__progname
;
125 /* Server configuration options. */
126 ServerOptions options
;
128 /* Name of the server configuration file. */
129 char *config_file_name
= _PATH_SERVER_CONFIG_FILE
;
132 * Debug mode flag. This can be set on the command line. If debug
133 * mode is enabled, extra debugging output will be sent to the system
134 * log, the daemon will not go to background, and will exit after processing
135 * the first connection.
139 /* Flag indicating that the daemon is being started from inetd. */
140 static int inetd_flag
= 0;
142 /* debug goes to stderr unless inetd_flag is set */
143 static int log_stderr
= 0;
145 /* Saved arguments to main(). */
146 static char **saved_argv
;
147 static int saved_argc
;
149 /* Daemon's agent connection */
151 static int have_agent
= 0;
154 * Any really sensitive data in the application is contained in this
155 * structure. The idea is that this structure could be locked into memory so
156 * that the pages do not get written into swap. However, there are some
157 * problems. The private key contains BIGNUMs, and we do not (in principle)
158 * have access to the internals of them, and locking just the structure is
159 * not very useful. Currently, memory locking is not implemented.
163 struct sshkey
**host_keys
; /* all private host keys */
164 struct sshkey
**host_pubkeys
; /* all public host keys */
165 struct sshkey
**host_certificates
; /* all public host certificates */
168 /* record remote hostname or ip */
169 u_int utmp_len
= HOST_NAME_MAX
+1;
171 static int startup_pipe
= -1; /* in child */
173 /* variables used for privilege separation */
174 struct monitor
*pmonitor
= NULL
;
175 int privsep_is_preauth
= 1;
176 static int privsep_chroot
= 1;
178 /* Unprivileged user */
179 struct passwd
*privsep_pw
= NULL
;
181 /* global connection state and authentication contexts */
182 Authctxt
*the_authctxt
= NULL
;
183 struct ssh
*the_active_state
;
185 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
186 struct sshauthopt
*auth_opts
= NULL
;
188 /* sshd_config buffer */
191 /* Included files from the configuration file */
192 struct include_list includes
= TAILQ_HEAD_INITIALIZER(includes
);
194 /* message to be displayed after login */
195 struct sshbuf
*loginmsg
;
197 /* Prototypes for various functions defined later in this file. */
198 void destroy_sensitive_data(void);
199 void demote_sensitive_data(void);
201 /* XXX reduce to stub once postauth split */
206 * m_pid is only set in the privileged part, and
207 * points to the unprivileged child.
209 return (pmonitor
&& pmonitor
->m_pid
> 0);
213 * Signal handler for the alarm after the login grace period has expired.
214 * As usual, this may only take signal-safe actions, even though it is
218 grace_alarm_handler(int sig
)
221 * Try to kill any processes that we have spawned, E.g. authorized
222 * keys command helpers or privsep children.
224 if (getpgid(0) == getpid()) {
227 /* mask all other signals while in handler */
228 memset(&sa
, 0, sizeof(sa
));
229 sa
.sa_handler
= SIG_IGN
;
230 sigfillset(&sa
.sa_mask
);
231 #if defined(SA_RESTART)
232 sa
.sa_flags
= SA_RESTART
;
234 (void)sigaction(SIGTERM
, &sa
, NULL
);
237 _exit(EXIT_LOGIN_GRACE
);
240 /* Destroy the host and server keys. They will no longer be needed. */
242 destroy_sensitive_data(void)
246 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
247 if (sensitive_data
.host_keys
[i
]) {
248 sshkey_free(sensitive_data
.host_keys
[i
]);
249 sensitive_data
.host_keys
[i
] = NULL
;
251 if (sensitive_data
.host_certificates
[i
]) {
252 sshkey_free(sensitive_data
.host_certificates
[i
]);
253 sensitive_data
.host_certificates
[i
] = NULL
;
258 /* Demote private to public keys for network child */
260 demote_sensitive_data(void)
266 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
267 if (sensitive_data
.host_keys
[i
]) {
268 if ((r
= sshkey_from_private(
269 sensitive_data
.host_keys
[i
], &tmp
)) != 0)
270 fatal_r(r
, "could not demote host %s key",
271 sshkey_type(sensitive_data
.host_keys
[i
]));
272 sshkey_free(sensitive_data
.host_keys
[i
]);
273 sensitive_data
.host_keys
[i
] = tmp
;
275 /* Certs do not need demotion */
287 arc4random_stir(); /* noop on recent arc4random() implementations */
288 arc4random_buf(rnd
, sizeof(rnd
)); /* let arc4random notice PID change */
291 RAND_seed(rnd
, sizeof(rnd
));
292 /* give libcrypto a chance to notice the PID change */
293 if ((RAND_bytes((u_char
*)rnd
, 1)) != 1)
294 fatal("%s: RAND_bytes failed", __func__
);
297 explicit_bzero(rnd
, sizeof(rnd
));
303 struct sshbuf
*keybuf
= NULL
, *hostkeys
= NULL
;
307 if ((hostkeys
= sshbuf_new()) == NULL
)
308 fatal_f("sshbuf_new failed");
310 /* pack hostkeys into a string. Empty key slots get empty strings */
311 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
313 if (sensitive_data
.host_pubkeys
[i
] != NULL
) {
314 if ((r
= sshkey_puts(sensitive_data
.host_pubkeys
[i
],
316 fatal_fr(r
, "compose hostkey public");
318 if ((r
= sshbuf_put_string(hostkeys
, NULL
, 0)) != 0)
319 fatal_fr(r
, "compose hostkey empty public");
322 if (sensitive_data
.host_certificates
[i
] != NULL
) {
323 if ((r
= sshkey_puts(
324 sensitive_data
.host_certificates
[i
],
326 fatal_fr(r
, "compose host cert");
328 if ((r
= sshbuf_put_string(hostkeys
, NULL
, 0)) != 0)
329 fatal_fr(r
, "compose host cert empty");
338 privsep_preauth(struct ssh
*ssh
)
343 /* Set up unprivileged child process to deal with network data */
344 pmonitor
= monitor_init();
345 /* Store a pointer to the kex for later rekeying */
346 pmonitor
->m_pkex
= &ssh
->kex
;
348 if ((pid
= fork()) == -1)
349 fatal("fork of unprivileged child failed");
351 debug2("Network child is on pid %ld", (long)pid
);
353 pmonitor
->m_pid
= pid
;
355 r
= ssh_get_authentication_socket(&auth_sock
);
357 error_r(r
, "Could not get agent socket");
361 monitor_child_preauth(ssh
, pmonitor
);
363 /* Wait for the child's exit status */
364 while (waitpid(pid
, &status
, 0) == -1) {
367 pmonitor
->m_pid
= -1;
368 fatal_f("waitpid: %s", strerror(errno
));
370 privsep_is_preauth
= 0;
371 pmonitor
->m_pid
= -1;
372 if (WIFEXITED(status
)) {
373 if (WEXITSTATUS(status
) != 0)
374 fatal_f("preauth child exited with status %d",
375 WEXITSTATUS(status
));
376 } else if (WIFSIGNALED(status
))
377 fatal_f("preauth child terminated by signal %d",
382 close(pmonitor
->m_sendfd
);
383 close(pmonitor
->m_log_recvfd
);
386 * Arrange unpriv-preauth child process fds:
387 * 0, 1 network socket
390 * 4 monitor message socket
391 * 5 monitor logging socket
393 * We know that the monitor sockets will have fds > 4 because
394 * of the reserved fds in main()
397 if (ssh_packet_get_connection_in(ssh
) != STDIN_FILENO
&&
398 dup2(ssh_packet_get_connection_in(ssh
), STDIN_FILENO
) == -1)
399 fatal("dup2 stdin failed: %s", strerror(errno
));
400 if (ssh_packet_get_connection_out(ssh
) != STDOUT_FILENO
&&
401 dup2(ssh_packet_get_connection_out(ssh
),
402 STDOUT_FILENO
) == -1)
403 fatal("dup2 stdout failed: %s", strerror(errno
));
404 /* leave stderr as-is */
405 log_redirect_stderr_to(NULL
); /* dup can clobber log fd */
406 if (pmonitor
->m_recvfd
!= PRIVSEP_MONITOR_FD
&&
407 dup2(pmonitor
->m_recvfd
, PRIVSEP_MONITOR_FD
) == -1)
408 fatal("dup2 monitor fd: %s", strerror(errno
));
409 if (pmonitor
->m_log_sendfd
!= PRIVSEP_LOG_FD
&&
410 dup2(pmonitor
->m_log_sendfd
, PRIVSEP_LOG_FD
) == -1)
411 fatal("dup2 log fd: %s", strerror(errno
));
412 closefrom(PRIVSEP_MIN_FREE_FD
);
414 saved_argv
[0] = options
.sshd_auth_path
;
415 execv(options
.sshd_auth_path
, saved_argv
);
417 fatal_f("exec of %s failed: %s",
418 options
.sshd_auth_path
, strerror(errno
));
423 privsep_postauth(struct ssh
*ssh
, Authctxt
*authctxt
)
425 int skip_privdrop
= 0;
428 * Hack for systems that don't support FD passing: retain privileges
429 * in the post-auth privsep process so it can allocate PTYs directly.
430 * This is basically equivalent to what we did <= 9.7, which was to
431 * disable post-auth privsep entriely.
432 * Cygwin doesn't need to drop privs here although it doesn't support
433 * fd passing, as AFAIK PTY allocation on this platform doesn't require
434 * special privileges to begin with.
436 #if defined(DISABLE_FD_PASSING) && !defined(HAVE_CYGWIN)
440 /* New socket pair */
441 monitor_reinit(pmonitor
);
443 pmonitor
->m_pid
= fork();
444 if (pmonitor
->m_pid
== -1)
445 fatal("fork of unprivileged child failed");
446 else if (pmonitor
->m_pid
!= 0) {
447 verbose("User child is on pid %ld", (long)pmonitor
->m_pid
);
448 sshbuf_reset(loginmsg
);
449 monitor_clear_keystate(ssh
, pmonitor
);
450 monitor_child_postauth(ssh
, pmonitor
);
458 close(pmonitor
->m_sendfd
);
459 pmonitor
->m_sendfd
= -1;
461 /* Demote the private keys to public keys. */
462 demote_sensitive_data();
466 /* Drop privileges */
468 do_setusercontext(authctxt
->pw
);
470 /* It is safe now to apply the key state */
471 monitor_apply_keystate(ssh
, pmonitor
);
474 * Tell the packet layer that authentication was successful, since
475 * this information is not part of the key state.
477 ssh_packet_set_authenticated(ssh
);
480 static struct sshkey
*
481 get_hostkey_by_type(int type
, int nid
, int need_private
, struct ssh
*ssh
)
486 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
491 case KEY_ED25519_CERT
:
492 case KEY_ECDSA_SK_CERT
:
493 case KEY_ED25519_SK_CERT
:
495 key
= sensitive_data
.host_certificates
[i
];
498 key
= sensitive_data
.host_keys
[i
];
499 if (key
== NULL
&& !need_private
)
500 key
= sensitive_data
.host_pubkeys
[i
];
503 if (key
== NULL
|| key
->type
!= type
)
509 case KEY_ECDSA_SK_CERT
:
510 if (key
->ecdsa_nid
!= nid
)
514 return need_private
?
515 sensitive_data
.host_keys
[i
] : key
;
522 get_hostkey_public_by_type(int type
, int nid
, struct ssh
*ssh
)
524 return get_hostkey_by_type(type
, nid
, 0, ssh
);
528 get_hostkey_private_by_type(int type
, int nid
, struct ssh
*ssh
)
530 return get_hostkey_by_type(type
, nid
, 1, ssh
);
534 get_hostkey_by_index(int ind
)
536 if (ind
< 0 || (u_int
)ind
>= options
.num_host_key_files
)
538 return (sensitive_data
.host_keys
[ind
]);
542 get_hostkey_public_by_index(int ind
, struct ssh
*ssh
)
544 if (ind
< 0 || (u_int
)ind
>= options
.num_host_key_files
)
546 return (sensitive_data
.host_pubkeys
[ind
]);
550 get_hostkey_index(struct sshkey
*key
, int compare
, struct ssh
*ssh
)
554 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
555 if (sshkey_is_cert(key
)) {
556 if (key
== sensitive_data
.host_certificates
[i
] ||
557 (compare
&& sensitive_data
.host_certificates
[i
] &&
559 sensitive_data
.host_certificates
[i
])))
562 if (key
== sensitive_data
.host_keys
[i
] ||
563 (compare
&& sensitive_data
.host_keys
[i
] &&
564 sshkey_equal(key
, sensitive_data
.host_keys
[i
])))
566 if (key
== sensitive_data
.host_pubkeys
[i
] ||
567 (compare
&& sensitive_data
.host_pubkeys
[i
] &&
568 sshkey_equal(key
, sensitive_data
.host_pubkeys
[i
])))
575 /* Inform the client of all hostkeys */
577 notify_hostkeys(struct ssh
*ssh
)
585 /* Some clients cannot cope with the hostkeys message, skip those. */
586 if (ssh
->compat
& SSH_BUG_HOSTKEYS
)
589 if ((buf
= sshbuf_new()) == NULL
)
590 fatal_f("sshbuf_new");
591 for (i
= nkeys
= 0; i
< options
.num_host_key_files
; i
++) {
592 key
= get_hostkey_public_by_index(i
, ssh
);
593 if (key
== NULL
|| key
->type
== KEY_UNSPEC
||
596 fp
= sshkey_fingerprint(key
, options
.fingerprint_hash
,
598 debug3_f("key %d: %s %s", i
, sshkey_ssh_name(key
), fp
);
602 * Start building the request when we find the
605 if ((r
= sshpkt_start(ssh
, SSH2_MSG_GLOBAL_REQUEST
)) != 0 ||
606 (r
= sshpkt_put_cstring(ssh
, "hostkeys-00@openssh.com")) != 0 ||
607 (r
= sshpkt_put_u8(ssh
, 0)) != 0) /* want reply */
608 sshpkt_fatal(ssh
, r
, "%s: start request", __func__
);
610 /* Append the key to the request */
612 if ((r
= sshkey_putb(key
, buf
)) != 0)
613 fatal_fr(r
, "couldn't put hostkey %d", i
);
614 if ((r
= sshpkt_put_stringb(ssh
, buf
)) != 0)
615 sshpkt_fatal(ssh
, r
, "%s: append key", __func__
);
618 debug3_f("sent %u hostkeys", nkeys
);
620 fatal_f("no hostkeys");
621 if ((r
= sshpkt_send(ssh
)) != 0)
622 sshpkt_fatal(ssh
, r
, "%s: send", __func__
);
629 fprintf(stderr
, "%s, %s\n", SSH_RELEASE
, SSH_OPENSSL_VERSION
);
631 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
632 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
633 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
639 parse_hostkeys(struct sshbuf
*hostkeys
)
648 while (sshbuf_len(hostkeys
) != 0) {
650 fatal_f("too many hostkeys");
651 sensitive_data
.host_keys
= xrecallocarray(
652 sensitive_data
.host_keys
, num_keys
, num_keys
+ 1,
653 sizeof(*sensitive_data
.host_pubkeys
));
654 sensitive_data
.host_pubkeys
= xrecallocarray(
655 sensitive_data
.host_pubkeys
, num_keys
, num_keys
+ 1,
656 sizeof(*sensitive_data
.host_pubkeys
));
657 sensitive_data
.host_certificates
= xrecallocarray(
658 sensitive_data
.host_certificates
, num_keys
, num_keys
+ 1,
659 sizeof(*sensitive_data
.host_certificates
));
662 if ((r
= sshbuf_froms(hostkeys
, &kbuf
)) != 0)
663 fatal_fr(r
, "extract privkey");
664 if (sshbuf_len(kbuf
) != 0 &&
665 (r
= sshkey_private_deserialize(kbuf
, &k
)) != 0)
666 fatal_fr(r
, "parse pubkey");
667 sensitive_data
.host_keys
[num_keys
] = k
;
670 debug2_f("privkey %u: %s", num_keys
, sshkey_ssh_name(k
));
673 if ((r
= sshbuf_get_string_direct(hostkeys
, &cp
, &len
)) != 0)
674 fatal_fr(r
, "extract pubkey");
675 if (len
!= 0 && (r
= sshkey_from_blob(cp
, len
, &k
)) != 0)
676 fatal_fr(r
, "parse pubkey");
677 sensitive_data
.host_pubkeys
[num_keys
] = k
;
679 debug2_f("pubkey %u: %s", num_keys
, sshkey_ssh_name(k
));
682 if ((r
= sshbuf_get_string_direct(hostkeys
, &cp
, &len
)) != 0)
683 fatal_fr(r
, "extract pubkey");
684 if (len
!= 0 && (r
= sshkey_from_blob(cp
, len
, &k
)) != 0)
685 fatal_fr(r
, "parse pubkey");
686 sensitive_data
.host_certificates
[num_keys
] = k
;
688 debug2_f("cert %u: %s", num_keys
, sshkey_ssh_name(k
));
691 sensitive_data
.num_hostkeys
= num_keys
;
695 recv_rexec_state(int fd
, struct sshbuf
*conf
, uint64_t *timing_secretp
)
697 struct sshbuf
*m
, *inc
, *hostkeys
;
701 struct include_item
*item
;
703 debug3_f("entering fd = %d", fd
);
705 if ((m
= sshbuf_new()) == NULL
|| (inc
= sshbuf_new()) == NULL
)
706 fatal_f("sshbuf_new failed");
707 if (ssh_msg_recv(fd
, m
) == -1)
708 fatal_f("ssh_msg_recv failed");
709 if ((r
= sshbuf_get_u8(m
, &ver
)) != 0)
710 fatal_fr(r
, "parse version");
712 fatal_f("rexec version mismatch");
713 if ((r
= sshbuf_get_string(m
, &cp
, &len
)) != 0 || /* XXX _direct */
714 (r
= sshbuf_get_u64(m
, timing_secretp
)) != 0 ||
715 (r
= sshbuf_froms(m
, &hostkeys
)) != 0 ||
716 (r
= sshbuf_get_stringb(m
, inc
)) != 0)
717 fatal_fr(r
, "parse config");
719 if (conf
!= NULL
&& (r
= sshbuf_put(conf
, cp
, len
)))
720 fatal_fr(r
, "sshbuf_put");
722 while (sshbuf_len(inc
) != 0) {
723 item
= xcalloc(1, sizeof(*item
));
724 if ((item
->contents
= sshbuf_new()) == NULL
)
725 fatal_f("sshbuf_new failed");
726 if ((r
= sshbuf_get_cstring(inc
, &item
->selector
, NULL
)) != 0 ||
727 (r
= sshbuf_get_cstring(inc
, &item
->filename
, NULL
)) != 0 ||
728 (r
= sshbuf_get_stringb(inc
, item
->contents
)) != 0)
729 fatal_fr(r
, "parse includes");
730 TAILQ_INSERT_TAIL(&includes
, item
, entry
);
733 parse_hostkeys(hostkeys
);
737 sshbuf_free(hostkeys
);
744 * If IP options are supported, make sure there are none (log and
745 * return an error if any are found). Basically we are worried about
746 * source routing; it can be used to pretend you are somebody
747 * (ip-address) you are not. That itself may be "almost acceptable"
748 * under certain circumstances, but rhosts authentication is useless
749 * if source routing is accepted. Notice also that if we just dropped
750 * source routing here, the other side could use IP spoofing to do
751 * rest of the interaction and could still bypass security. So we
752 * exit here if we detect any IP options.
755 check_ip_options(struct ssh
*ssh
)
758 int sock_in
= ssh_packet_get_connection_in(ssh
);
759 struct sockaddr_storage from
;
761 socklen_t i
, option_size
= sizeof(opts
), fromlen
= sizeof(from
);
762 char text
[sizeof(opts
) * 3 + 1];
764 memset(&from
, 0, sizeof(from
));
765 if (getpeername(sock_in
, (struct sockaddr
*)&from
,
768 if (from
.ss_family
!= AF_INET
)
770 /* XXX IPv6 options? */
772 if (getsockopt(sock_in
, IPPROTO_IP
, IP_OPTIONS
, opts
,
773 &option_size
) >= 0 && option_size
!= 0) {
775 for (i
= 0; i
< option_size
; i
++)
776 snprintf(text
+ i
*3, sizeof(text
) - i
*3,
778 fatal("Connection from %.100s port %d with IP opts: %.800s",
779 ssh_remote_ipaddr(ssh
), ssh_remote_port(ssh
), text
);
781 #endif /* IP_OPTIONS */
784 /* Set the routing domain for this process */
786 set_process_rdomain(struct ssh
*ssh
, const char *name
)
788 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
790 return; /* default */
792 if (strcmp(name
, "%D") == 0) {
793 /* "expands" to routing domain of connection */
794 if ((name
= ssh_packet_rdomain_in(ssh
)) == NULL
)
797 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
798 return sys_set_process_rdomain(name
);
799 #elif defined(__OpenBSD__)
800 int rtable
, ortable
= getrtable();
804 return; /* default */
806 if (strcmp(name
, "%D") == 0) {
807 /* "expands" to routing domain of connection */
808 if ((name
= ssh_packet_rdomain_in(ssh
)) == NULL
)
812 rtable
= (int)strtonum(name
, 0, 255, &errstr
);
813 if (errstr
!= NULL
) /* Shouldn't happen */
814 fatal("Invalid routing domain \"%s\": %s", name
, errstr
);
815 if (rtable
!= ortable
&& setrtable(rtable
) != 0)
816 fatal("Unable to set routing domain %d: %s",
817 rtable
, strerror(errno
));
818 debug_f("set routing domain %d (was %d)", rtable
, ortable
);
819 #else /* defined(__OpenBSD__) */
820 fatal("Unable to set routing domain: not supported in this platform");
825 * Main program for the daemon.
828 main(int ac
, char **av
)
830 struct ssh
*ssh
= NULL
;
833 int devnull
, r
, opt
, on
= 1, remote_port
;
834 int sock_in
= -1, sock_out
= -1, rexeced_flag
= 0, have_key
= 0;
835 const char *remote_ip
, *rdomain
;
836 char *line
, *laddr
, *logfile
= NULL
;
838 u_int64_t ibytes
, obytes
;
841 struct connection_info
*connection_info
= NULL
;
843 uint64_t timing_secret
= 0;
844 struct itimerval itv
;
846 sigemptyset(&sigmask
);
847 sigprocmask(SIG_SETMASK
, &sigmask
, NULL
);
849 #ifdef HAVE_SECUREWARE
850 (void)set_auth_parameters(ac
, av
);
852 __progname
= ssh_get_progname(av
[0]);
854 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
856 saved_argv
= xcalloc(ac
+ 1, sizeof(*saved_argv
));
857 for (i
= 0; (int)i
< ac
; i
++)
858 saved_argv
[i
] = xstrdup(av
[i
]);
859 saved_argv
[i
] = NULL
;
861 #ifndef HAVE_SETPROCTITLE
862 /* Prepare for later setproctitle emulation */
863 compat_init_setproctitle(ac
, av
);
867 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
870 /* Initialize configuration options to their default values. */
871 initialize_server_options(&options
);
873 /* Parse command-line arguments. */
874 while ((opt
= getopt(ac
, av
,
875 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
878 options
.address_family
= AF_INET
;
881 options
.address_family
= AF_INET6
;
884 config_file_name
= optarg
;
887 servconf_add_hostcert("[command-line]", 0,
891 if (debug_flag
== 0) {
893 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
894 } else if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
919 options
.log_level
= SYSLOG_LEVEL_QUIET
;
922 /* protocol 1, ignored */
925 options
.ports_from_cmdline
= 1;
926 if (options
.num_ports
>= MAX_PORTS
) {
927 fprintf(stderr
, "too many ports.\n");
930 options
.ports
[options
.num_ports
++] = a2port(optarg
);
931 if (options
.ports
[options
.num_ports
-1] <= 0) {
932 fprintf(stderr
, "Bad port number.\n");
937 if ((options
.login_grace_time
= convtime(optarg
)) == -1) {
938 fprintf(stderr
, "Invalid login grace time.\n");
943 /* protocol 1, ignored */
946 servconf_add_hostkey("[command-line]", 0,
947 &options
, optarg
, 1);
952 fatal("test/dump modes not supported");
955 connection_info
= server_get_connection_info(ssh
, 0, 0);
956 if (parse_server_match_testspec(connection_info
,
961 utmp_len
= (u_int
)strtonum(optarg
, 0, HOST_NAME_MAX
+1+1, NULL
);
962 if (utmp_len
> HOST_NAME_MAX
+1) {
963 fprintf(stderr
, "Invalid utmp length.\n");
968 line
= xstrdup(optarg
);
969 if (process_server_config_line(&options
, line
,
970 "command-line", 0, NULL
, NULL
, &includes
) != 0)
975 fprintf(stderr
, "%s, %s\n",
976 SSH_RELEASE
, SSH_OPENSSL_VERSION
);
984 /* Check that there are no remaining arguments. */
986 fprintf(stderr
, "Extra argument %s.\n", av
[optind
]);
990 debug("sshd version %s, %s", SSH_VERSION
, SSH_OPENSSL_VERSION
);
993 fatal("sshd-session should not be executed directly");
995 closefrom(REEXEC_MIN_FREE_FD
);
997 /* Reserve fds we'll need later for reexec things */
998 if ((devnull
= open(_PATH_DEVNULL
, O_RDWR
)) == -1)
999 fatal("open %s: %s", _PATH_DEVNULL
, strerror(errno
));
1000 while (devnull
< PRIVSEP_MIN_FREE_FD
) {
1001 if ((devnull
= dup(devnull
)) == -1)
1002 fatal("dup %s: %s", _PATH_DEVNULL
, strerror(errno
));
1007 /* If requested, redirect the logs to the specified logfile. */
1008 if (logfile
!= NULL
) {
1009 char *cp
, pid_s
[32];
1011 snprintf(pid_s
, sizeof(pid_s
), "%ld", (unsigned long)getpid());
1012 cp
= percent_expand(logfile
,
1014 "P", "sshd-session",
1016 log_redirect_stderr_to(cp
);
1021 * Force logging to stderr until we have loaded the private host
1022 * key (unless started from inetd)
1024 log_init(__progname
,
1025 options
.log_level
== SYSLOG_LEVEL_NOT_SET
?
1026 SYSLOG_LEVEL_INFO
: options
.log_level
,
1027 options
.log_facility
== SYSLOG_FACILITY_NOT_SET
?
1028 SYSLOG_FACILITY_AUTH
: options
.log_facility
,
1029 log_stderr
|| !inetd_flag
|| debug_flag
);
1031 debug("sshd version %s, %s", SSH_VERSION
, SSH_OPENSSL_VERSION
);
1033 /* Fetch our configuration */
1034 if ((cfg
= sshbuf_new()) == NULL
)
1035 fatal("sshbuf_new config buf failed");
1036 setproctitle("%s", "[rexeced]");
1037 recv_rexec_state(REEXEC_CONFIG_PASS_FD
, cfg
, &timing_secret
);
1038 /* close the fd, but keep the slot reserved */
1039 if (dup2(devnull
, REEXEC_CONFIG_PASS_FD
) == -1)
1040 fatal("dup2 devnull->config fd: %s", strerror(errno
));
1041 parse_server_config(&options
, "rexec", cfg
, &includes
, NULL
, 1);
1042 /* Fill in default values for those options not explicitly set. */
1043 fill_default_server_options(&options
);
1044 options
.timing_secret
= timing_secret
;
1046 /* Store privilege separation user for later use if required. */
1047 privsep_chroot
= (getuid() == 0 || geteuid() == 0);
1048 if ((privsep_pw
= getpwnam(SSH_PRIVSEP_USER
)) == NULL
) {
1049 if (privsep_chroot
|| options
.kerberos_authentication
)
1050 fatal("Privilege separation user %s does not exist",
1053 privsep_pw
= pwcopy(privsep_pw
);
1054 freezero(privsep_pw
->pw_passwd
, strlen(privsep_pw
->pw_passwd
));
1055 privsep_pw
->pw_passwd
= xstrdup("*");
1059 if (!debug_flag
&& !inetd_flag
) {
1060 if ((startup_pipe
= dup(REEXEC_STARTUP_PIPE_FD
)) == -1)
1061 fatal("internal error: no startup pipe");
1062 /* close the fd, but keep the slot reserved */
1063 if (dup2(devnull
, REEXEC_STARTUP_PIPE_FD
) == -1)
1064 fatal("dup2 devnull->startup fd: %s", strerror(errno
));
1067 * Signal parent that this child is at a point where
1068 * they can go away if they have a SIGHUP pending.
1070 (void)atomicio(vwrite
, startup_pipe
, "\0", 1);
1073 /* Check that options are sensible */
1074 if (options
.authorized_keys_command_user
== NULL
&&
1075 (options
.authorized_keys_command
!= NULL
&&
1076 strcasecmp(options
.authorized_keys_command
, "none") != 0))
1077 fatal("AuthorizedKeysCommand set without "
1078 "AuthorizedKeysCommandUser");
1079 if (options
.authorized_principals_command_user
== NULL
&&
1080 (options
.authorized_principals_command
!= NULL
&&
1081 strcasecmp(options
.authorized_principals_command
, "none") != 0))
1082 fatal("AuthorizedPrincipalsCommand set without "
1083 "AuthorizedPrincipalsCommandUser");
1086 * Check whether there is any path through configured auth methods.
1087 * Unfortunately it is not possible to verify this generally before
1088 * daemonisation in the presence of Match block, but this catches
1089 * and warns for trivial misconfigurations that could break login.
1091 if (options
.num_auth_methods
!= 0) {
1092 for (i
= 0; i
< options
.num_auth_methods
; i
++) {
1093 if (auth2_methods_valid(options
.auth_methods
[i
],
1097 if (i
>= options
.num_auth_methods
)
1098 fatal("AuthenticationMethods cannot be satisfied by "
1099 "enabled authentication methods");
1103 if (options
.moduli_file
!= NULL
)
1104 dh_set_moduli_file(options
.moduli_file
);
1107 if (options
.host_key_agent
) {
1108 if (strcmp(options
.host_key_agent
, SSH_AUTHSOCKET_ENV_NAME
))
1109 setenv(SSH_AUTHSOCKET_ENV_NAME
,
1110 options
.host_key_agent
, 1);
1111 if ((r
= ssh_get_authentication_socket(NULL
)) == 0)
1114 error_r(r
, "Could not connect to agent \"%s\"",
1115 options
.host_key_agent
);
1118 if (options
.num_host_key_files
!= sensitive_data
.num_hostkeys
) {
1119 fatal("internal error: hostkeys confused (config %u recvd %u)",
1120 options
.num_host_key_files
, sensitive_data
.num_hostkeys
);
1123 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
1124 if (sensitive_data
.host_keys
[i
] != NULL
||
1125 (have_agent
&& sensitive_data
.host_pubkeys
[i
] != NULL
)) {
1131 fatal("internal error: monitor received no hostkeys");
1133 /* Ensure that umask disallows at least group and world write */
1134 new_umask
= umask(0077) | 0022;
1135 (void) umask(new_umask
);
1137 /* Initialize the log (it is reinitialized below in case we forked). */
1140 log_init(__progname
, options
.log_level
,
1141 options
.log_facility
, log_stderr
);
1142 for (i
= 0; i
< options
.num_log_verbose
; i
++)
1143 log_verbose_add(options
.log_verbose
[i
]);
1145 /* Reinitialize the log (because of the fork above). */
1146 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1149 * Chdir to the root directory so that the current disk can be
1150 * unmounted if desired.
1152 if (chdir("/") == -1)
1153 error("chdir(\"/\"): %s", strerror(errno
));
1155 /* ignore SIGPIPE */
1156 ssh_signal(SIGPIPE
, SIG_IGN
);
1158 /* Get a connection, either from inetd or rexec */
1161 * NB. must be different fd numbers for the !socket case,
1162 * as packet_connection_is_on_socket() depends on this.
1164 sock_in
= dup(STDIN_FILENO
);
1165 sock_out
= dup(STDOUT_FILENO
);
1167 /* rexec case; accept()ed socket in ancestor listener */
1168 sock_in
= sock_out
= dup(STDIN_FILENO
);
1172 * We intentionally do not close the descriptors 0, 1, and 2
1173 * as our code for setting the descriptors won't work if
1174 * ttyfd happens to be one of those.
1176 if (stdfd_devnull(1, 1, !log_stderr
) == -1)
1177 error("stdfd_devnull failed");
1178 debug("network sockets: %d, %d", sock_in
, sock_out
);
1180 /* This is the child processing a new connection. */
1181 setproctitle("%s", "[accepted]");
1183 /* Executed child processes don't need these. */
1184 fcntl(sock_out
, F_SETFD
, FD_CLOEXEC
);
1185 fcntl(sock_in
, F_SETFD
, FD_CLOEXEC
);
1187 /* We will not restart on SIGHUP since it no longer makes sense. */
1188 ssh_signal(SIGALRM
, SIG_DFL
);
1189 ssh_signal(SIGHUP
, SIG_DFL
);
1190 ssh_signal(SIGTERM
, SIG_DFL
);
1191 ssh_signal(SIGQUIT
, SIG_DFL
);
1192 ssh_signal(SIGCHLD
, SIG_DFL
);
1193 ssh_signal(SIGINT
, SIG_DFL
);
1196 * Register our connection. This turns encryption off because we do
1199 if ((ssh
= ssh_packet_set_connection(NULL
, sock_in
, sock_out
)) == NULL
)
1200 fatal("Unable to create connection");
1201 the_active_state
= ssh
;
1202 ssh_packet_set_server(ssh
);
1204 check_ip_options(ssh
);
1206 /* Prepare the channels layer */
1207 channel_init_channels(ssh
);
1208 channel_set_af(ssh
, options
.address_family
);
1209 server_process_channel_timeouts(ssh
);
1210 server_process_permitopen(ssh
);
1212 /* Set SO_KEEPALIVE if requested. */
1213 if (options
.tcp_keep_alive
&& ssh_packet_connection_is_on_socket(ssh
) &&
1214 setsockopt(sock_in
, SOL_SOCKET
, SO_KEEPALIVE
, &on
, sizeof(on
)) == -1)
1215 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno
));
1217 if ((remote_port
= ssh_remote_port(ssh
)) < 0) {
1218 debug("ssh_remote_port failed");
1223 * The rest of the code depends on the fact that
1224 * ssh_remote_ipaddr() caches the remote ip, even if
1225 * the socket goes away.
1227 remote_ip
= ssh_remote_ipaddr(ssh
);
1229 #ifdef SSH_AUDIT_EVENTS
1230 audit_connection_from(remote_ip
, remote_port
);
1233 rdomain
= ssh_packet_rdomain_in(ssh
);
1235 /* Log the connection. */
1236 laddr
= get_local_ipaddr(sock_in
);
1237 verbose("Connection from %s port %d on %s port %d%s%s%s",
1238 remote_ip
, remote_port
, laddr
, ssh_local_port(ssh
),
1239 rdomain
== NULL
? "" : " rdomain \"",
1240 rdomain
== NULL
? "" : rdomain
,
1241 rdomain
== NULL
? "" : "\"");
1245 * We don't want to listen forever unless the other side
1246 * successfully authenticates itself. So we set up an alarm which is
1247 * cleared after successful authentication. A limit of zero
1248 * indicates no limit. Note that we don't set the alarm in debugging
1249 * mode; it is just annoying to have the server exit just when you
1250 * are about to discover the bug.
1252 ssh_signal(SIGALRM
, grace_alarm_handler
);
1253 if (!debug_flag
&& options
.login_grace_time
> 0) {
1254 int ujitter
= arc4random_uniform(4 * 1000000);
1256 timerclear(&itv
.it_interval
);
1257 itv
.it_value
.tv_sec
= options
.login_grace_time
;
1258 itv
.it_value
.tv_sec
+= ujitter
/ 1000000;
1259 itv
.it_value
.tv_usec
= ujitter
% 1000000;
1261 if (setitimer(ITIMER_REAL
, &itv
, NULL
) == -1)
1262 fatal("login grace time setitimer failed");
1265 if ((r
= kex_exchange_identification(ssh
, -1,
1266 options
.version_addendum
)) != 0)
1267 sshpkt_fatal(ssh
, r
, "banner exchange");
1269 ssh_packet_set_nonblocking(ssh
);
1271 /* allocate authentication context */
1272 authctxt
= xcalloc(1, sizeof(*authctxt
));
1273 ssh
->authctxt
= authctxt
;
1275 /* XXX global for cleanup, access from other modules */
1276 the_authctxt
= authctxt
;
1278 /* Set default key authentication options */
1279 if ((auth_opts
= sshauthopt_new_with_keys_defaults()) == NULL
)
1280 fatal("allocation failed");
1282 /* prepare buffer to collect messages to display to user after login */
1283 if ((loginmsg
= sshbuf_new()) == NULL
)
1284 fatal("sshbuf_new loginmsg failed");
1287 if (privsep_preauth(ssh
) != 1)
1288 fatal("privsep_preauth failed");
1290 /* Now user is authenticated */
1293 * Cancel the alarm we set to limit the time taken for
1296 timerclear(&itv
.it_interval
);
1297 timerclear(&itv
.it_value
);
1298 if (setitimer(ITIMER_REAL
, &itv
, NULL
) == -1)
1299 fatal("login grace time clear failed");
1300 ssh_signal(SIGALRM
, SIG_DFL
);
1301 authctxt
->authenticated
= 1;
1302 if (startup_pipe
!= -1) {
1303 /* signal listener that authentication completed successfully */
1304 (void)atomicio(vwrite
, startup_pipe
, "\001", 1);
1305 close(startup_pipe
);
1309 if (options
.routing_domain
!= NULL
)
1310 set_process_rdomain(ssh
, options
.routing_domain
);
1312 #ifdef SSH_AUDIT_EVENTS
1313 audit_event(ssh
, SSH_AUTH_SUCCESS
);
1317 if (options
.gss_authentication
) {
1318 temporarily_use_uid(authctxt
->pw
);
1319 ssh_gssapi_storecreds();
1324 if (options
.use_pam
) {
1326 do_pam_session(ssh
);
1331 * In privilege separation, we fork another child and prepare
1332 * file descriptor passing.
1334 privsep_postauth(ssh
, authctxt
);
1335 /* the monitor process [priv] will not return */
1337 ssh_packet_set_timeout(ssh
, options
.client_alive_interval
,
1338 options
.client_alive_count_max
);
1340 /* Try to send all our hostkeys to the client */
1341 notify_hostkeys(ssh
);
1343 /* Start session. */
1344 do_authenticated(ssh
, authctxt
);
1346 /* The connection has been terminated. */
1347 ssh_packet_get_bytes(ssh
, &ibytes
, &obytes
);
1348 verbose("Transferred: sent %llu, received %llu bytes",
1349 (unsigned long long)obytes
, (unsigned long long)ibytes
);
1351 verbose("Closing connection to %.500s port %d", remote_ip
, remote_port
);
1354 if (options
.use_pam
)
1356 #endif /* USE_PAM */
1358 #ifdef SSH_AUDIT_EVENTS
1359 mm_audit_event(ssh
, SSH_CONNECTION_CLOSE
);
1362 ssh_packet_close(ssh
);
1370 sshd_hostkey_sign(struct ssh
*ssh
, struct sshkey
*privkey
,
1371 struct sshkey
*pubkey
, u_char
**signature
, size_t *slenp
,
1372 const u_char
*data
, size_t dlen
, const char *alg
)
1375 if (mm_sshkey_sign(ssh
, privkey
, signature
, slenp
,
1376 data
, dlen
, alg
, options
.sk_provider
, NULL
,
1378 fatal_f("privkey sign failed");
1380 if (mm_sshkey_sign(ssh
, pubkey
, signature
, slenp
,
1381 data
, dlen
, alg
, options
.sk_provider
, NULL
,
1383 fatal_f("pubkey sign failed");
1388 /* server specific fatal cleanup */
1392 extern int auth_attempted
; /* monitor.c */
1394 if (the_active_state
!= NULL
&& the_authctxt
!= NULL
) {
1395 do_cleanup(the_active_state
, the_authctxt
);
1396 if (privsep_is_preauth
&&
1397 pmonitor
!= NULL
&& pmonitor
->m_pid
> 1) {
1398 debug("Killing privsep child %d", pmonitor
->m_pid
);
1399 if (kill(pmonitor
->m_pid
, SIGKILL
) != 0 &&
1401 error_f("kill(%d): %s", pmonitor
->m_pid
,
1406 #ifdef SSH_AUDIT_EVENTS
1407 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
1408 if (the_active_state
!= NULL
&& mm_is_monitor())
1409 audit_event(the_active_state
, SSH_CONNECTION_ABANDON
);
1411 /* Override default fatal exit value when auth was attempted */
1412 if (i
== 255 && auth_attempted
)
1413 _exit(EXIT_AUTH_ATTEMPTED
);