]> git.ipfire.org Git - thirdparty/openssh-portable.git/commitdiff
upstream: Split per-connection sshd-session binary
authordjm@openbsd.org <djm@openbsd.org>
Mon, 14 Oct 2024 01:57:50 +0000 (01:57 +0000)
committerDamien Miller <djm@mindrot.org>
Mon, 14 Oct 2024 03:01:37 +0000 (14:01 +1100)
This splits the user authentication code from the sshd-session
binary into a separate sshd-auth binary. This will be executed by
sshd-session to complete the user authentication phase of the
protocol only.

Splitting this code into a separate binary ensures that the crucial
pre-authentication attack surface has an entirely disjoint address
space from the code used for the rest of the connection. It also
yields a small runtime memory saving as the authentication code will
be unloaded after thhe authentication phase completes.

Joint work with markus@ feedback deraadt@

Tested in snaps since last week

OpenBSD-Commit-ID: 9c3b2087ae08626ec31b4177b023db600e986d9c

22 files changed:
Makefile.in
log.c
monitor.c
monitor.h
monitor_wrap.c
monitor_wrap.h
pathnames.h
sandbox-capsicum.c
sandbox-darwin.c
sandbox-null.c
sandbox-pledge.c
sandbox-rlimit.c
sandbox-seccomp-filter.c
sandbox-solaris.c
sandbox-systrace.c
servconf.c
servconf.h
session.c
ssh-sandbox.h
sshd-auth.c [new file with mode: 0644]
sshd-session.c
sshd.c

index 4243006b0cedfa8e52312dfd5e0ae5652d16a9ec..c7141cf6dedc59e1a25a062da54dc1e523205c67 100644 (file)
@@ -25,6 +25,7 @@ ASKPASS_PROGRAM=$(libexecdir)/ssh-askpass
 SFTP_SERVER=$(libexecdir)/sftp-server
 SSH_KEYSIGN=$(libexecdir)/ssh-keysign
 SSHD_SESSION=$(libexecdir)/sshd-session
+SSHD_AUTH=$(libexecdir)/sshd-auth
 SSH_PKCS11_HELPER=$(libexecdir)/ssh-pkcs11-helper
 SSH_SK_HELPER=$(libexecdir)/ssh-sk-helper
 PRIVSEP_PATH=@PRIVSEP_PATH@
@@ -71,7 +72,7 @@ MKDIR_P=@MKDIR_P@
 
 .SUFFIXES: .lo
 
-TARGETS=ssh$(EXEEXT) sshd$(EXEEXT) sshd-session$(EXEEXT) ssh-add$(EXEEXT) ssh-keygen$(EXEEXT) ssh-keyscan${EXEEXT} ssh-keysign${EXEEXT} ssh-pkcs11-helper$(EXEEXT) ssh-agent$(EXEEXT) scp$(EXEEXT) sftp-server$(EXEEXT) sftp$(EXEEXT) ssh-sk-helper$(EXEEXT)
+TARGETS=ssh$(EXEEXT) sshd$(EXEEXT) sshd-session$(EXEEXT) sshd-auth$(EXEEXT) ssh-add$(EXEEXT) ssh-keygen$(EXEEXT) ssh-keyscan${EXEEXT} ssh-keysign${EXEEXT} ssh-pkcs11-helper$(EXEEXT) ssh-agent$(EXEEXT) scp$(EXEEXT) sftp-server$(EXEEXT) sftp$(EXEEXT) ssh-sk-helper$(EXEEXT)
 
 XMSS_OBJS=\
        ssh-xmss.o \
@@ -137,9 +138,22 @@ SSHD_SESSION_OBJS=sshd-session.o auth-rhosts.o auth-passwd.o \
        auth2-gss.o gss-serv.o gss-serv-krb5.o \
        loginrec.o auth-pam.o auth-shadow.o auth-sia.o \
        sftp-server.o sftp-common.o \
-       sandbox-null.o sandbox-rlimit.o sandbox-systrace.o sandbox-darwin.o \
-       sandbox-seccomp-filter.o sandbox-capsicum.o sandbox-pledge.o \
-       sandbox-solaris.o uidswap.o $(SKOBJS)
+       uidswap.o $(SKOBJS)
+
+SSHD_AUTH_OBJS=sshd-auth.o \
+       auth2-methods.o \
+       auth-rhosts.o auth-passwd.o sshpty.o sshlogin.o servconf.o \
+       serverloop.o auth.o auth2.o auth-options.o session.o auth2-chall.o \
+       groupaccess.o auth-bsdauth.o auth2-hostbased.o auth2-kbdint.o \
+       auth2-none.o auth2-passwd.o auth2-pubkey.o auth2-pubkeyfile.o \
+       auth2-gss.o gss-serv.o gss-serv-krb5.o \
+       monitor_wrap.o auth-krb5.o \
+       audit.o audit-bsm.o audit-linux.o platform.o \
+       loginrec.o auth-pam.o auth-shadow.o auth-sia.o \
+       sandbox-null.o sandbox-rlimit.o sandbox-darwin.o \
+       sandbox-seccomp-filter.o sandbox-capsicum.o  sandbox-solaris.o \
+       sftp-server.o sftp-common.o \
+       uidswap.o $(SKOBJS)
 
 SFTP_CLIENT_OBJS=sftp-common.o sftp-client.o sftp-glob.o
 
@@ -220,6 +234,9 @@ sshd$(EXEEXT): libssh.a     $(LIBCOMPAT) $(SSHDOBJS)
 sshd-session$(EXEEXT): libssh.a        $(LIBCOMPAT) $(SSHD_SESSION_OBJS)
        $(LD) -o $@ $(SSHD_SESSION_OBJS) $(LDFLAGS) -lssh -lopenbsd-compat $(SSHDLIBS) $(LIBS) $(GSSLIBS) $(K5LIBS) $(CHANNELLIBS)
 
+sshd-auth$(EXEEXT): libssh.a $(LIBCOMPAT) $(SSHD_AUTH_OBJS)
+       $(LD) -o $@ $(SSHD_AUTH_OBJS) $(LDFLAGS) -lssh -lopenbsd-compat $(SSHDLIBS) $(LIBS) $(GSSLIBS) $(K5LIBS) $(CHANNELLIBS)
+
 scp$(EXEEXT): $(LIBCOMPAT) libssh.a $(SCP_OBJS)
        $(LD) -o $@ $(SCP_OBJS) $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
 
@@ -411,6 +428,7 @@ install-files:
        $(INSTALL) -m 0755 $(STRIP_OPT) ssh-keyscan$(EXEEXT) $(DESTDIR)$(bindir)/ssh-keyscan$(EXEEXT)
        $(INSTALL) -m 0755 $(STRIP_OPT) sshd$(EXEEXT) $(DESTDIR)$(sbindir)/sshd$(EXEEXT)
        $(INSTALL) -m 0755 $(STRIP_OPT) sshd-session$(EXEEXT) $(DESTDIR)$(SSHD_SESSION)$(EXEEXT)
+       $(INSTALL) -m 0755 $(STRIP_OPT) sshd-auth$(EXEEXT) $(DESTDIR)$(SSHD_AUTH)$(EXEEXT)
        $(INSTALL) -m 4711 $(STRIP_OPT) ssh-keysign$(EXEEXT) $(DESTDIR)$(SSH_KEYSIGN)$(EXEEXT)
        $(INSTALL) -m 0755 $(STRIP_OPT) ssh-pkcs11-helper$(EXEEXT) $(DESTDIR)$(SSH_PKCS11_HELPER)$(EXEEXT)
        $(INSTALL) -m 0755 $(STRIP_OPT) ssh-sk-helper$(EXEEXT) $(DESTDIR)$(SSH_SK_HELPER)$(EXEEXT)
@@ -754,6 +772,7 @@ interop-tests t-exec file-tests extra-tests: regress-prep regress-binaries $(TAR
                TEST_SSH_SSH="$(BUILDDIR)/ssh" \
                TEST_SSH_SSHD="$(BUILDDIR)/sshd" \
                TEST_SSH_SSHD_SESSION="$(BUILDDIR)/sshd-session" \
+               TEST_SSH_SSHD_AUTH="$(BUILDDIR)/sshd-auth" \
                TEST_SSH_SSHAGENT="$(BUILDDIR)/ssh-agent" \
                TEST_SSH_SSHADD="$(BUILDDIR)/ssh-add" \
                TEST_SSH_SSHKEYGEN="$(BUILDDIR)/ssh-keygen" \
diff --git a/log.c b/log.c
index 23ad10c0225d746effcbc9317d053feda8d06668..3ae3e56820575571a4600b4ec179b551323d191c 100644 (file)
--- a/log.c
+++ b/log.c
@@ -460,9 +460,9 @@ sshlogv(const char *file, const char *func, int line, int showfunc,
        if (nlog_verbose == 0 && level > log_level)
                return;
 
-       snprintf(tag, sizeof(tag), "%.48s:%.48s():%d (pid=%ld)",
+       snprintf(tag, sizeof(tag), "%.48s:%.48s():%d (bin=%s, pid=%ld)",
            (cp = strrchr(file, '/')) == NULL ? file : cp + 1, func, line,
-           (long)getpid());
+           argv0 == NULL ? "UNKNOWN" : argv0, (long)getpid());
        for (i = 0; i < nlog_verbose; i++) {
                if (match_pattern_list(tag, log_verbose[i], 0) == 1) {
                        forced = 1;
index f3f79de43dd7553bba49afdf88b8e1ccd2741133..84d5168296b1368dd50c84d06d5bd292ff124db2 100644 (file)
--- a/monitor.c
+++ b/monitor.c
@@ -105,7 +105,9 @@ static Gssctxt *gsscontext = NULL;
 /* Imports */
 extern ServerOptions options;
 extern u_int utmp_len;
+extern struct sshbuf *cfg;
 extern struct sshbuf *loginmsg;
+extern struct include_list includes;
 extern struct sshauthopt *auth_opts; /* XXX move to permanent ssh->authctxt? */
 
 /* State exported from the child */
@@ -126,6 +128,7 @@ int mm_answer_keyverify(struct ssh *, int, struct sshbuf *);
 int mm_answer_pty(struct ssh *, int, struct sshbuf *);
 int mm_answer_pty_cleanup(struct ssh *, int, struct sshbuf *);
 int mm_answer_term(struct ssh *, int, struct sshbuf *);
+int mm_answer_state(struct ssh *, int, struct sshbuf *);
 
 #ifdef USE_PAM
 int mm_answer_pam_start(struct ssh *, int, struct sshbuf *);
@@ -184,6 +187,7 @@ static int monitor_read(struct ssh *, struct monitor *, struct mon_table *,
 static int monitor_read_log(struct monitor *);
 
 struct mon_table mon_dispatch_proto20[] = {
+    {MONITOR_REQ_STATE, MON_ONCE, mm_answer_state},
 #ifdef WITH_OPENSSL
     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
 #endif
@@ -219,6 +223,7 @@ struct mon_table mon_dispatch_proto20[] = {
 };
 
 struct mon_table mon_dispatch_postauth20[] = {
+    {MONITOR_REQ_STATE, MON_ONCE, mm_answer_state},
 #ifdef WITH_OPENSSL
     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
 #endif
@@ -284,7 +289,8 @@ monitor_child_preauth(struct ssh *ssh, struct monitor *pmonitor)
        authctxt->loginmsg = loginmsg;
 
        mon_dispatch = mon_dispatch_proto20;
-       /* Permit requests for moduli and signatures */
+       /* Permit requests for state, moduli and signatures */
+       monitor_permit(mon_dispatch, MONITOR_REQ_STATE, 1);
        monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
        monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
 
@@ -405,6 +411,7 @@ monitor_child_postauth(struct ssh *ssh, struct monitor *pmonitor)
        mon_dispatch = mon_dispatch_postauth20;
 
        /* Permit requests for moduli and signatures */
+       monitor_permit(mon_dispatch, MONITOR_REQ_STATE, 1);
        monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
        monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
        monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
@@ -462,7 +469,8 @@ monitor_read_log(struct monitor *pmonitor)
        /* Log it */
        if (log_level_name(level) == NULL)
                fatal_f("invalid log level %u (corrupted message?)", level);
-       sshlogdirect(level, forced, "%s [preauth]", msg);
+       sshlogdirect(level, forced, "%s [%s]", msg,
+           mon_dispatch == mon_dispatch_postauth20 ? "postauth" : "preauth");
 
        sshbuf_free(logmsg);
        free(msg);
@@ -568,6 +576,82 @@ monitor_reset_key_state(void)
        hostbased_chost = NULL;
 }
 
+int
+mm_answer_state(struct ssh *ssh, int sock, struct sshbuf *m)
+{
+       struct sshbuf *inc = NULL, *hostkeys = NULL;
+       struct sshbuf *opts = NULL, *confdata = NULL;
+       struct include_item *item = NULL;
+       int postauth;
+       int r;
+
+       sshbuf_reset(m);
+
+       debug_f("config len %zu", sshbuf_len(cfg));
+
+       if ((m = sshbuf_new()) == NULL ||
+           (inc = sshbuf_new()) == NULL ||
+           (opts = sshbuf_new()) == NULL ||
+           (confdata = sshbuf_new()) == NULL)
+               fatal_f("sshbuf_new failed");
+
+       /* XXX unneccessary? */
+       /* pack includes into a string */
+       TAILQ_FOREACH(item, &includes, entry) {
+               if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
+                   (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
+                   (r = sshbuf_put_stringb(inc, item->contents)) != 0)
+                       fatal_fr(r, "compose includes");
+       }
+
+       hostkeys = pack_hostkeys();
+
+       /*
+        * Protocol from monitor to unpriv privsep process:
+        *      string  configuration
+        *      uint64  timing_secret   XXX move delays to monitor and remove
+        *      string  host_keys[] {
+        *              string public_key
+        *              string certificate
+        *      }
+        *      string  server_banner
+        *      string  client_banner
+        *      string  included_files[] {
+        *              string  selector
+        *              string  filename
+        *              string  contents
+        *      }
+        *      string  configuration_data (postauth)
+        *      string  keystate (postauth)
+        *      string  authenticated_user (postauth)
+        *      string  session_info (postauth)
+        *      string  authopts (postauth)
+        */
+       if ((r = sshbuf_put_stringb(m, cfg)) != 0 ||
+           (r = sshbuf_put_u64(m, options.timing_secret)) != 0 ||
+           (r = sshbuf_put_stringb(m, hostkeys)) != 0 ||
+           (r = sshbuf_put_stringb(m, ssh->kex->server_version)) != 0 ||
+           (r = sshbuf_put_stringb(m, ssh->kex->client_version)) != 0 ||
+           (r = sshbuf_put_stringb(m, inc)) != 0)
+               fatal_fr(r, "compose config");
+
+       postauth = (authctxt && authctxt->pw && authctxt->authenticated);
+       if (postauth) {
+               /* XXX shouldn't be reachable */
+               fatal_f("internal error: called in postauth");
+       }
+
+       sshbuf_free(inc);
+       sshbuf_free(opts);
+       sshbuf_free(confdata);
+
+       mm_request_send(sock, MONITOR_ANS_STATE, m);
+
+       debug3_f("done");
+
+       return (0);
+}
+
 #ifdef WITH_OPENSSL
 int
 mm_answer_moduli(struct ssh *ssh, int sock, struct sshbuf *m)
@@ -613,24 +697,27 @@ int
 mm_answer_sign(struct ssh *ssh, int sock, struct sshbuf *m)
 {
        extern int auth_sock;                   /* XXX move to state struct? */
-       struct sshkey *key;
+       struct sshkey *pubkey, *key;
        struct sshbuf *sigbuf = NULL;
        u_char *p = NULL, *signature = NULL;
        char *alg = NULL;
-       size_t datlen, siglen, alglen;
-       int r, is_proof = 0;
-       u_int keyid, compat;
+       size_t datlen, siglen;
+       int r, is_proof = 0, keyid;
+       u_int compat;
        const char proof_req[] = "hostkeys-prove-00@openssh.com";
 
        debug3_f("entering");
 
-       if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
+       if ((r = sshkey_froms(m, &pubkey)) != 0 ||
            (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
-           (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0 ||
+           (r = sshbuf_get_cstring(m, &alg, NULL)) != 0 ||
            (r = sshbuf_get_u32(m, &compat)) != 0)
                fatal_fr(r, "parse");
-       if (keyid > INT_MAX)
-               fatal_f("invalid key ID");
+
+       if ((keyid = get_hostkey_index(pubkey, 1, ssh)) == -1)
+               fatal_f("unknown hostkey");
+       debug_f("hostkey %s index %d", sshkey_ssh_name(pubkey), keyid);
+       sshkey_free(pubkey);
 
        /*
         * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
index fa48fc69be6c4a056792488a9dfbdc9659d3b5f0..3f8a9bea30c6106f117801fa4c75461180772701 100644 (file)
--- a/monitor.h
+++ b/monitor.h
@@ -54,6 +54,7 @@ enum monitor_reqtype {
        MONITOR_REQ_GSSUSEROK = 46, MONITOR_ANS_GSSUSEROK = 47,
        MONITOR_REQ_GSSCHECKMIC = 48, MONITOR_ANS_GSSCHECKMIC = 49,
        MONITOR_REQ_TERM = 50,
+       MONITOR_REQ_STATE = 51, MONITOR_ANS_STATE = 52,
 
        MONITOR_REQ_PAM_START = 100,
        MONITOR_REQ_PAM_ACCOUNT = 102, MONITOR_ANS_PAM_ACCOUNT = 103,
@@ -96,4 +97,6 @@ void mm_get_keystate(struct ssh *, struct monitor *);
 /* XXX: should be returned via a monitor call rather than config_fd */
 void mm_encode_server_options(struct sshbuf *);
 
+struct sshbuf *pack_hostkeys(void);
+
 #endif /* _MONITOR_H_ */
index 5358c77a1133ff08b4cb0b6780c3877df6b81582..20c480ed9b76e2841d3fad0189da8b3d307016cd 100644 (file)
@@ -111,16 +111,6 @@ mm_log_handler(LogLevel level, int forced, const char *msg, void *ctx)
        sshbuf_free(log_msg);
 }
 
-int
-mm_is_monitor(void)
-{
-       /*
-        * m_pid is only set in the privileged part, and
-        * points to the unprivileged child.
-        */
-       return (pmonitor && pmonitor->m_pid > 0);
-}
-
 static void
 mm_reap(void)
 {
@@ -264,15 +254,13 @@ mm_sshkey_sign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
     const u_char *data, size_t datalen, const char *hostkey_alg,
     const char *sk_provider, const char *sk_pin, u_int compat)
 {
-       struct kex *kex = *pmonitor->m_pkex;
        struct sshbuf *m;
-       u_int ndx = kex->host_key_index(key, 0, ssh);
        int r;
 
        debug3_f("entering");
        if ((m = sshbuf_new()) == NULL)
                fatal_f("sshbuf_new failed");
-       if ((r = sshbuf_put_u32(m, ndx)) != 0 ||
+       if ((r = sshkey_puts(key, m)) != 0 ||
            (r = sshbuf_put_string(m, data, datalen)) != 0 ||
            (r = sshbuf_put_cstring(m, hostkey_alg)) != 0 ||
            (r = sshbuf_put_u32(m, compat)) != 0)
@@ -285,6 +273,7 @@ mm_sshkey_sign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
        if ((r = sshbuf_get_string(m, sigp, lenp)) != 0)
                fatal_fr(r, "parse");
        sshbuf_free(m);
+       debug3_f("%s signature len=%zu", hostkey_alg, *lenp);
 
        return (0);
 }
@@ -861,6 +850,72 @@ mm_terminate(void)
        sshbuf_free(m);
 }
 
+/* Request state information */
+
+void
+mm_get_state(struct ssh *ssh, struct include_list *includes,
+    struct sshbuf *conf, struct sshbuf **confdatap,
+    uint64_t *timing_secretp,
+    struct sshbuf **hostkeysp, struct sshbuf **keystatep,
+    u_char **pw_namep,
+    struct sshbuf **authinfop, struct sshbuf **auth_optsp)
+{
+       struct sshbuf *m, *inc;
+       u_char *cp;
+       size_t len;
+       int r;
+       struct include_item *item;
+
+       debug3_f("entering");
+
+       if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
+               fatal_f("sshbuf_new failed");
+
+       mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_STATE, m);
+
+       debug3_f("waiting for MONITOR_ANS_STATE");
+       mm_request_receive_expect(pmonitor->m_recvfd,
+           MONITOR_ANS_STATE, m);
+
+       if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
+           (r = sshbuf_get_u64(m, timing_secretp)) != 0 ||
+           (r = sshbuf_froms(m, hostkeysp)) != 0 ||
+           (r = sshbuf_get_stringb(m, ssh->kex->server_version)) != 0 ||
+           (r = sshbuf_get_stringb(m, ssh->kex->client_version)) != 0 ||
+           (r = sshbuf_get_stringb(m, inc)) != 0)
+               fatal_fr(r, "parse config");
+
+       /* postauth */
+       if (confdatap) {
+               if ((r = sshbuf_froms(m, confdatap)) != 0 ||
+                   (r = sshbuf_froms(m, keystatep)) != 0 ||
+                   (r = sshbuf_get_string(m, pw_namep, NULL)) != 0 ||
+                   (r = sshbuf_froms(m, authinfop)) != 0 ||
+                   (r = sshbuf_froms(m, auth_optsp)) != 0)
+                       fatal_fr(r, "parse config postauth");
+       }
+
+       if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
+               fatal_fr(r, "sshbuf_put");
+
+       while (sshbuf_len(inc) != 0) {
+               item = xcalloc(1, sizeof(*item));
+               if ((item->contents = sshbuf_new()) == NULL)
+                       fatal_f("sshbuf_new failed");
+               if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
+                   (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
+                   (r = sshbuf_get_stringb(inc, item->contents)) != 0)
+                       fatal_fr(r, "parse includes");
+               TAILQ_INSERT_TAIL(includes, item, entry);
+       }
+
+       free(cp);
+       sshbuf_free(m);
+       sshbuf_free(inc);
+
+       debug3_f("done");
+}
+
 static void
 mm_chall_setup(char **name, char **infotxt, u_int *numprompts,
     char ***prompts, u_int **echo_on)
index e768036ed438a88e8ea7249d4db68be784f6435a..7134afeecf4e3a6b7d83c46ca72ed030a11de827 100644 (file)
@@ -90,6 +90,12 @@ void mm_session_pty_cleanup2(struct Session *);
 
 void mm_send_keystate(struct ssh *, struct monitor*);
 
+/* state */
+struct include_list;
+void mm_get_state(struct ssh *, struct include_list *, struct sshbuf *,
+    struct sshbuf **, uint64_t *, struct sshbuf **, struct sshbuf **,
+    u_char **, struct sshbuf **, struct sshbuf **);
+
 /* bsdauth */
 int mm_bsdauth_query(void *, char **, char **, u_int *, char ***, u_int **);
 int mm_bsdauth_respond(void *, u_int, char **);
index 61c5f8467094e62f5c67352761e834f4ef09b65a..1158bec967810ac18106aecbec0de03d77b87196 100644 (file)
@@ -51,6 +51,9 @@
 #ifndef _PATH_SSHD_SESSION
 #define _PATH_SSHD_SESSION             "/usr/libexec/sshd-session"
 #endif
+#ifndef _PATH_SSHD_AUTH
+#define _PATH_SSHD_AUTH                        "/usr/libexec/sshd-auth"
+#endif
 
 /*
  * The process id of the daemon listening for connections is saved here to
index 11045251c88525bf7186e0b0323432a79081dccb..7ebebf01110932725163737bdea631279851ed47 100644 (file)
@@ -45,8 +45,8 @@
  */
 
 struct ssh_sandbox {
-       struct monitor *monitor;
-       pid_t child_pid;
+       int m_recvfd;
+       int m_log_sendfd;
 };
 
 struct ssh_sandbox *
@@ -54,15 +54,10 @@ ssh_sandbox_init(struct monitor *monitor)
 {
        struct ssh_sandbox *box;
 
-       /*
-        * Strictly, we don't need to maintain any state here but we need
-        * to return non-NULL to satisfy the API.
-        */
        debug3("%s: preparing capsicum sandbox", __func__);
        box = xcalloc(1, sizeof(*box));
-       box->monitor = monitor;
-       box->child_pid = 0;
-
+       box->m_recvfd = monitor->m_recvfd;
+       box->m_log_sendfd = monitor->m_log_sendfd;
        return box;
 }
 
@@ -112,17 +107,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
 
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-       debug3("%s: finished", __func__);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       box->child_pid = child_pid;
-}
-
 #endif /* SANDBOX_CAPSICUM */
index 59b4d286eea54d62a094e5dab4017682509b45b6..08f4315b035c1fc88ea2dacfe0310bb4f5f0946c 100644 (file)
@@ -37,7 +37,7 @@
 /* Darwin/OS X sandbox */
 
 struct ssh_sandbox {
-       pid_t child_pid;
+       int junk;
 };
 
 struct ssh_sandbox *
@@ -51,8 +51,6 @@ ssh_sandbox_init(struct monitor *monitor)
         */
        debug3("%s: preparing Darwin sandbox", __func__);
        box = xcalloc(1, sizeof(*box));
-       box->child_pid = 0;
-
        return box;
 }
 
@@ -83,17 +81,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
                        __func__, strerror(errno));
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-       debug3("%s: finished", __func__);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       box->child_pid = child_pid;
-}
-
 #endif /* SANDBOX_DARWIN */
index d4cb9188b61dfd89fc3877863c85a56c63ded35c..6055eb86aa734e7de03eb58d2f926fe4188f627d 100644 (file)
@@ -57,16 +57,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
        /* Nothing to do here */
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       /* Nothing to do here */
-}
-
 #endif /* SANDBOX_NULL */
index 302f1cfedd3dab43e7f53870b37515f0ad6970b7..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 (file)
@@ -1,77 +0,0 @@
-/* $OpenBSD: sandbox-pledge.c,v 1.2 2020/10/18 11:32:01 djm Exp $ */
-/*
- * Copyright (c) 2015 Theo de Raadt <deraadt@openbsd.org>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-#include "includes.h"
-
-#ifdef SANDBOX_PLEDGE
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/syscall.h>
-#include <sys/socket.h>
-#include <sys/wait.h>
-
-#include <errno.h>
-#include <limits.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <pwd.h>
-
-#include "log.h"
-#include "ssh-sandbox.h"
-#include "xmalloc.h"
-
-struct ssh_sandbox {
-       pid_t child_pid;
-};
-
-struct ssh_sandbox *
-ssh_sandbox_init(struct monitor *m)
-{
-       struct ssh_sandbox *box;
-
-       debug3_f("preparing pledge sandbox");
-       box = xcalloc(1, sizeof(*box));
-       box->child_pid = 0;
-
-       return box;
-}
-
-void
-ssh_sandbox_child(struct ssh_sandbox *box)
-{
-       if (pledge("stdio", NULL) == -1)
-               fatal_f("pledge()");
-}
-
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-       debug3_f("finished");
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       box->child_pid = child_pid;
-       /* Nothing to do here */
-}
-
-#endif /* SANDBOX_PLEDGE */
index 26c61d26481700527ec76403ba19b8fbda0b402b..6bb4e56aa28381142269344f7ebebbebf6cf210e 100644 (file)
@@ -37,7 +37,7 @@
 /* Minimal sandbox that sets zero nfiles, nprocs and filesize rlimits */
 
 struct ssh_sandbox {
-       pid_t child_pid;
+       int junk;
 };
 
 struct ssh_sandbox *
@@ -51,8 +51,6 @@ ssh_sandbox_init(struct monitor *monitor)
         */
        debug3_f("preparing rlimit sandbox");
        box = xcalloc(1, sizeof(*box));
-       box->child_pid = 0;
-
        return box;
 }
 
@@ -80,17 +78,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
 #endif
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-       debug3_f("finished");
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       box->child_pid = child_pid;
-}
-
 #endif /* SANDBOX_RLIMIT */
index 23b40b6435678666205d1ded69f223f68d73bf6b..b31062c2b56cc51bb80c75dabc87839b25e9c608 100644 (file)
@@ -430,7 +430,7 @@ static const struct sock_fprog preauth_program = {
 };
 
 struct ssh_sandbox {
-       pid_t child_pid;
+       int junk;
 };
 
 struct ssh_sandbox *
@@ -444,8 +444,6 @@ ssh_sandbox_init(struct monitor *monitor)
         */
        debug3("%s: preparing seccomp filter sandbox", __func__);
        box = xcalloc(1, sizeof(*box));
-       box->child_pid = 0;
-
        return box;
 }
 
@@ -527,17 +525,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
                    "PR_SET_NO_NEW_PRIVS failed", __func__);
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       free(box);
-       debug3("%s: finished", __func__);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       box->child_pid = child_pid;
-}
-
 #endif /* SANDBOX_SECCOMP_FILTER */
index 56ddb9a9942a0622410b14587a720572ff2a054f..0b88c71245c19fc37a9142bfb6c715102b38cfd5 100644 (file)
@@ -97,18 +97,4 @@ ssh_sandbox_child(struct ssh_sandbox *box)
                fatal("setppriv: %s", strerror(errno));
 }
 
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       priv_freeset(box->pset);
-       box->pset = NULL;
-       free(box);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       /* Nothing to do here */
-}
-
 #endif /* SANDBOX_SOLARIS */
index e61d581aedbabba9fb9a99f24820bd6768474701..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 (file)
@@ -1,218 +0,0 @@
-/* $OpenBSD: sandbox-systrace.c,v 1.18 2015/10/02 01:39:26 deraadt Exp $ */
-/*
- * Copyright (c) 2011 Damien Miller <djm@mindrot.org>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-#include "includes.h"
-
-#ifdef SANDBOX_SYSTRACE
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/syscall.h>
-#include <sys/socket.h>
-#include <sys/wait.h>
-
-#include <dev/systrace.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "atomicio.h"
-#include "log.h"
-#include "ssh-sandbox.h"
-#include "xmalloc.h"
-
-struct sandbox_policy {
-       int syscall;
-       int action;
-};
-
-/* Permitted syscalls in preauth. Unlisted syscalls get SYSTR_POLICY_KILL */
-static const struct sandbox_policy preauth_policy[] = {
-       { SYS_exit, SYSTR_POLICY_PERMIT },
-#ifdef SYS_kbind
-       { SYS_kbind, SYSTR_POLICY_PERMIT },
-#endif
-
-       { SYS_getpid, SYSTR_POLICY_PERMIT },
-       { SYS_getpgid, SYSTR_POLICY_PERMIT },
-       { SYS_clock_gettime, SYSTR_POLICY_PERMIT },
-       { SYS_gettimeofday, SYSTR_POLICY_PERMIT },
-       { SYS_nanosleep, SYSTR_POLICY_PERMIT },
-       { SYS_sigprocmask, SYSTR_POLICY_PERMIT },
-
-#ifdef SYS_getentropy
-       /* OpenBSD 5.6 and newer use getentropy(2) to seed arc4random(3). */
-       { SYS_getentropy, SYSTR_POLICY_PERMIT },
-#else
-       /* Previous releases used sysctl(3)'s kern.arnd variable. */
-       { SYS___sysctl, SYSTR_POLICY_PERMIT },
-#endif
-#ifdef SYS_sendsyslog
-       { SYS_sendsyslog, SYSTR_POLICY_PERMIT },
-#endif
-
-       { SYS_madvise, SYSTR_POLICY_PERMIT },
-       { SYS_mmap, SYSTR_POLICY_PERMIT },
-       { SYS_mprotect, SYSTR_POLICY_PERMIT },
-       { SYS_mquery, SYSTR_POLICY_PERMIT },
-       { SYS_munmap, SYSTR_POLICY_PERMIT },
-
-       { SYS_poll, SYSTR_POLICY_PERMIT },
-       { SYS_select, SYSTR_POLICY_PERMIT },
-       { SYS_read, SYSTR_POLICY_PERMIT },
-       { SYS_write, SYSTR_POLICY_PERMIT },
-       { SYS_shutdown, SYSTR_POLICY_PERMIT },
-       { SYS_close, SYSTR_POLICY_PERMIT },
-
-       { SYS_open, SYSTR_POLICY_NEVER },
-
-       { -1, -1 }
-};
-
-struct ssh_sandbox {
-       int systrace_fd;
-       pid_t child_pid;
-       void (*osigchld)(int);
-};
-
-struct ssh_sandbox *
-ssh_sandbox_init(struct monitor *monitor)
-{
-       struct ssh_sandbox *box;
-
-       debug3("%s: preparing systrace sandbox", __func__);
-       box = xcalloc(1, sizeof(*box));
-       box->systrace_fd = -1;
-       box->child_pid = 0;
-       box->osigchld = ssh_signal(SIGCHLD, SIG_IGN);
-
-       return box;
-}
-
-void
-ssh_sandbox_child(struct ssh_sandbox *box)
-{
-       debug3("%s: ready", __func__);
-       ssh_signal(SIGCHLD, box->osigchld);
-       if (kill(getpid(), SIGSTOP) != 0)
-               fatal("%s: kill(%d, SIGSTOP)", __func__, getpid());
-       debug3("%s: started", __func__);
-}
-
-static void
-ssh_sandbox_parent(struct ssh_sandbox *box, pid_t child_pid,
-    const struct sandbox_policy *allowed_syscalls)
-{
-       int dev_systrace, i, j, found, status;
-       pid_t pid;
-       struct systrace_policy policy;
-
-       /* Wait for the child to send itself a SIGSTOP */
-       debug3("%s: wait for child %ld", __func__, (long)child_pid);
-       do {
-               pid = waitpid(child_pid, &status, WUNTRACED);
-       } while (pid == -1 && errno == EINTR);
-       ssh_signal(SIGCHLD, box->osigchld);
-       if (!WIFSTOPPED(status)) {
-               if (WIFSIGNALED(status))
-                       fatal("%s: child terminated with signal %d",
-                           __func__, WTERMSIG(status));
-               if (WIFEXITED(status))
-                       fatal("%s: child exited with status %d",
-                           __func__, WEXITSTATUS(status));
-               fatal("%s: child not stopped", __func__);
-       }
-       debug3("%s: child %ld stopped", __func__, (long)child_pid);
-       box->child_pid = child_pid;
-
-       /* Set up systracing of child */
-       if ((dev_systrace = open("/dev/systrace", O_RDONLY)) == -1)
-               fatal("%s: open(\"/dev/systrace\"): %s", __func__,
-                   strerror(errno));
-       if (ioctl(dev_systrace, STRIOCCLONE, &box->systrace_fd) == -1)
-               fatal("%s: ioctl(STRIOCCLONE, %d): %s", __func__,
-                   dev_systrace, strerror(errno));
-       close(dev_systrace);
-       debug3("%s: systrace attach, fd=%d", __func__, box->systrace_fd);
-       if (ioctl(box->systrace_fd, STRIOCATTACH, &child_pid) == -1)
-               fatal("%s: ioctl(%d, STRIOCATTACH, %d): %s", __func__,
-                   box->systrace_fd, child_pid, strerror(errno));
-
-       /* Allocate and assign policy */
-       memset(&policy, 0, sizeof(policy));
-       policy.strp_op = SYSTR_POLICY_NEW;
-       policy.strp_maxents = SYS_MAXSYSCALL;
-       if (ioctl(box->systrace_fd, STRIOCPOLICY, &policy) == -1)
-               fatal("%s: ioctl(%d, STRIOCPOLICY (new)): %s", __func__,
-                   box->systrace_fd, strerror(errno));
-
-       policy.strp_op = SYSTR_POLICY_ASSIGN;
-       policy.strp_pid = box->child_pid;
-       if (ioctl(box->systrace_fd, STRIOCPOLICY, &policy) == -1)
-               fatal("%s: ioctl(%d, STRIOCPOLICY (assign)): %s",
-                   __func__, box->systrace_fd, strerror(errno));
-
-       /* Set per-syscall policy */
-       for (i = 0; i < SYS_MAXSYSCALL; i++) {
-               found = 0;
-               for (j = 0; allowed_syscalls[j].syscall != -1; j++) {
-                       if (allowed_syscalls[j].syscall == i) {
-                               found = 1;
-                               break;
-                       }
-               }
-               policy.strp_op = SYSTR_POLICY_MODIFY;
-               policy.strp_code = i;
-               policy.strp_policy = found ?
-                   allowed_syscalls[j].action : SYSTR_POLICY_KILL;
-               if (found)
-                       debug3("%s: policy: enable syscall %d", __func__, i);
-               if (ioctl(box->systrace_fd, STRIOCPOLICY, &policy) == -1)
-                       fatal("%s: ioctl(%d, STRIOCPOLICY (modify)): %s",
-                           __func__, box->systrace_fd, strerror(errno));
-       }
-
-       /* Signal the child to start running */
-       debug3("%s: start child %ld", __func__, (long)child_pid);
-       if (kill(box->child_pid, SIGCONT) != 0)
-               fatal("%s: kill(%d, SIGCONT)", __func__, box->child_pid);
-}
-
-void
-ssh_sandbox_parent_finish(struct ssh_sandbox *box)
-{
-       /* Closing this before the child exits will terminate it */
-       close(box->systrace_fd);
-
-       free(box);
-       debug3("%s: finished", __func__);
-}
-
-void
-ssh_sandbox_parent_preauth(struct ssh_sandbox *box, pid_t child_pid)
-{
-       ssh_sandbox_parent(box, child_pid, preauth_policy);
-}
-
-#endif /* SANDBOX_SYSTRACE */
index dd774f46817c911a4bf6fe0b6cfb358f2167e9f6..2abf2846a2c7132be0d3155c3367964e313f1f3b 100644 (file)
@@ -214,6 +214,7 @@ initialize_server_options(ServerOptions *options)
        options->num_channel_timeouts = 0;
        options->unused_connection_timeout = -1;
        options->sshd_session_path = NULL;
+       options->sshd_auth_path = NULL;
        options->refuse_connection = -1;
 }
 
@@ -493,6 +494,8 @@ fill_default_server_options(ServerOptions *options)
                options->unused_connection_timeout = 0;
        if (options->sshd_session_path == NULL)
                options->sshd_session_path = xstrdup(_PATH_SSHD_SESSION);
+       if (options->sshd_auth_path == NULL)
+               options->sshd_auth_path = xstrdup(_PATH_SSHD_AUTH);
        if (options->refuse_connection == -1)
                options->refuse_connection = 0;
 
@@ -577,7 +580,7 @@ typedef enum {
        sAllowStreamLocalForwarding, sFingerprintHash, sDisableForwarding,
        sExposeAuthInfo, sRDomain, sPubkeyAuthOptions, sSecurityKeyProvider,
        sRequiredRSASize, sChannelTimeout, sUnusedConnectionTimeout,
-       sSshdSessionPath, sRefuseConnection,
+       sSshdSessionPath, sSshdAuthPath, sRefuseConnection,
        sDeprecated, sIgnore, sUnsupported
 } ServerOpCodes;
 
@@ -745,6 +748,7 @@ static struct {
        { "channeltimeout", sChannelTimeout, SSHCFG_ALL },
        { "unusedconnectiontimeout", sUnusedConnectionTimeout, SSHCFG_ALL },
        { "sshdsessionpath", sSshdSessionPath, SSHCFG_GLOBAL },
+       { "sshdauthpath", sSshdAuthPath, SSHCFG_GLOBAL },
        { "refuseconnection", sRefuseConnection, SSHCFG_ALL },
        { NULL, sBadOption, 0 }
 };
@@ -2703,6 +2707,10 @@ process_server_config_line_depth(ServerOptions *options, char *line,
                charptr = &options->sshd_session_path;
                goto parse_filename;
 
+       case sSshdAuthPath:
+               charptr = &options->sshd_auth_path;
+               goto parse_filename;
+
        case sRefuseConnection:
                intptr = &options->refuse_connection;
                multistate_ptr = multistate_flag;
@@ -3288,6 +3296,7 @@ dump_config(ServerOptions *o)
        dump_cfg_string(sRDomain, o->routing_domain);
 #endif
        dump_cfg_string(sSshdSessionPath, o->sshd_session_path);
+       dump_cfg_string(sSshdAuthPath, o->sshd_auth_path);
        dump_cfg_string(sPerSourcePenaltyExemptList, o->per_source_penalty_exempt);
 
        /* string arguments requiring a lookup */
index 5089bc9ea77e35c382a9c6052d2ac6257857abc5..9beb90fae3da6951fa2a7f2211f4322312a76488 100644 (file)
@@ -249,6 +249,7 @@ typedef struct {
        int     unused_connection_timeout;
 
        char   *sshd_session_path;
+       char   *sshd_auth_path;
 
        int     refuse_connection;
 }       ServerOptions;
index c9415114db94f2b7bd6ea483665f53d7b36a6d87..41fdcf7a95d581aca3d5d5a84fab1369edb00522 100644 (file)
--- a/session.c
+++ b/session.c
@@ -1510,8 +1510,7 @@ do_child(struct ssh *ssh, Session *s, const char *command)
 
        sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
 
-       /* remove hostkey from the child's memory */
-       destroy_sensitive_data();
+       /* remove keys from memory */
        ssh_packet_clear_keys(ssh);
 
        /* Force a password change */
@@ -2145,10 +2144,6 @@ session_signal_req(struct ssh *ssh, Session *s)
                    signame, s->forced ? "forced-command" : "subsystem");
                goto out;
        }
-       if (mm_is_monitor()) {
-               error_f("session signalling requires privilege separation");
-               goto out;
-       }
 
        debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig);
        temporarily_use_uid(s->pw);
index bd5fd83722a0dc2d79e116e182549c97445407c2..3b74840266bcd2ed776653749f82520be0dfe5c8 100644 (file)
@@ -20,5 +20,3 @@ struct ssh_sandbox;
 
 struct ssh_sandbox *ssh_sandbox_init(struct monitor *);
 void ssh_sandbox_child(struct ssh_sandbox *);
-void ssh_sandbox_parent_finish(struct ssh_sandbox *);
-void ssh_sandbox_parent_preauth(struct ssh_sandbox *, pid_t);
diff --git a/sshd-auth.c b/sshd-auth.c
new file mode 100644 (file)
index 0000000..5774706
--- /dev/null
@@ -0,0 +1,861 @@
+/* $OpenBSD$ */
+/*
+ * SSH2 implementation:
+ * Privilege Separation:
+ *
+ * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
+ * Copyright (c) 2002 Niels Provos.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "includes.h"
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+
+#include "openbsd-compat/sys-tree.h"
+#include "openbsd-compat/sys-queue.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <paths.h>
+#include <pwd.h>
+#include <grp.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <limits.h>
+
+#ifdef WITH_OPENSSL
+#include <openssl/bn.h>
+#include <openssl/evp.h>
+#endif
+
+#include "xmalloc.h"
+#include "ssh.h"
+#include "ssh2.h"
+#include "sshpty.h"
+#include "packet.h"
+#include "log.h"
+#include "sshbuf.h"
+#include "misc.h"
+#include "match.h"
+#include "servconf.h"
+#include "uidswap.h"
+#include "compat.h"
+#include "cipher.h"
+#include "digest.h"
+#include "sshkey.h"
+#include "kex.h"
+#include "authfile.h"
+#include "pathnames.h"
+#include "atomicio.h"
+#include "canohost.h"
+#include "hostfile.h"
+#include "auth.h"
+#include "authfd.h"
+#include "msg.h"
+#include "dispatch.h"
+#include "channels.h"
+#include "session.h"
+#include "monitor.h"
+#ifdef GSSAPI
+#include "ssh-gss.h"
+#endif
+#include "monitor_wrap.h"
+#include "auth-options.h"
+#include "version.h"
+#include "ssherr.h"
+#include "sk-api.h"
+#include "srclimit.h"
+#include "ssh-sandbox.h"
+#include "dh.h"
+
+/* Privsep fds */
+#define PRIVSEP_MONITOR_FD             (STDERR_FILENO + 1)
+#define PRIVSEP_LOG_FD                 (STDERR_FILENO + 2)
+#define PRIVSEP_MIN_FREE_FD            (STDERR_FILENO + 3)
+
+extern char *__progname;
+
+/* Server configuration options. */
+ServerOptions options;
+
+/* Name of the server configuration file. */
+char *config_file_name = _PATH_SERVER_CONFIG_FILE;
+
+/*
+ * Debug mode flag.  This can be set on the command line.  If debug
+ * mode is enabled, extra debugging output will be sent to the system
+ * log, the daemon will not go to background, and will exit after processing
+ * the first connection.
+ */
+int debug_flag = 0;
+
+/* Flag indicating that the daemon is being started from inetd. */
+static int inetd_flag = 0;
+
+/* Saved arguments to main(). */
+static char **saved_argv;
+
+/* Daemon's agent connection */
+int auth_sock = -1;
+static int have_agent = 0;
+
+u_int          num_hostkeys;
+struct sshkey  **host_pubkeys;         /* all public host keys */
+struct sshkey  **host_certificates;    /* all public host certificates */
+
+/* record remote hostname or ip */
+u_int utmp_len = HOST_NAME_MAX+1;
+
+/* variables used for privilege separation */
+struct monitor *pmonitor = NULL;
+int privsep_is_preauth = 1;
+static int privsep_chroot = 1;
+
+/* global connection state and authentication contexts */
+Authctxt *the_authctxt = NULL;
+struct ssh *the_active_state;
+
+/* global key/cert auth options. XXX move to permanent ssh->authctxt? */
+struct sshauthopt *auth_opts = NULL;
+
+/* sshd_config buffer */
+struct sshbuf *cfg;
+
+/* Included files from the configuration file */
+struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
+
+/* message to be displayed after login */
+struct sshbuf *loginmsg;
+
+/* Prototypes for various functions defined later in this file. */
+static void do_ssh2_kex(struct ssh *);
+
+/* Unprivileged user */
+struct passwd *privsep_pw = NULL;
+
+/* XXX stub */
+int
+mm_is_monitor(void)
+{
+       return 0;
+}
+
+static void
+privsep_child_demote(void)
+{
+       gid_t gidset[1];
+#ifndef HAVE_PLEDGE
+       struct ssh_sandbox *box = NULL;
+
+       if ((box = ssh_sandbox_init(pmonitor)) == NULL)
+               fatal_f("ssh_sandbox_init failed");
+#endif
+       /* Demote the child */
+       if (privsep_chroot) {
+               /* Change our root directory */
+               if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
+                       fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
+                           strerror(errno));
+               if (chdir("/") == -1)
+                       fatal("chdir(\"/\"): %s", strerror(errno));
+
+               /*
+                * Drop our privileges
+                * NB. Can't use setusercontext() after chroot.
+                */
+               debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
+                   (u_int)privsep_pw->pw_gid);
+               gidset[0] = privsep_pw->pw_gid;
+               if (setgroups(1, gidset) == -1)
+                       fatal("setgroups: %.100s", strerror(errno));
+               permanently_set_uid(privsep_pw);
+       }
+
+       /* sandbox ourselves */
+#ifdef HAVE_PLEDGE
+       if (pledge("stdio", NULL) == -1)
+               fatal_f("pledge()");
+#else
+       ssh_sandbox_child(box);
+#endif
+}
+
+static void
+append_hostkey_type(struct sshbuf *b, const char *s)
+{
+       int r;
+
+       if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
+               debug3_f("%s key not permitted by HostkeyAlgorithms", s);
+               return;
+       }
+       if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
+               fatal_fr(r, "sshbuf_putf");
+}
+
+static char *
+list_hostkey_types(void)
+{
+       struct sshbuf *b;
+       struct sshkey *key;
+       char *ret;
+       u_int i;
+
+       if ((b = sshbuf_new()) == NULL)
+               fatal_f("sshbuf_new failed");
+       for (i = 0; i < options.num_host_key_files; i++) {
+               key = host_pubkeys[i];
+               if (key == NULL)
+                       continue;
+               switch (key->type) {
+               case KEY_RSA:
+                       /* for RSA we also support SHA2 signatures */
+                       append_hostkey_type(b, "rsa-sha2-512");
+                       append_hostkey_type(b, "rsa-sha2-256");
+                       /* FALLTHROUGH */
+               case KEY_DSA:
+               case KEY_ECDSA:
+               case KEY_ED25519:
+               case KEY_ECDSA_SK:
+               case KEY_ED25519_SK:
+               case KEY_XMSS:
+                       append_hostkey_type(b, sshkey_ssh_name(key));
+                       break;
+               }
+               /* If the private key has a cert peer, then list that too */
+               key = host_certificates[i];
+               if (key == NULL)
+                       continue;
+               switch (key->type) {
+               case KEY_RSA_CERT:
+                       /* for RSA we also support SHA2 signatures */
+                       append_hostkey_type(b,
+                           "rsa-sha2-512-cert-v01@openssh.com");
+                       append_hostkey_type(b,
+                           "rsa-sha2-256-cert-v01@openssh.com");
+                       /* FALLTHROUGH */
+               case KEY_DSA_CERT:
+               case KEY_ECDSA_CERT:
+               case KEY_ED25519_CERT:
+               case KEY_ECDSA_SK_CERT:
+               case KEY_ED25519_SK_CERT:
+               case KEY_XMSS_CERT:
+                       append_hostkey_type(b, sshkey_ssh_name(key));
+                       break;
+               }
+       }
+       if ((ret = sshbuf_dup_string(b)) == NULL)
+               fatal_f("sshbuf_dup_string failed");
+       sshbuf_free(b);
+       debug_f("%s", ret);
+       return ret;
+}
+
+struct sshkey *
+get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
+{
+       u_int i;
+       struct sshkey *key;
+
+       for (i = 0; i < options.num_host_key_files; i++) {
+               switch (type) {
+               case KEY_RSA_CERT:
+               case KEY_DSA_CERT:
+               case KEY_ECDSA_CERT:
+               case KEY_ED25519_CERT:
+               case KEY_ECDSA_SK_CERT:
+               case KEY_ED25519_SK_CERT:
+               case KEY_XMSS_CERT:
+                       key = host_certificates[i];
+                       break;
+               default:
+                       key = host_pubkeys[i];
+                       break;
+               }
+               if (key == NULL || key->type != type)
+                       continue;
+               switch (type) {
+               case KEY_ECDSA:
+               case KEY_ECDSA_SK:
+               case KEY_ECDSA_CERT:
+               case KEY_ECDSA_SK_CERT:
+                       if (key->ecdsa_nid != nid)
+                               continue;
+                       /* FALLTHROUGH */
+               default:
+                       return key;
+               }
+       }
+       return NULL;
+}
+
+/* XXX remove */
+struct sshkey *
+get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
+{
+       return NULL;
+}
+
+/* XXX remove */
+struct sshkey *
+get_hostkey_by_index(int ind)
+{
+       return NULL;
+}
+
+struct sshkey *
+get_hostkey_public_by_index(int ind, struct ssh *ssh)
+{
+       if (ind < 0 || (u_int)ind >= options.num_host_key_files)
+               return (NULL);
+       return host_pubkeys[ind];
+}
+
+int
+get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
+{
+       u_int i;
+
+       for (i = 0; i < options.num_host_key_files; i++) {
+               if (sshkey_is_cert(key)) {
+                       if (key == host_certificates[i] ||
+                           (compare && host_certificates[i] &&
+                           sshkey_equal(key, host_certificates[i])))
+                               return (i);
+               } else {
+                       if (key == host_pubkeys[i] ||
+                           (compare && host_pubkeys[i] &&
+                           sshkey_equal(key, host_pubkeys[i])))
+                               return (i);
+               }
+       }
+       return (-1);
+}
+
+static void
+usage(void)
+{
+       fprintf(stderr, "%s, %s\n", SSH_VERSION, SSH_OPENSSL_VERSION);
+       fprintf(stderr,
+"usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
+"            [-E log_file] [-f config_file] [-g login_grace_time]\n"
+"            [-h host_key_file] [-o option] [-p port] [-u len]\n"
+       );
+       exit(1);
+}
+
+static void
+parse_hostkeys(struct sshbuf *hostkeys)
+{
+       int r;
+       u_int num_keys = 0;
+       struct sshkey *k;
+       const u_char *cp;
+       size_t len;
+
+       while (sshbuf_len(hostkeys) != 0) {
+               if (num_keys > 2048)
+                       fatal_f("too many hostkeys");
+               host_pubkeys = xrecallocarray(host_pubkeys,
+                   num_keys, num_keys + 1, sizeof(*host_pubkeys));
+               host_certificates = xrecallocarray(host_certificates,
+                   num_keys, num_keys + 1, sizeof(*host_certificates));
+               /* public key */
+               k = NULL;
+               if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
+                       fatal_fr(r, "extract pubkey");
+               if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
+                       fatal_fr(r, "parse pubkey");
+               host_pubkeys[num_keys] = k;
+               if (k)
+                       debug2_f("key %u: %s", num_keys, sshkey_ssh_name(k));
+               /* certificate */
+               k = NULL;
+               if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
+                       fatal_fr(r, "extract pubkey");
+               if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
+                       fatal_fr(r, "parse pubkey");
+               host_certificates[num_keys] = k;
+               if (k)
+                       debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k));
+               num_keys++;
+       }
+       num_hostkeys = num_keys;
+}
+
+static void
+recv_privsep_state(struct ssh *ssh, struct sshbuf *conf,
+    uint64_t *timing_secretp)
+{
+       struct sshbuf *hostkeys;
+
+       debug3_f("begin");
+
+       mm_get_state(ssh, &includes, conf, NULL, timing_secretp,
+           &hostkeys, NULL, NULL, NULL, NULL);
+       parse_hostkeys(hostkeys);
+
+       sshbuf_free(hostkeys);
+
+       debug3_f("done");
+}
+
+/*
+ * Main program for the daemon.
+ */
+int
+main(int ac, char **av)
+{
+       struct ssh *ssh = NULL;
+       extern char *optarg;
+       extern int optind;
+       int r, opt, have_key = 0;
+       int sock_in = -1, sock_out = -1, rexeced_flag = 0;
+       char *line, *logfile = NULL;
+       u_int i;
+       mode_t new_umask;
+       Authctxt *authctxt;
+       struct connection_info *connection_info = NULL;
+       sigset_t sigmask;
+       uint64_t timing_secret = 0;
+
+       closefrom(PRIVSEP_MIN_FREE_FD);
+       sigemptyset(&sigmask);
+       sigprocmask(SIG_SETMASK, &sigmask, NULL);
+
+       /* Save argv. */
+       saved_argv = av;
+
+       /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
+       sanitise_stdfd();
+
+       /* Initialize configuration options to their default values. */
+       initialize_server_options(&options);
+
+       /* Parse command-line arguments. */
+       while ((opt = getopt(ac, av,
+           "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
+               switch (opt) {
+               case '4':
+                       options.address_family = AF_INET;
+                       break;
+               case '6':
+                       options.address_family = AF_INET6;
+                       break;
+               case 'f':
+                       config_file_name = optarg;
+                       break;
+               case 'c':
+                       servconf_add_hostcert("[command-line]", 0,
+                           &options, optarg);
+                       break;
+               case 'd':
+                       if (debug_flag == 0) {
+                               debug_flag = 1;
+                               options.log_level = SYSLOG_LEVEL_DEBUG1;
+                       } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
+                               options.log_level++;
+                       break;
+               case 'D':
+                       /* ignore */
+                       break;
+               case 'E':
+                       logfile = optarg;
+                       /* FALLTHROUGH */
+               case 'e':
+                       /* ignore */
+                       break;
+               case 'i':
+                       inetd_flag = 1;
+                       break;
+               case 'r':
+                       /* ignore */
+                       break;
+               case 'R':
+                       rexeced_flag = 1;
+                       break;
+               case 'Q':
+                       /* ignored */
+                       break;
+               case 'q':
+                       options.log_level = SYSLOG_LEVEL_QUIET;
+                       break;
+               case 'b':
+                       /* protocol 1, ignored */
+                       break;
+               case 'p':
+                       options.ports_from_cmdline = 1;
+                       if (options.num_ports >= MAX_PORTS) {
+                               fprintf(stderr, "too many ports.\n");
+                               exit(1);
+                       }
+                       options.ports[options.num_ports++] = a2port(optarg);
+                       if (options.ports[options.num_ports-1] <= 0) {
+                               fprintf(stderr, "Bad port number.\n");
+                               exit(1);
+                       }
+                       break;
+               case 'g':
+                       if ((options.login_grace_time = convtime(optarg)) == -1) {
+                               fprintf(stderr, "Invalid login grace time.\n");
+                               exit(1);
+                       }
+                       break;
+               case 'k':
+                       /* protocol 1, ignored */
+                       break;
+               case 'h':
+                       servconf_add_hostkey("[command-line]", 0,
+                           &options, optarg, 1);
+                       break;
+               case 't':
+               case 'T':
+               case 'G':
+                       fatal("test/dump modes not supported");
+                       break;
+               case 'C':
+                       connection_info = server_get_connection_info(ssh, 0, 0);
+                       if (parse_server_match_testspec(connection_info,
+                           optarg) == -1)
+                               exit(1);
+                       break;
+               case 'u':
+                       utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
+                       if (utmp_len > HOST_NAME_MAX+1) {
+                               fprintf(stderr, "Invalid utmp length.\n");
+                               exit(1);
+                       }
+                       break;
+               case 'o':
+                       line = xstrdup(optarg);
+                       if (process_server_config_line(&options, line,
+                           "command-line", 0, NULL, NULL, &includes) != 0)
+                               exit(1);
+                       free(line);
+                       break;
+               case 'V':
+                       fprintf(stderr, "%s, %s\n",
+                           SSH_VERSION, SSH_OPENSSL_VERSION);
+                       exit(0);
+               default:
+                       usage();
+                       break;
+               }
+       }
+
+       if (!rexeced_flag)
+               fatal("sshd-auth should not be executed directly");
+
+#ifdef WITH_OPENSSL
+       OpenSSL_add_all_algorithms();
+#endif
+
+       /* If requested, redirect the logs to the specified logfile. */
+       if (logfile != NULL) {
+               char *cp, pid_s[32];
+
+               snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
+               cp = percent_expand(logfile,
+                   "p", pid_s,
+                   "P", "sshd-auth",
+                   (char *)NULL);
+               log_redirect_stderr_to(cp);
+               free(cp);
+       }
+
+       log_init(__progname,
+           options.log_level == SYSLOG_LEVEL_NOT_SET ?
+           SYSLOG_LEVEL_INFO : options.log_level,
+           options.log_facility == SYSLOG_FACILITY_NOT_SET ?
+           SYSLOG_FACILITY_AUTH : options.log_facility, 1);
+
+       /* XXX can't use monitor_init(); it makes fds */
+       pmonitor = xcalloc(1, sizeof(*pmonitor));
+       pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
+       pmonitor->m_recvfd = PRIVSEP_MONITOR_FD;
+       pmonitor->m_log_sendfd = PRIVSEP_LOG_FD;
+       set_log_handler(mm_log_handler, pmonitor);
+
+       /* Check that there are no remaining arguments. */
+       if (optind < ac) {
+               fprintf(stderr, "Extra argument %s.\n", av[optind]);
+               exit(1);
+       }
+
+       debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
+
+       /* Connection passed by stdin/out */
+       if (inetd_flag) {
+               /*
+                * NB. must be different fd numbers for the !socket case,
+                * as packet_connection_is_on_socket() depends on this.
+                */
+               sock_in = dup(STDIN_FILENO);
+               sock_out = dup(STDOUT_FILENO);
+       } else {
+               /* rexec case; accept()ed socket in ancestor listener */
+               sock_in = sock_out = dup(STDIN_FILENO);
+       }
+
+       if (stdfd_devnull(1, 1, 0) == -1)
+               error("stdfd_devnull failed");
+       debug("network sockets: %d, %d", sock_in, sock_out);
+
+       /*
+        * Register our connection.  This turns encryption off because we do
+        * not have a key.
+        */
+       if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
+               fatal("Unable to create connection");
+       the_active_state = ssh;
+       ssh_packet_set_server(ssh);
+       pmonitor->m_pkex = &ssh->kex;
+
+       /* Fetch our configuration */
+       if ((cfg = sshbuf_new()) == NULL)
+               fatal("sshbuf_new config buf failed");
+       setproctitle("%s", "[session-auth early]");
+       recv_privsep_state(ssh, cfg, &timing_secret);
+       parse_server_config(&options, "rexec", cfg, &includes, NULL, 1);
+       /* Fill in default values for those options not explicitly set. */
+       fill_default_server_options(&options);
+       options.timing_secret = timing_secret; /* XXX eliminate from unpriv */
+
+       /* Store privilege separation user for later use if required. */
+       privsep_chroot = (getuid() == 0 || geteuid() == 0);
+       if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
+               if (privsep_chroot || options.kerberos_authentication)
+                       fatal("Privilege separation user %s does not exist",
+                           SSH_PRIVSEP_USER);
+       } else {
+               privsep_pw = pwcopy(privsep_pw);
+               freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
+               privsep_pw->pw_passwd = xstrdup("*");
+       }
+       endpwent();
+
+#ifdef WITH_OPENSSL
+       if (options.moduli_file != NULL)
+               dh_set_moduli_file(options.moduli_file);
+#endif
+
+       if (options.host_key_agent) {
+               if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
+                       setenv(SSH_AUTHSOCKET_ENV_NAME,
+                           options.host_key_agent, 1);
+               if ((r = ssh_get_authentication_socket(NULL)) == 0)
+                       have_agent = 1;
+               else
+                       error_r(r, "Could not connect to agent \"%s\"",
+                           options.host_key_agent);
+       }
+
+       if (options.num_host_key_files != num_hostkeys) {
+               fatal("internal error: hostkeys confused (config %u recvd %u)",
+                   options.num_host_key_files, num_hostkeys);
+       }
+
+       for (i = 0; i < options.num_host_key_files; i++) {
+               if (host_pubkeys[i] != NULL) {
+                       have_key = 1;
+                       break;
+               }
+       }
+       if (!have_key)
+               fatal("internal error: recieved no hostkeys");
+
+       /* Ensure that umask disallows at least group and world write */
+       new_umask = umask(0077) | 0022;
+       (void) umask(new_umask);
+
+       /* Initialize the log (it is reinitialized below in case we forked). */
+       log_init(__progname, options.log_level, options.log_facility, 1);
+       set_log_handler(mm_log_handler, pmonitor);
+       for (i = 0; i < options.num_log_verbose; i++)
+               log_verbose_add(options.log_verbose[i]);
+
+       /*
+        * Chdir to the root directory so that the current disk can be
+        * unmounted if desired.
+        */
+       if (chdir("/") == -1)
+               error("chdir(\"/\"): %s", strerror(errno));
+
+       /* This is the child authenticating a new connection. */
+       setproctitle("%s", "[session-auth]");
+
+       /* Executed child processes don't need these. */
+       fcntl(sock_out, F_SETFD, FD_CLOEXEC);
+       fcntl(sock_in, F_SETFD, FD_CLOEXEC);
+
+       ssh_signal(SIGPIPE, SIG_IGN);
+       ssh_signal(SIGALRM, SIG_DFL);
+       ssh_signal(SIGHUP, SIG_DFL);
+       ssh_signal(SIGTERM, SIG_DFL);
+       ssh_signal(SIGQUIT, SIG_DFL);
+       ssh_signal(SIGCHLD, SIG_DFL);
+
+       /* Prepare the channels layer */
+       channel_init_channels(ssh);
+       channel_set_af(ssh, options.address_family);
+       server_process_channel_timeouts(ssh);
+       server_process_permitopen(ssh);
+
+       ssh_packet_set_nonblocking(ssh);
+
+       /* allocate authentication context */
+       authctxt = xcalloc(1, sizeof(*authctxt));
+       ssh->authctxt = authctxt;
+
+       /* XXX global for cleanup, access from other modules */
+       the_authctxt = authctxt;
+
+       /* Set default key authentication options */
+       if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
+               fatal("allocation failed");
+
+       /* prepare buffer to collect messages to display to user after login */
+       if ((loginmsg = sshbuf_new()) == NULL)
+               fatal("sshbuf_new loginmsg failed");
+       auth_debug_reset();
+
+       /* Enable challenge-response authentication for privilege separation */
+       privsep_challenge_enable();
+
+#ifdef GSSAPI
+       /* Cache supported mechanism OIDs for later use */
+       ssh_gssapi_prepare_supported_oids();
+#endif
+
+       privsep_child_demote();
+
+       /* perform the key exchange */
+       /* authenticate user and start session */
+       do_ssh2_kex(ssh);
+       do_authentication2(ssh);
+
+       /*
+        * The unprivileged child now transfers the current keystate and exits.
+        */
+       mm_send_keystate(ssh, pmonitor);
+       ssh_packet_clear_keys(ssh);
+       exit(0);
+}
+
+int
+sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
+    struct sshkey *pubkey, u_char **signature, size_t *slenp,
+    const u_char *data, size_t dlen, const char *alg)
+{
+       if (privkey) {
+               if (mm_sshkey_sign(ssh, privkey, signature, slenp,
+                   data, dlen, alg, options.sk_provider, NULL,
+                   ssh->compat) < 0)
+                       fatal_f("privkey sign failed");
+       } else {
+               if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
+                   data, dlen, alg, options.sk_provider, NULL,
+                   ssh->compat) < 0)
+                       fatal_f("pubkey sign failed");
+       }
+       return 0;
+}
+
+/* SSH2 key exchange */
+static void
+do_ssh2_kex(struct ssh *ssh)
+{
+       char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
+       const char *compression = NULL;
+       struct kex *kex;
+       int r;
+
+       if (options.rekey_limit || options.rekey_interval)
+               ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
+                   options.rekey_interval);
+
+       if (options.compression == COMP_NONE)
+               compression = "none";
+       hkalgs = list_hostkey_types();
+
+       kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
+           options.ciphers, options.macs, compression, hkalgs);
+
+       free(hkalgs);
+
+       /* start key exchange */
+       if ((r = kex_setup(ssh, myproposal)) != 0)
+               fatal_r(r, "kex_setup");
+       kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos);
+       kex = ssh->kex;
+
+#ifdef WITH_OPENSSL
+       kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
+       kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
+       kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
+       kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
+       kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
+       kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
+       kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
+# ifdef OPENSSL_HAS_ECC
+       kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
+# endif /* OPENSSL_HAS_ECC */
+#endif /* WITH_OPENSSL */
+       kex->kex[KEX_C25519_SHA256] = kex_gen_server;
+       kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
+       kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
+       kex->load_host_public_key=&get_hostkey_public_by_type;
+       kex->load_host_private_key=&get_hostkey_private_by_type;
+       kex->host_key_index=&get_hostkey_index;
+       kex->sign = sshd_hostkey_sign;
+
+       ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
+       kex_proposal_free_entries(myproposal);
+
+#ifdef DEBUG_KEXDH
+       /* send 1st encrypted/maced/compressed message */
+       if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
+           (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
+           (r = sshpkt_send(ssh)) != 0 ||
+           (r = ssh_packet_write_wait(ssh)) != 0)
+               fatal_fr(r, "send test");
+#endif
+       debug("KEX done");
+}
+
+/* server specific fatal cleanup */
+void
+cleanup_exit(int i)
+{
+       _exit(i);
+}
index 4b79b9ba6ab473a86b1379862ffd8ca26f8abbd8..8eea088484e4edb1f99652754e8dd2372dc70241 100644 (file)
 #include "ssh-gss.h"
 #endif
 #include "monitor_wrap.h"
-#include "ssh-sandbox.h"
 #include "auth-options.h"
 #include "version.h"
 #include "ssherr.h"
 #define REEXEC_CONFIG_PASS_FD          (STDERR_FILENO + 3)
 #define REEXEC_MIN_FREE_FD             (STDERR_FILENO + 4)
 
+/* Privsep fds */
+#define PRIVSEP_MONITOR_FD             (STDERR_FILENO + 1)
+#define PRIVSEP_LOG_FD                 (STDERR_FILENO + 2)
+#define PRIVSEP_MIN_FREE_FD            (STDERR_FILENO + 3)
+
 extern char *__progname;
 
 /* Server configuration options. */
@@ -193,7 +197,17 @@ struct sshbuf *loginmsg;
 /* Prototypes for various functions defined later in this file. */
 void destroy_sensitive_data(void);
 void demote_sensitive_data(void);
-static void do_ssh2_kex(struct ssh *);
+
+/* XXX reduce to stub once postauth split */
+int
+mm_is_monitor(void)
+{
+       /*
+        * m_pid is only set in the privileged part, and
+        * points to the unprivileged child.
+        */
+       return (pmonitor && pmonitor->m_pid > 0);
+}
 
 /*
  * Signal handler for the alarm after the login grace period has expired.
@@ -283,41 +297,41 @@ reseed_prngs(void)
        explicit_bzero(rnd, sizeof(rnd));
 }
 
-static void
-privsep_preauth_child(void)
+struct sshbuf *
+pack_hostkeys(void)
 {
-       gid_t gidset[1];
-
-       /* Enable challenge-response authentication for privilege separation */
-       privsep_challenge_enable();
-
-#ifdef GSSAPI
-       /* Cache supported mechanism OIDs for later use */
-       ssh_gssapi_prepare_supported_oids();
-#endif
-
-       reseed_prngs();
+       struct sshbuf *keybuf = NULL, *hostkeys = NULL;
+       int r;
+       u_int i;
 
-       /* Demote the private keys to public keys. */
-       demote_sensitive_data();
+       if ((hostkeys = sshbuf_new()) == NULL)
+               fatal_f("sshbuf_new failed");
 
-       /* Demote the child */
-       if (privsep_chroot) {
-               /* Change our root directory */
-               if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
-                       fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
-                           strerror(errno));
-               if (chdir("/") == -1)
-                       fatal("chdir(\"/\"): %s", strerror(errno));
-
-               /* Drop our privileges */
-               debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
-                   (u_int)privsep_pw->pw_gid);
-               gidset[0] = privsep_pw->pw_gid;
-               if (setgroups(1, gidset) == -1)
-                       fatal("setgroups: %.100s", strerror(errno));
-               permanently_set_uid(privsep_pw);
+       /* pack hostkeys into a string. Empty key slots get empty strings */
+       for (i = 0; i < options.num_host_key_files; i++) {
+               /* public key */
+               if (sensitive_data.host_pubkeys[i] != NULL) {
+                       if ((r = sshkey_puts(sensitive_data.host_pubkeys[i],
+                           hostkeys)) != 0)
+                               fatal_fr(r, "compose hostkey public");
+               } else {
+                       if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
+                               fatal_fr(r, "compose hostkey empty public");
+               }
+               /* cert */
+               if (sensitive_data.host_certificates[i] != NULL) {
+                       if ((r = sshkey_puts(
+                           sensitive_data.host_certificates[i],
+                           hostkeys)) != 0)
+                               fatal_fr(r, "compose host cert");
+               } else {
+                       if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0)
+                               fatal_fr(r, "compose host cert empty");
+               }
        }
+
+       sshbuf_free(keybuf);
+       return hostkeys;
 }
 
 static int
@@ -325,18 +339,15 @@ privsep_preauth(struct ssh *ssh)
 {
        int status, r;
        pid_t pid;
-       struct ssh_sandbox *box = NULL;
 
        /* Set up unprivileged child process to deal with network data */
        pmonitor = monitor_init();
        /* Store a pointer to the kex for later rekeying */
        pmonitor->m_pkex = &ssh->kex;
 
-       box = ssh_sandbox_init(pmonitor);
-       pid = fork();
-       if (pid == -1) {
+       if ((pid = fork()) == -1)
                fatal("fork of unprivileged child failed");
-       else if (pid != 0) {
+       else if (pid != 0) {
                debug2("Network child is on pid %ld", (long)pid);
 
                pmonitor->m_pid = pid;
@@ -347,8 +358,6 @@ privsep_preauth(struct ssh *ssh)
                                have_agent = 0;
                        }
                }
-               if (box != NULL)
-                       ssh_sandbox_parent_preauth(box, pid);
                monitor_child_preauth(ssh, pmonitor);
 
                /* Wait for the child's exit status */
@@ -367,23 +376,46 @@ privsep_preauth(struct ssh *ssh)
                } else if (WIFSIGNALED(status))
                        fatal_f("preauth child terminated by signal %d",
                            WTERMSIG(status));
-               if (box != NULL)
-                       ssh_sandbox_parent_finish(box);
                return 1;
        } else {
                /* child */
                close(pmonitor->m_sendfd);
                close(pmonitor->m_log_recvfd);
 
-               /* Arrange for logging to be sent to the monitor */
-               set_log_handler(mm_log_handler, pmonitor);
-
-               privsep_preauth_child();
-               setproctitle("%s", "[net]");
-               if (box != NULL)
-                       ssh_sandbox_child(box);
+               /*
+                * Arrange unpriv-preauth child process fds:
+                * 0, 1 network socket
+                * 2 optional stderr
+                * 3 reserved
+                * 4 monitor message socket
+                * 5 monitor logging socket
+                *
+                * We know that the monitor sockets will have fds > 4 because
+                * of the reserved fds in main()
+                */
 
-               return 0;
+               if (ssh_packet_get_connection_in(ssh) != STDIN_FILENO &&
+                   dup2(ssh_packet_get_connection_in(ssh), STDIN_FILENO) == -1)
+                       fatal("dup2 stdin failed: %s", strerror(errno));
+               if (ssh_packet_get_connection_out(ssh) != STDOUT_FILENO &&
+                   dup2(ssh_packet_get_connection_out(ssh),
+                   STDOUT_FILENO) == -1)
+                       fatal("dup2 stdout failed: %s", strerror(errno));
+               /* leave stderr as-is */
+               log_redirect_stderr_to(NULL); /* dup can clobber log fd */
+               if (pmonitor->m_recvfd != PRIVSEP_MONITOR_FD &&
+                   dup2(pmonitor->m_recvfd, PRIVSEP_MONITOR_FD) == -1)
+                       fatal("dup2 monitor fd: %s", strerror(errno));
+               if (pmonitor->m_log_sendfd != PRIVSEP_LOG_FD &&
+                   dup2(pmonitor->m_log_sendfd, PRIVSEP_LOG_FD) == -1)
+                       fatal("dup2 log fd: %s", strerror(errno));
+               closefrom(PRIVSEP_MIN_FREE_FD);
+
+               saved_argv[0] = options.sshd_auth_path;
+               execv(options.sshd_auth_path, saved_argv);
+
+               fatal_f("exec of %s failed: %s",
+                   options.sshd_auth_path, strerror(errno));
        }
 }
 
@@ -445,79 +477,6 @@ privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
        ssh_packet_set_authenticated(ssh);
 }
 
-static void
-append_hostkey_type(struct sshbuf *b, const char *s)
-{
-       int r;
-
-       if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
-               debug3_f("%s key not permitted by HostkeyAlgorithms", s);
-               return;
-       }
-       if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
-               fatal_fr(r, "sshbuf_putf");
-}
-
-static char *
-list_hostkey_types(void)
-{
-       struct sshbuf *b;
-       struct sshkey *key;
-       char *ret;
-       u_int i;
-
-       if ((b = sshbuf_new()) == NULL)
-               fatal_f("sshbuf_new failed");
-       for (i = 0; i < options.num_host_key_files; i++) {
-               key = sensitive_data.host_keys[i];
-               if (key == NULL)
-                       key = sensitive_data.host_pubkeys[i];
-               if (key == NULL)
-                       continue;
-               switch (key->type) {
-               case KEY_RSA:
-                       /* for RSA we also support SHA2 signatures */
-                       append_hostkey_type(b, "rsa-sha2-512");
-                       append_hostkey_type(b, "rsa-sha2-256");
-                       /* FALLTHROUGH */
-               case KEY_DSA:
-               case KEY_ECDSA:
-               case KEY_ED25519:
-               case KEY_ECDSA_SK:
-               case KEY_ED25519_SK:
-               case KEY_XMSS:
-                       append_hostkey_type(b, sshkey_ssh_name(key));
-                       break;
-               }
-               /* If the private key has a cert peer, then list that too */
-               key = sensitive_data.host_certificates[i];
-               if (key == NULL)
-                       continue;
-               switch (key->type) {
-               case KEY_RSA_CERT:
-                       /* for RSA we also support SHA2 signatures */
-                       append_hostkey_type(b,
-                           "rsa-sha2-512-cert-v01@openssh.com");
-                       append_hostkey_type(b,
-                           "rsa-sha2-256-cert-v01@openssh.com");
-                       /* FALLTHROUGH */
-               case KEY_DSA_CERT:
-               case KEY_ECDSA_CERT:
-               case KEY_ED25519_CERT:
-               case KEY_ECDSA_SK_CERT:
-               case KEY_ED25519_SK_CERT:
-               case KEY_XMSS_CERT:
-                       append_hostkey_type(b, sshkey_ssh_name(key));
-                       break;
-               }
-       }
-       if ((ret = sshbuf_dup_string(b)) == NULL)
-               fatal_f("sshbuf_dup_string failed");
-       sshbuf_free(b);
-       debug_f("%s", ret);
-       return ret;
-}
-
 static struct sshkey *
 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
 {
@@ -871,7 +830,7 @@ main(int ac, char **av)
        struct ssh *ssh = NULL;
        extern char *optarg;
        extern int optind;
-       int r, opt, on = 1, remote_port;
+       int devnull, r, opt, on = 1, remote_port;
        int sock_in = -1, sock_out = -1, rexeced_flag = 0, have_key = 0;
        const char *remote_ip, *rdomain;
        char *line, *laddr, *logfile = NULL;
@@ -1035,6 +994,14 @@ main(int ac, char **av)
 
        closefrom(REEXEC_MIN_FREE_FD);
 
+       /* Reserve fds we'll need later for reexec things */
+       if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1)
+               fatal("open %s: %s", _PATH_DEVNULL, strerror(errno));
+       while (devnull < PRIVSEP_MIN_FREE_FD) {
+               if ((devnull = dup(devnull)) == -1)
+                       fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno));
+       }
+
        seed_rng();
 
        /* If requested, redirect the logs to the specified logfile. */
@@ -1068,7 +1035,9 @@ main(int ac, char **av)
                fatal("sshbuf_new config buf failed");
        setproctitle("%s", "[rexeced]");
        recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg, &timing_secret);
-       close(REEXEC_CONFIG_PASS_FD);
+       /* close the fd, but keep the slot reserved */
+       if (dup2(devnull, REEXEC_CONFIG_PASS_FD) == -1)
+               fatal("dup2 devnull->config fd: %s", strerror(errno));
        parse_server_config(&options, "rexec", cfg, &includes, NULL, 1);
        /* Fill in default values for those options not explicitly set. */
        fill_default_server_options(&options);
@@ -1087,9 +1056,13 @@ main(int ac, char **av)
        }
        endpwent();
 
-       if (!debug_flag) {
-               startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
-               close(REEXEC_STARTUP_PIPE_FD);
+       if (!debug_flag && !inetd_flag) {
+               if ((startup_pipe = dup(REEXEC_STARTUP_PIPE_FD)) == -1)
+                       fatal("internal error: no startup pipe");
+               /* close the fd, but keep the slot reserved */
+               if (dup2(devnull, REEXEC_STARTUP_PIPE_FD) == -1)
+                       fatal("dup2 devnull->startup fd: %s", strerror(errno));
+
                /*
                 * Signal parent that this child is at a point where
                 * they can go away if they have a SIGHUP pending.
@@ -1311,22 +1284,11 @@ main(int ac, char **av)
                fatal("sshbuf_new loginmsg failed");
        auth_debug_reset();
 
-       if (privsep_preauth(ssh) == 1)
-               goto authenticated;
+       if (privsep_preauth(ssh) != 1)
+               fatal("privsep_preauth failed");
 
-       /* perform the key exchange */
-       /* authenticate user and start session */
-       do_ssh2_kex(ssh);
-       do_authentication2(ssh);
+       /* Now user is authenticated */
 
-       /*
-        * The unprivileged child now transfers the current keystate and exits.
-        */
-       mm_send_keystate(ssh, pmonitor);
-       ssh_packet_clear_keys(ssh);
-       exit(0);
-
- authenticated:
        /*
         * Cancel the alarm we set to limit the time taken for
         * authentication.
@@ -1423,68 +1385,6 @@ sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
        return 0;
 }
 
-/* SSH2 key exchange */
-static void
-do_ssh2_kex(struct ssh *ssh)
-{
-       char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
-       const char *compression = NULL;
-       struct kex *kex;
-       int r;
-
-       if (options.rekey_limit || options.rekey_interval)
-               ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
-                   options.rekey_interval);
-
-       if (options.compression == COMP_NONE)
-               compression = "none";
-       hkalgs = list_hostkey_types();
-
-       kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
-           options.ciphers, options.macs, compression, hkalgs);
-
-       free(hkalgs);
-
-       /* start key exchange */
-       if ((r = kex_setup(ssh, myproposal)) != 0)
-               fatal_r(r, "kex_setup");
-       kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos);
-       kex = ssh->kex;
-
-#ifdef WITH_OPENSSL
-       kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
-       kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
-       kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
-       kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
-       kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
-       kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
-       kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
- #ifdef OPENSSL_HAS_ECC
-       kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
- #endif
-#endif
-       kex->kex[KEX_C25519_SHA256] = kex_gen_server;
-       kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
-       kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
-       kex->load_host_public_key=&get_hostkey_public_by_type;
-       kex->load_host_private_key=&get_hostkey_private_by_type;
-       kex->host_key_index=&get_hostkey_index;
-       kex->sign = sshd_hostkey_sign;
-
-       ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
-       kex_proposal_free_entries(myproposal);
-
-#ifdef DEBUG_KEXDH
-       /* send 1st encrypted/maced/compressed message */
-       if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
-           (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
-           (r = sshpkt_send(ssh)) != 0 ||
-           (r = ssh_packet_write_wait(ssh)) != 0)
-               fatal_fr(r, "send test");
-#endif
-       debug("KEX done");
-}
-
 /* server specific fatal cleanup */
 void
 cleanup_exit(int i)
diff --git a/sshd.c b/sshd.c
index df76dc78c75317600659b5d143399eafcef11b22..dda8d9b77ead01d14aa826730ea64959f474541c 100644 (file)
--- a/sshd.c
+++ b/sshd.c
@@ -1664,6 +1664,13 @@ main(int ac, char **av)
                fatal("%s does not exist or is not executable", rexec_argv[0]);
        debug3("using %s for re-exec", rexec_argv[0]);
 
+       /* Ensure that the privsep binary exists now too. */
+       if (stat(options.sshd_auth_path, &sb) != 0 ||
+           !(sb.st_mode & (S_IXOTH|S_IXUSR))) {
+               fatal("%s does not exist or is not executable",
+                   options.sshd_auth_path);
+       }
+
        listener_proctitle = prepare_proctitle(ac, av);
 
        /* Ensure that umask disallows at least group and world write */