From 646e7cf3d7e7d4231c2d97d27c09fe5fe1d749e2 Mon Sep 17 00:00:00 2001 From: Damien Miller Date: Wed, 13 Mar 2002 12:47:54 +1100 Subject: Import of Niels Provos' 20020312 ssh-complete.diff PAM, Cygwin and OSF SIA will not work for sure --- Makefile.in | 6 +- auth.h | 4 +- auth1.c | 30 ++- auth2.c | 119 ++++++---- bufaux.c | 2 + cipher.c | 40 ++++ cipher.h | 2 + compress.c | 4 +- kex.c | 4 + kex.h | 1 + kexdh.c | 13 +- kexgex.c | 19 +- key.c | 43 ++++ key.h | 1 + monitor.c | 656 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ monitor.h | 57 +++++ monitor_fdpass.c | 89 ++++++++ monitor_fdpass.h | 32 +++ monitor_mm.c | 329 ++++++++++++++++++++++++++++ monitor_mm.h | 64 ++++++ monitor_wrap.c | 538 +++++++++++++++++++++++++++++++++++++++++++++ monitor_wrap.h | 99 +++++++++ packet.c | 106 ++++++++- packet.h | 7 + servconf.c | 15 ++ session.c | 53 ++--- session.h | 28 +++ sshd.c | 173 ++++++++++++++- 28 files changed, 2425 insertions(+), 109 deletions(-) create mode 100644 monitor.c create mode 100644 monitor.h create mode 100644 monitor_fdpass.c create mode 100644 monitor_fdpass.h create mode 100644 monitor_mm.c create mode 100644 monitor_mm.h create mode 100644 monitor_wrap.c create mode 100644 monitor_wrap.h diff --git a/Makefile.in b/Makefile.in index b58250aae..38c1d381c 100644 --- a/Makefile.in +++ b/Makefile.in @@ -1,4 +1,4 @@ -# $Id: Makefile.in,v 1.197 2002/02/26 19:24:22 mouring Exp $ +# $Id: Makefile.in,v 1.198 2002/03/13 01:47:54 djm Exp $ prefix=@prefix@ exec_prefix=@exec_prefix@ @@ -50,11 +50,11 @@ INSTALL_SSH_RAND_HELPER=@INSTALL_SSH_RAND_HELPER@ TARGETS=ssh$(EXEEXT) sshd$(EXEEXT) ssh-add$(EXEEXT) ssh-keygen$(EXEEXT) ssh-keyscan${EXEEXT} ssh-agent$(EXEEXT) scp$(EXEEXT) ssh-rand-helper${EXEEXT} $(SFTP_PROGS) -LIBSSH_OBJS=atomicio.o authfd.o authfile.o bufaux.o buffer.o canohost.o channels.o cipher.o compat.o compress.o crc32.o deattack.o dh.o dispatch.o fatal.o mac.o hostfile.o key.o kex.o kexdh.o kexgex.o log.o match.o misc.o mpaux.o nchan.o packet.o radix.o rijndael.o entropy.o readpass.o rsa.o scard.o ssh-dss.o ssh-rsa.o tildexpand.o ttymodes.o uidswap.o uuencode.o xmalloc.o +LIBSSH_OBJS=atomicio.o authfd.o authfile.o bufaux.o buffer.o canohost.o channels.o cipher.o compat.o compress.o crc32.o deattack.o dh.o dispatch.o fatal.o mac.o hostfile.o key.o kex.o kexdh.o kexgex.o log.o match.o misc.o monitor_fdpass.c monitor_wrap.c mpaux.o nchan.o packet.o radix.o rijndael.o entropy.o readpass.o rsa.o scard.o ssh-dss.o ssh-rsa.o tildexpand.o ttymodes.o uidswap.o uuencode.o xmalloc.o SSHOBJS= ssh.o sshconnect.o sshconnect1.o sshconnect2.o sshtty.o readconf.o clientloop.o -SSHDOBJS= sshd.o auth.o auth1.o auth2.o auth-chall.o auth2-chall.o auth-rhosts.o auth-options.o auth-krb4.o auth-pam.o auth2-pam.o auth-passwd.o auth-rsa.o auth-rh-rsa.o auth-sia.o sshpty.o sshlogin.o loginrec.o servconf.o serverloop.o md5crypt.o session.o groupaccess.o auth-skey.o auth-bsdauth.o +SSHDOBJS= sshd.o auth.o auth1.o auth2.o auth-chall.o auth2-chall.o auth-rhosts.o auth-options.o auth-krb4.o auth-pam.o auth2-pam.o auth-passwd.o auth-rsa.o auth-rh-rsa.o auth-sia.o monitor.c monitor_mm.c sshpty.o sshlogin.o loginrec.o servconf.o serverloop.o md5crypt.o session.o groupaccess.o auth-skey.o auth-bsdauth.o MANPAGES = scp.1.out ssh-add.1.out ssh-agent.1.out ssh-keygen.1.out ssh-keyscan.1.out ssh.1.out sshd.8.out sftp-server.8.out sftp.1.out MANPAGES_IN = scp.1 ssh-add.1 ssh-agent.1 ssh-keygen.1 ssh-keyscan.1 ssh.1 sshd.8 sftp-server.8 sftp.1 diff --git a/auth.h b/auth.h index c7175405d..9b5b19f6c 100644 --- a/auth.h +++ b/auth.h @@ -121,8 +121,8 @@ void krb5_cleanup_proc(void *authctxt); #include "auth-pam.h" #include "auth2-pam.h" -void do_authentication(void); -void do_authentication2(void); +Authctxt *do_authentication(void); +Authctxt *do_authentication2(void); Authctxt *authctxt_new(void); void auth_log(Authctxt *, int, char *, char *); diff --git a/auth1.c b/auth1.c index c2d99895f..c52f63897 100644 --- a/auth1.c +++ b/auth1.c @@ -26,8 +26,13 @@ RCSID("$OpenBSD: auth1.c,v 1.35 2002/02/03 17:53:25 markus Exp $"); #include "session.h" #include "misc.h" #include "uidswap.h" +#include "monitor.h" +#include "monitor_wrap.h" /* import */ +extern int use_privsep; +extern int mm_recvfd; + extern ServerOptions options; /* @@ -355,12 +360,13 @@ do_authloop(Authctxt *authctxt) * Performs authentication of an incoming connection. Session key has already * been exchanged and encryption is enabled. */ -void +Authctxt * do_authentication(void) { Authctxt *authctxt; - struct passwd *pw; + struct passwd *pw = NULL, *pwent; u_int ulen; + int allowed; char *p, *user, *style = NULL; /* Get the name of the user that we wish to log in as. */ @@ -382,17 +388,26 @@ do_authentication(void) authctxt->style = style; /* Verify that the user is a valid user. */ - pw = getpwnam(user); - if (pw && allowed_user(pw)) { + if (!use_privsep) { + pwent = getpwnam(user); + allowed = pwent ? allowed_user(pwent) : 0; + } else + pwent = mm_getpwnamallow(mm_recvfd, user, &allowed); + if (pwent && allowed) { authctxt->valid = 1; - pw = pwcopy(pw); + pw = pwcopy(pwent); } else { debug("do_authentication: illegal user %s", user); pw = NULL; } + /* Free memory */ + if (use_privsep) + pwfree(pwent); + authctxt->pw = pw; - setproctitle("%s", pw ? user : "unknown"); + setproctitle("%s%s", use_privsep ? " [net]" : "", + pw ? user : "unknown"); #ifdef USE_PAM start_pam(pw == NULL ? "NOUSER" : user); @@ -418,6 +433,5 @@ do_authentication(void) packet_send(); packet_write_wait(); - /* Perform session preparation. */ - do_authenticated(authctxt); + return (authctxt); } diff --git a/auth2.c b/auth2.c index f2a801ecc..f661f8d7c 100644 --- a/auth2.c +++ b/auth2.c @@ -51,8 +51,13 @@ RCSID("$OpenBSD: auth2.c,v 1.85 2002/02/24 19:14:59 markus Exp $"); #include "hostfile.h" #include "canohost.h" #include "match.h" +#include "monitor.h" +#include "monitor_wrap.h" /* import */ +extern int use_privsep; +extern int mm_recvfd; + extern ServerOptions options; extern u_char *session_id2; extern int session_id2_len; @@ -75,8 +80,8 @@ static void input_userauth_request(int, u_int32_t, void *); /* helper */ static Authmethod *authmethod_lookup(const char *); static char *authmethods_get(void); -static int user_key_allowed(struct passwd *, Key *); -static int hostbased_key_allowed(struct passwd *, const char *, char *, Key *); +int user_key_allowed(struct passwd *, Key *); +int hostbased_key_allowed(struct passwd *, const char *, char *, Key *); /* auth */ static void userauth_banner(void); @@ -109,7 +114,7 @@ Authmethod authmethods[] = { * loop until authctxt->success == TRUE */ -void +Authctxt * do_authentication2(void) { Authctxt *authctxt = authctxt_new(); @@ -125,7 +130,8 @@ do_authentication2(void) dispatch_init(&dispatch_protocol_error); dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request); dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt); - do_authenticated(authctxt); + + return(authctxt); } static void @@ -182,10 +188,15 @@ input_userauth_request(int type, u_int32_t seq, void *ctxt) *style++ = 0; if (authctxt->attempt++ == 0) { - /* setup auth context */ + /* setup auth context */ + int allowed; struct passwd *pw = NULL; - pw = getpwnam(user); - if (pw && allowed_user(pw) && strcmp(service, "ssh-connection")==0) { + if (!use_privsep) { + pw = getpwnam(user); + allowed = pw ? allowed_user(pw) : 0; + } else + pw = mm_getpwnamallow(mm_recvfd, user, &allowed); + if (pw && allowed && strcmp(service, "ssh-connection")==0) { authctxt->pw = pwcopy(pw); authctxt->valid = 1; debug2("input_userauth_request: setting up authctxt for %s", user); @@ -198,10 +209,18 @@ input_userauth_request(int type, u_int32_t seq, void *ctxt) start_pam("NOUSER"); #endif } - setproctitle("%s", pw ? user : "unknown"); + /* Free memory */ + if (use_privsep) + pwfree(pw); + + setproctitle("%s%s", use_privsep ? " [net]" : "", + pw ? user : "unknown"); authctxt->user = xstrdup(user); authctxt->service = xstrdup(service); authctxt->style = style ? xstrdup(style) : NULL; + + if (use_privsep) + mm_inform_authserv(mm_recvfd, service, style); } else if (strcmp(user, authctxt->user) != 0 || strcmp(service, authctxt->service) != 0) { packet_disconnect("Change of username or service not allowed: " @@ -313,6 +332,8 @@ done: static int userauth_none(Authctxt *authctxt) { + int res = 0; + /* disable method "none", only allowed one time */ Authmethod *m = authmethod_lookup("none"); if (m != NULL) @@ -322,18 +343,16 @@ userauth_none(Authctxt *authctxt) if (authctxt->valid == 0) return(0); - -#ifdef HAVE_CYGWIN - if (check_nt_auth(1, authctxt->pw) == 0) - return(0); + if (!authctxt->valid) + return (0); + if (use_privsep) +#if defined(USE_PAM) || defined(HAVE_OSF_SIA) +#error NOT IMPLEMENTED FOR PRIVSEP #endif -#ifdef USE_PAM - return auth_pam_password(authctxt->pw, ""); -#elif defined(HAVE_OSF_SIA) - return 0; -#else /* !HAVE_OSF_SIA && !USE_PAM */ - return auth_password(authctxt, ""); -#endif /* USE_PAM */ + res = mm_auth_password(mm_recvfd, ""); + else + res = auth_password(authctxt, ""); + return (res); } static int @@ -348,18 +367,16 @@ userauth_passwd(Authctxt *authctxt) log("password change not supported"); password = packet_get_string(&len); packet_check_eom(); - if (authctxt->valid && -#ifdef HAVE_CYGWIN - check_nt_auth(1, authctxt->pw) && + +#if defined(HAVE_CYGWIN) || defined(USE_PAM) || defined(HAVE_OSF_SIA) +#error NOT IMPLEMENTED FOR PRIVSEP #endif -#ifdef USE_PAM - auth_pam_password(authctxt->pw, password) == 1) -#elif defined(HAVE_OSF_SIA) - auth_sia_password(authctxt->user, password) == 1) -#else /* !USE_PAM && !HAVE_OSF_SIA */ - auth_password(authctxt, password) == 1) -#endif /* USE_PAM */ - authenticated = 1; + if (authctxt->valid) { + if (use_privsep) + authenticated = mm_auth_password(mm_recvfd, password); + else + authenticated = auth_password(authctxt, password); + } memset(password, 0, len); xfree(password); return authenticated; @@ -467,12 +484,23 @@ userauth_pubkey(Authctxt *authctxt) buffer_dump(&b); #endif /* test for correct signature */ - if (user_key_allowed(authctxt->pw, key) && - key_verify(key, sig, slen, buffer_ptr(&b), buffer_len(&b)) == 1) - authenticated = 1; + authenticated = 0; + if (use_privsep) { + if (mm_user_key_allowed(mm_recvfd, key) && + mm_key_verify(mm_recvfd, + MM_USERKEY, NULL, NULL, key, sig, slen, + buffer_ptr(&b), buffer_len(&b)) == 1) + authenticated = 1; + } else { + if (user_key_allowed(authctxt->pw, key) && + key_verify(key, sig, slen, buffer_ptr(&b), + buffer_len(&b)) == 1) + authenticated = 1; + } buffer_clear(&b); xfree(sig); } else { + int res = 0; debug("test whether pkalg/pkblob are acceptable"); packet_check_eom(); @@ -484,7 +512,11 @@ userauth_pubkey(Authctxt *authctxt) * if a user is not allowed to login. is this an * issue? -markus */ - if (user_key_allowed(authctxt->pw, key)) { + if (use_privsep) + res = mm_user_key_allowed(mm_recvfd, key); + else + res = user_key_allowed(authctxt->pw, key); + if (res) { packet_start(SSH2_MSG_USERAUTH_PK_OK); packet_put_string(pkalg, alen); packet_put_string(pkblob, blen); @@ -572,9 +604,18 @@ userauth_hostbased(Authctxt *authctxt) buffer_dump(&b); #endif /* test for allowed key and correct signature */ - if (hostbased_key_allowed(authctxt->pw, cuser, chost, key) && - key_verify(key, sig, slen, buffer_ptr(&b), buffer_len(&b)) == 1) - authenticated = 1; + authenticated = 0; + if (use_privsep) { + if (mm_hostbased_key_allowed(mm_recvfd, cuser, chost, key) && + mm_key_verify(mm_recvfd, MM_HOSTKEY, cuser, chost, key, + sig, slen, buffer_ptr(&b), buffer_len(&b)) == 1) + authenticated = 1; + } else { + if (hostbased_key_allowed(authctxt->pw, cuser, chost, key) && + key_verify(key, sig, slen, buffer_ptr(&b), + buffer_len(&b)) == 1) + authenticated = 1; + } buffer_clear(&b); done: @@ -730,7 +771,7 @@ user_key_allowed2(struct passwd *pw, Key *key, char *file) } /* check whether given key is in .ssh/authorized_keys* */ -static int +int user_key_allowed(struct passwd *pw, Key *key) { int success; @@ -750,7 +791,7 @@ user_key_allowed(struct passwd *pw, Key *key) } /* return 1 if given hostkey is allowed */ -static int +int hostbased_key_allowed(struct passwd *pw, const char *cuser, char *chost, Key *key) { diff --git a/bufaux.c b/bufaux.c index 23bc0c814..64b9a26e9 100644 --- a/bufaux.c +++ b/bufaux.c @@ -221,6 +221,8 @@ buffer_put_string(Buffer *buffer, const void *buf, u_int len) void buffer_put_cstring(Buffer *buffer, const char *s) { + if (s == NULL) + fatal("buffer_put_cstring: s == NULL"); buffer_put_string(buffer, s, strlen(s)); } diff --git a/cipher.c b/cipher.c index 9e8f42f5e..5ddf819c4 100644 --- a/cipher.c +++ b/cipher.c @@ -541,3 +541,43 @@ evp_rijndael(void) #endif return (&rijndal_cbc); } + +/* + * Exports an IV from the CipherContext required to export the key + * state back from the unprivileged child to the privileged parent + * process. + */ + +void +cipher_get_keyiv(CipherContext *cc, u_char *iv, u_int len) +{ + Cipher *c = cc->cipher; + u_char *civ = NULL; + int evplen; + + switch (c->number) { + case SSH_CIPHER_SSH2: + evplen = EVP_CIPHER_CTX_iv_length(&cc->evp); + if (evplen == 0) + return; + if (evplen != len) + fatal("%s: wrong iv length %d != %d", __FUNCTION__, + evplen, len); + + if (strncmp(c->name, "aes", 3) == 0) { + struct ssh_rijndael_ctx *aesc; + + aesc = EVP_CIPHER_CTX_get_app_data(&cc->evp); + if (aesc == NULL) + fatal("ssh_rijndael_cbc: no context"); + civ = aesc->r_iv; + } else { + civ = cc->evp.iv; + } + break; + default: + fatal("%s: bad cipher %d", __FUNCTION__, c->number); + } + memcpy(iv, civ, len); +} + diff --git a/cipher.h b/cipher.h index b3b0303c7..c7724469b 100644 --- a/cipher.h +++ b/cipher.h @@ -81,4 +81,6 @@ void cipher_cleanup(CipherContext *); void cipher_set_key_string(CipherContext *, Cipher *, const char *, int); u_int cipher_blocksize(Cipher *); u_int cipher_keylen(Cipher *); + +void cipher_get_keyiv(CipherContext *, u_char *, u_int); #endif /* CIPHER_H */ diff --git a/compress.c b/compress.c index 3badbf452..dec96ba55 100644 --- a/compress.c +++ b/compress.c @@ -19,8 +19,8 @@ RCSID("$OpenBSD: compress.c,v 1.17 2001/12/29 21:56:01 stevesk Exp $"); #include "zlib.h" #include "compress.h" -static z_stream incoming_stream; -static z_stream outgoing_stream; +z_stream incoming_stream; +z_stream outgoing_stream; static int compress_init_send_called = 0; static int compress_init_recv_called = 0; diff --git a/kex.c b/kex.c index bf8fd95b4..e5c0b0d00 100644 --- a/kex.c +++ b/kex.c @@ -43,6 +43,10 @@ RCSID("$OpenBSD: kex.c,v 1.47 2002/02/28 15:46:33 markus Exp $"); #define KEX_COOKIE_LEN 16 +/* Use privilege separation for sshd */ +int use_privsep; +int mm_recvfd; + /* prototype */ static void kex_kexinit_finish(Kex *); static void kex_choose_conf(Kex *); diff --git a/kex.h b/kex.h index 755bf332a..c99afaec0 100644 --- a/kex.h +++ b/kex.h @@ -111,6 +111,7 @@ struct Kex { char *server_version_string; int (*verify_host_key)(Key *); Key *(*load_host_key)(int); + int (*host_key_index)(Key *); }; Kex *kex_setup(char *[PROPOSAL_MAX]); diff --git a/kexdh.c b/kexdh.c index eaf497ca7..6256722ff 100644 --- a/kexdh.c +++ b/kexdh.c @@ -37,6 +37,12 @@ RCSID("$OpenBSD: kexdh.c,v 1.17 2002/02/28 15:46:33 markus Exp $"); #include "packet.h" #include "dh.h" #include "ssh2.h" +#include "monitor.h" +#include "monitor_wrap.h" + +/* Imports */ +extern int use_privsep; +extern int mm_recvfd; static u_char * kex_dh_hash( @@ -275,7 +281,12 @@ kexdh_server(Kex *kex) /* sign H */ /* XXX hashlen depends on KEX */ - key_sign(server_host_key, &signature, &slen, hash, 20); + if (use_privsep) + mm_key_sign(mm_recvfd, + kex->host_key_index(server_host_key), + &signature, &slen, hash, 20); + else + key_sign(server_host_key, &signature, &slen, hash, 20); /* destroy_sensitive_data(); */ diff --git a/kexgex.c b/kexgex.c index 61896e6ed..3c811f337 100644 --- a/kexgex.c +++ b/kexgex.c @@ -38,6 +38,12 @@ RCSID("$OpenBSD: kexgex.c,v 1.20 2002/02/28 15:46:33 markus Exp $"); #include "dh.h" #include "ssh2.h" #include "compat.h" +#include "monitor.h" +#include "monitor_wrap.h" + +/* Imports */ +extern int use_privsep; +extern int mm_recvfd; static u_char * kexgex_hash( @@ -296,7 +302,11 @@ kexgex_server(Kex *kex) fatal("DH_GEX_REQUEST, bad parameters: %d !< %d !< %d", min, nbits, max); - dh = choose_dh(min, nbits, max); + /* Contact privileged parent */ + if (use_privsep) + dh = mm_choose_dh(mm_recvfd, min, nbits, max); + else + dh = choose_dh(min, nbits, max); if (dh == NULL) packet_disconnect("Protocol error: no matching DH grp found"); @@ -379,7 +389,11 @@ kexgex_server(Kex *kex) /* sign H */ /* XXX hashlen depends on KEX */ - key_sign(server_host_key, &signature, &slen, hash, 20); + if (use_privsep) + mm_key_sign(mm_recvfd, kex->host_key_index(server_host_key), + &signature, &slen, hash, 20); + else + key_sign(server_host_key, &signature, &slen, hash, 20); /* destroy_sensitive_data(); */ @@ -390,6 +404,7 @@ kexgex_server(Kex *kex) packet_put_bignum2(dh->pub_key); /* f */ packet_put_string(signature, slen); packet_send(); + xfree(signature); xfree(server_host_key_blob); /* have keys, free DH */ diff --git a/key.c b/key.c index cda91571a..fb6bff95b 100644 --- a/key.c +++ b/key.c @@ -801,3 +801,46 @@ key_verify( break; } } + +/* Converts a private to a public key */ + +Key * +key_demote(Key *k) +{ + Key *pk; + + pk = xmalloc(sizeof(*pk)); + pk->type = k->type; + pk->flags = k->flags; + pk->dsa = NULL; + pk->rsa = NULL; + + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + if ((pk->rsa = RSA_new()) == NULL) + fatal("key_demote: RSA_new failed"); + if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL) + fatal("key_demote: BN_dup failed"); + break; + case KEY_DSA: + if ((pk->dsa = DSA_new()) == NULL) + fatal("key_demote: DSA_new failed"); + if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) + fatal("key_demote: BN_dup failed"); + break; + default: + fatal("key_free: bad key type %d", k->type); + break; + } + + return (pk); +} diff --git a/key.h b/key.h index a2257731a..bc8b3d06b 100644 --- a/key.h +++ b/key.h @@ -58,6 +58,7 @@ struct Key { Key *key_new(int); Key *key_new_private(int); void key_free(Key *); +Key *key_demote(Key *); int key_equal(Key *, Key *); char *key_fingerprint(Key *, enum fp_type, enum fp_rep); char *key_type(Key *); diff --git a/monitor.c b/monitor.c new file mode 100644 index 000000000..b85790271 --- /dev/null +++ b/monitor.c @@ -0,0 +1,656 @@ +/* + * Copyright 2001 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" +RCSID("$OpenBSD$"); + +#include + +#include "ssh.h" +#include "auth.h" +#include "kex.h" +#include "dh.h" +#include "zlib.h" +#include "packet.h" +#include "auth-options.h" +#include "sshpty.h" +#include "channels.h" +#include "session.h" +#include "log.h" +#include "monitor.h" +#include "monitor_mm.h" +#include "monitor_wrap.h" +#include "monitor_fdpass.h" +#include "xmalloc.h" +#include "misc.h" +#include "buffer.h" +#include "bufaux.h" + +/* Imports */ +extern Newkeys *current_keys[]; +extern z_stream incoming_stream; +extern z_stream outgoing_stream; +extern int compat20; +extern int mm_sendfd; + +/* State exported from the child */ + +struct { + z_stream incoming; + z_stream outgoing; + u_char *keyin; + u_int keyinlen; + u_char *keyout; + u_int keyoutlen; +} child_state; + +/* Prototype for authentication functions */ + +int hostbased_key_allowed(struct passwd *, const char *, char *, Key *); +int user_key_allowed(struct passwd *, Key *); +Key *get_hostkey_by_index(int); + +void session_pty_cleanup(void *); + +static Authctxt *authctxt; + +struct mon_table { + enum monitor_reqtype type; + int flags; + int (*f)(int, Buffer *); +}; + +#define MON_PROTOONE 0x0001 /* Used in protocol 1 */ +#define MON_PROTOTWO 0x0002 /* Used in protocol 2 */ +#define MON_AUTH 0x0004 /* Authentication Request */ + +#define MON_BOTH (MON_PROTOONE|MON_PROTOTWO) + +#define MON_PERMIT 0x1000 /* Request is permitted */ + +struct mon_table mon_dispatch_proto20[] = { + {MONITOR_REQ_MODULI, MON_PROTOTWO, mm_answer_moduli}, + {MONITOR_REQ_SIGN, MON_PROTOTWO, mm_answer_sign}, + {MONITOR_REQ_PWNAM, MON_BOTH, mm_answer_pwnamallow}, + {MONITOR_REQ_AUTHSERV, MON_BOTH, mm_answer_authserv}, + {MONITOR_REQ_AUTHPASSWORD, MON_BOTH | MON_AUTH, mm_answer_authpassword}, + {MONITOR_REQ_KEYALLOWED, MON_BOTH | MON_AUTH, mm_answer_keyallowed}, + {MONITOR_REQ_KEYVERIFY, MON_BOTH | MON_AUTH, mm_answer_keyverify}, + {0, 0, NULL} +}; + +struct mon_table mon_dispatch_postauth20[] = { + {MONITOR_REQ_MODULI, MON_PROTOTWO, mm_answer_moduli}, + {MONITOR_REQ_SIGN, MON_PROTOTWO, mm_answer_sign}, + {MONITOR_REQ_PTY, MON_BOTH, mm_answer_pty}, + {MONITOR_REQ_TERM, MON_BOTH, mm_answer_term}, + {0, 0, NULL} +}; + +struct mon_table mon_dispatch_proto15[] = { + {0, 0, NULL} +}; + +struct mon_table *mon_dispatch; + +/* Specifies if a certain message is allowed at the moment */ + +void +monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit) +{ + while (ent->f != NULL) { + if (ent->type == type) { + ent->flags &= ~MON_PERMIT; + ent->flags |= permit ? MON_PERMIT : 0; + return; + } + ent++; + } +} + +void +monitor_permit_authentications(int permit) +{ + struct mon_table *ent = mon_dispatch; + + while (ent->f != NULL) { + if (ent->flags & MON_AUTH) { + ent->flags &= ~MON_PERMIT; + ent->flags |= permit ? MON_PERMIT : 0; + } + ent++; + } +} + +#define FD_CLOSEONEXEC(x) do { \ + if (fcntl(x, F_SETFD, 1) == -1) \ + fatal("fcntl(%d, F_SETFD)", x); \ +} while (0) + +void +monitor_socketpair(int *pair) +{ + if (socketpair(PF_LOCAL, SOCK_STREAM, 0, pair) == -1) + fatal("%s: socketpair", __FUNCTION__); + FD_CLOSEONEXEC(pair[0]); + FD_CLOSEONEXEC(pair[1]); +} + +Authctxt * +monitor_child_preauth(int socket) +{ + debug3("preauth child monitor started"); + + if (compat20) { + mon_dispatch = mon_dispatch_proto20; + + /* Permit requests for moduli and signatures */ + monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); + monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); + } else + mon_dispatch = mon_dispatch_proto15; + + authctxt = authctxt_new(); + + /* The first few requests do not require asynchronous access */ + for (;;) { + if (monitor_read(socket, mon_dispatch)) + break; + } + + debug("%s: %s has been authenticated by privileged process", + __FUNCTION__, authctxt->user); + + if (compat20) { + mm_get_keystate(socket); + } else { + fatal("Use loose"); + } + + return (authctxt); +} + +void +monitor_child_postauth(int socket) +{ + if (compat20) { + mon_dispatch = mon_dispatch_postauth20; + + /* Permit requests for moduli and signatures */ + monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); + monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); + monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1); + + if (!no_pty_flag) + monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1); + } else + mon_dispatch = mon_dispatch_proto15; + + for (;;) { + if (monitor_read(socket, mon_dispatch)) + break; + } +} + +int +monitor_read(int socket, struct mon_table *ent) +{ + Buffer m; + int ret; + u_char type; + + buffer_init(&m); + + mm_request_receive(socket, &m); + type = buffer_get_char(&m); + + debug3("%s: checking request %d", __FUNCTION__, type); + + while (ent->f != NULL) { + if (ent->type == type) + break; + ent++; + } + + if (ent->f != NULL) { + if (!(ent->flags & MON_PERMIT)) + fatal("%s: unpermitted request %d", __FUNCTION__, + type); + ret = (*ent->f)(socket, &m); + buffer_free(&m); + return ret; + } + + fatal("%s: unsupported request: %d\n", __FUNCTION__, type); + + /* NOTREACHED */ + return (-1); +} + +int +mm_answer_moduli(int socket, Buffer *m) +{ + DH *dh; + int min, want, max; + + /* Turn off requests for moduli */ + monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 0); + + min = buffer_get_int(m); + want = buffer_get_int(m); + max = buffer_get_int(m); + + debug3("%s: got parameters: %d %d %d", + __FUNCTION__, min, want, max); + /* We need to check here, too, in case the child got corrupted */ + if (max < min || want < min || max < want) + fatal("%s: bad parameters: %d %d %d", + __FUNCTION__, min, want, max); + + buffer_clear(m); + + dh = choose_dh(min, want, max); + if (dh == NULL) { + buffer_put_char(m, 0); + return (0); + } else { + /* Send first bignum */ + buffer_put_char(m, 1); + buffer_put_bignum2(m, dh->p); + buffer_put_bignum2(m, dh->g); + + DH_free(dh); + } + mm_request_send(socket, MONITOR_ANS_MODULI, m); + return (0); +} + +int +mm_answer_sign(int socket, Buffer *m) +{ + Key *key; + u_char *p; + u_char *signature; + u_int siglen, datlen; + int keyid; + + debug3("%s", __FUNCTION__); + + keyid = buffer_get_int(m); + p = buffer_get_string(m, &datlen); + + if ((key = get_hostkey_by_index(keyid)) == NULL) + fatal("%s: no hostkey from index %d", __FUNCTION__, keyid); + if (key_sign(key, &signature, &siglen, p, datlen) < 0) + fatal("%s: key_sign failed", __FUNCTION__); + + debug3("%s: signature %p(%d)", __FUNCTION__, signature, siglen); + + buffer_clear(m); + buffer_put_string(m, signature, siglen); + + xfree(p); + xfree(signature); + + /* Turn on permissions for getpwnam */ + monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1); + + mm_request_send(socket, MONITOR_ANS_SIGN, m); + return (0); +} + +/* Retrieves the password entry and also checks if the user is permitted */ + +int +mm_answer_pwnamallow(int socket, Buffer *m) +{ + char *login; + struct passwd *pwent; + int allowed; + + debug3("%s", __FUNCTION__); + + if (authctxt->attempt++ != 0) + fatal("%s: multiple attempts for getpwnam", __FUNCTION__); + + login = buffer_get_string(m, NULL); + + /* XXX - probably latch the username here */ + pwent = getpwnam(login); + authctxt->user = xstrdup(login); + setproctitle("%s [priv]", pwent ? login : "unknown"); + xfree(login); + + /* Allow service/style information on the auth context */ + monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1); + + buffer_clear(m); + + if (pwent == NULL) { + buffer_put_char(m, 0); + mm_request_send(socket, MONITOR_ANS_PWNAM, m); + return (0); + } + + /* Check if we permit this user */ + allowed = allowed_user(pwent); + + if (allowed) { + authctxt->pw = pwcopy(pwent); + authctxt->valid = 1; + } + buffer_put_char(m, allowed); + buffer_put_string(m, pwent, sizeof(struct passwd)); + buffer_put_cstring(m, pwent->pw_name); + buffer_put_cstring(m, "*"); + buffer_put_cstring(m, pwent->pw_gecos); + buffer_put_cstring(m, pwent->pw_class); + buffer_put_cstring(m, pwent->pw_dir); + buffer_put_cstring(m, pwent->pw_shell); + + debug3("%s: sending MONITOR_ANS_PWNAM: %d", __FUNCTION__, allowed); + mm_request_send(socket, MONITOR_ANS_PWNAM, m); + + return (0); +} + +int +mm_answer_authserv(int socket, Buffer *m) +{ + /* Disallow service/style information on the auth context */ + monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 0); + + monitor_permit_authentications(1); + + authctxt->service = buffer_get_string(m, NULL); + authctxt->style = buffer_get_string(m, NULL); + if (strlen(authctxt->style) == 0) { + xfree(authctxt->style); + authctxt->style = NULL; + } + + debug3("%s: service=%s, style=%s", + __FUNCTION__, authctxt->service, authctxt->style); + + return (0); +} + +int +mm_answer_authpassword(int socket, Buffer *m) +{ + char *passwd; + int authenticated; + + passwd = buffer_get_string(m, NULL); + /* Only authenticate if the context is valid */ + authenticated = authctxt->valid && auth_password(authctxt, passwd); + memset(passwd, 0, strlen(passwd)); + xfree(passwd); + + buffer_clear(m); + buffer_put_int(m, authenticated); + + debug3("%s: sending result %d", __FUNCTION__, authenticated); + mm_request_send(socket, MONITOR_ANS_AUTHPASSWORD, m); + + /* Causes monitor loop to terminate if authenticated */ + return (authenticated); +} + +int +mm_answer_keyallowed(int socket, Buffer *m) +{ + Key *key; + u_char *cuser, *chost, *blob; + u_int bloblen; + enum mm_keytype type = 0; + int allowed = 0; + + debug3("%s entering", __FUNCTION__); + + type = buffer_get_int(m); + cuser = buffer_get_string(m, NULL); + chost = buffer_get_string(m, NULL); + blob = buffer_get_string(m, &bloblen); + + key = key_from_blob(blob, bloblen); + + debug3("%s: key_from_blob: %p", __FUNCTION__, key); + + if (key != NULL && authctxt->pw != NULL) { + switch(type) { + case MM_USERKEY: + allowed = user_key_allowed(authctxt->pw, key); + break; + case MM_HOSTKEY: + allowed = hostbased_key_allowed(authctxt->pw, + cuser, chost, key); + break; + default: + fatal("%s: unknown key type %d", __FUNCTION__, + type); + break; + } + key_free(key); + } + xfree(chost); + xfree(cuser); + xfree(blob); + + debug3("%s: key %p is %s", + __FUNCTION__, key, allowed ? "allowed" : "disallowed"); + + buffer_clear(m); + buffer_put_int(m, allowed); + + mm_request_send(socket, MONITOR_ANS_KEYALLOWED, m); + return (0); +} + +int +mm_answer_keyverify(int socket, Buffer *m) +{ + Key *key; + u_char *signature, *data, *cuser, *chost, *blob; + u_int signaturelen, datalen, bloblen; + int type; + int verified = 0; + + type = buffer_get_int(m); + cuser = buffer_get_string(m, NULL); + chost = buffer_get_string(m, NULL); + blob = buffer_get_string(m, &bloblen); + signature = buffer_get_string(m, &signaturelen); + data = buffer_get_string(m, &datalen); + + key = key_from_blob(blob, bloblen); + if (key == NULL) + fatal("%s: bad public key blob", __FUNCTION__); + + if (authctxt->pw == NULL || !user_key_allowed(authctxt->pw, key)) + fatal("%s: user not allowed", __FUNCTION__); + verified = key_verify(key, signature, signaturelen, data, datalen); + debug3("%s: key %p signature %s", + __FUNCTION__, key, verified ? "verified" : "unverified"); + + key_free(key); + xfree(chost); + xfree(cuser); + xfree(blob); + xfree(signature); + xfree(data); + + buffer_clear(m); + buffer_put_int(m, verified); + mm_request_send(socket, MONITOR_ANS_KEYVERIFY, m); + + return (verified); +} + +int +mm_answer_pty(int socket, Buffer *m) +{ + Session *s; + int res; + + debug3("%s entering", __FUNCTION__); + + buffer_clear(m); + s = session_new(); + if (s == NULL) + goto error; + s->authctxt = authctxt; + s->pw = authctxt->pw; + res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)); + if (res == 0) + goto error; + fatal_add_cleanup(session_pty_cleanup, (void *)s); + pty_setowner(authctxt->pw, s->tty); + + buffer_put_int(m, 1); + buffer_put_cstring(m, s->tty); + mm_request_send(socket, MONITOR_ANS_PTY, m); + + mm_send_fd(mm_sendfd, s->ptyfd); + mm_send_fd(mm_sendfd, s->ttyfd); + return (0); + + error: + if (s != NULL) + session_close(s); + buffer_put_int(m, 0); + mm_request_send(socket, MONITOR_ANS_PTY, m); + return (0); +} + +int +mm_answer_term(int socket, Buffer *req) +{ + debug3("%s: tearing down sessions", __FUNCTION__); + + /* The child is terminating */ + session_destroy_all(); + + return (1); +} + +void +mm_apply_keystate(struct mm_master *mm) +{ + /* XXX - delegate to child? */ + set_newkeys(MODE_IN); + set_newkeys(MODE_OUT); + + packet_set_keycontext(MODE_OUT, child_state.keyout); + xfree(child_state.keyout); + packet_set_keycontext(MODE_IN, child_state.keyin); + xfree(child_state.keyin); + + memcpy(&incoming_stream, &child_state.incoming, + sizeof(incoming_stream)); + memcpy(&outgoing_stream, &child_state.outgoing, + sizeof(outgoing_stream)); + + /* Update with new address */ + mm_init_compression(mm); +} + +/* This function requries careful sanity checking */ + +void +mm_get_keystate(int socket) +{ + Buffer m; + u_char *blob, *p; + u_int bloblen, plen; + + debug3("%s: Waiting for new keys", __FUNCTION__); + + buffer_init(&m); + mm_request_receive_expect(socket, MONITOR_REQ_KEYEXPORT, &m); + + blob = buffer_get_string(&m, &bloblen); + current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen); + xfree(blob); + + debug3("%s: Waiting for second key", __FUNCTION__); + blob = buffer_get_string(&m, &bloblen); + current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen); + xfree(blob); + + /* Now get sequence numbers for the packets */ + packet_set_seqnr(MODE_OUT, buffer_get_int(&m)); + packet_set_seqnr(MODE_IN, buffer_get_int(&m)); + + /* Get the key context */ + child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen); + child_state.keyin = buffer_get_string(&m, &child_state.keyinlen); + + debug3("%s: Getting compression state", __FUNCTION__); + /* Get compression state */ + p = buffer_get_string(&m, &plen); + if (plen != sizeof(child_state.outgoing)) + fatal("%s: bad request size", __FUNCTION__); + memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing)); + xfree(p); + + p = buffer_get_string(&m, &plen); + if (plen != sizeof(child_state.incoming)) + fatal("%s: bad request size", __FUNCTION__); + memcpy(&child_state.incoming, p, sizeof(child_state.incoming)); + xfree(p); + + buffer_free(&m); +} + + +/* Allocation functions for zlib */ +void * +mm_zalloc(struct mm_master *mm, u_int ncount, u_int size) +{ + void *address; + + address = mm_malloc(mm, size * ncount); + + return (address); +} + +void +mm_zfree(struct mm_master *mm, void *address) +{ + mm_free(mm, address); +} + +void +mm_init_compression(struct mm_master *mm) +{ + outgoing_stream.zalloc = (alloc_func)mm_zalloc; + outgoing_stream.zfree = (free_func)mm_zfree; + outgoing_stream.opaque = mm; + + incoming_stream.zalloc = (alloc_func)mm_zalloc; + incoming_stream.zfree = (free_func)mm_zfree; + incoming_stream.opaque = mm; +} diff --git a/monitor.h b/monitor.h new file mode 100644 index 000000000..7568603fe --- /dev/null +++ b/monitor.h @@ -0,0 +1,57 @@ +/* + * Copyright 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. + */ + +#ifndef _MONITOR_H_ +#define _MONITOR_H_ + +enum monitor_reqtype { + MONITOR_REQ_MODULI, MONITOR_ANS_MODULI, + MONITOR_REQ_FREE, MONITOR_REQ_AUTHSERV, + MONITOR_REQ_SIGN, MONITOR_ANS_SIGN, + MONITOR_REQ_PWNAM, MONITOR_ANS_PWNAM, + MONITOR_REQ_AUTHPASSWORD, MONITOR_ANS_AUTHPASSWORD, + MONITOR_REQ_KEYALLOWED, MONITOR_ANS_KEYALLOWED, + MONITOR_REQ_KEYVERIFY, MONITOR_ANS_KEYVERIFY, + MONITOR_REQ_KEYEXPORT, + MONITOR_REQ_PTY, MONITOR_ANS_PTY, + MONITOR_REQ_TERM +}; + +struct monitor_req { + enum monitor_reqtype type; + void *address; + size_t size; +}; + +void monitor_socketpair(int *pair); + +struct Authctxt; +struct Authctxt *monitor_child_preauth(int); +void monitor_child_postauth(int); + +struct mon_table; +int monitor_read(int, struct mon_table *); + +#endif /* _MONITOR_H_ */ diff --git a/monitor_fdpass.c b/monitor_fdpass.c new file mode 100644 index 000000000..46087ae66 --- /dev/null +++ b/monitor_fdpass.c @@ -0,0 +1,89 @@ +/* + * Copyright 2001 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" +RCSID("$OpenBSD$"); + +#include + +#include "ssh.h" +#include "log.h" +#include "xmalloc.h" +#include "misc.h" +#include "monitor_fdpass.h" + +void +mm_send_fd(int socket, int fd) +{ + struct msghdr msg; + char tmp[CMSG_SPACE(sizeof(int))]; + struct cmsghdr *cmsg; + struct iovec vec; + char ch; + + memset(&msg, 0, sizeof(msg)); + msg.msg_control = (caddr_t)tmp; + msg.msg_controllen = CMSG_LEN(sizeof(int)); + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + *(int *)CMSG_DATA(cmsg) = fd; + + vec.iov_base = &ch; + vec.iov_len = 1; + msg.msg_iov = &vec; + msg.msg_iovlen = 1; + + if (sendmsg(socket, &msg, 0) == -1) + fatal("%s: sendmsg(%d)", __FUNCTION__, fd); +} + +int +mm_receive_fd(int socket) +{ + struct msghdr msg; + char tmp[CMSG_SPACE(sizeof(int))]; + struct cmsghdr *cmsg; + struct iovec vec; + char ch; + + memset(&msg, 0, sizeof(msg)); + vec.iov_base = &ch; + vec.iov_len = 1; + msg.msg_iov = &vec; + msg.msg_iovlen = 1; + msg.msg_control = tmp; + msg.msg_controllen = sizeof(tmp); + + if (recvmsg(socket, &msg, 0) == -1) + fatal("%s: recvmsg", __FUNCTION__); + + cmsg = CMSG_FIRSTHDR(&msg); + if (cmsg->cmsg_type != SCM_RIGHTS) + fatal("%s: expected type %d got %d", __FUNCTION__, + SCM_RIGHTS, cmsg->cmsg_type); + return (*(int *)CMSG_DATA(cmsg)); +} diff --git a/monitor_fdpass.h b/monitor_fdpass.h new file mode 100644 index 000000000..cb6b71c93 --- /dev/null +++ b/monitor_fdpass.h @@ -0,0 +1,32 @@ +/* + * Copyright 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. + */ + +#ifndef _MM_FDPASS_H_ +#define _MM_FDPASS_H_ + +void mm_send_fd(int, int); +int mm_receive_fd(int); + +#endif /* _MM_FDPASS_H_ */ diff --git a/monitor_mm.c b/monitor_mm.c new file mode 100644 index 000000000..111c97d90 --- /dev/null +++ b/monitor_mm.c @@ -0,0 +1,329 @@ +/* + * Copyright 2001 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" +RCSID("$OpenBSD$"); + +#include + +#include "ssh.h" +#include "xmalloc.h" +#include "log.h" +#include "monitor_mm.h" + +static int +mm_compare(struct mm_share *a, struct mm_share *b) +{ + return (a->address - b->address); +} + +RB_GENERATE(mmtree, mm_share, next, mm_compare); + +static struct mm_share * +mm_make_entry(struct mm_master *mm, struct mmtree *head, + void *address, size_t size) +{ + struct mm_share *tmp, *tmp2; + + if (mm->mmalloc == NULL) + tmp = xmalloc(sizeof(struct mm_share)); + else + tmp = mm_xmalloc(mm->mmalloc, sizeof(struct mm_share)); + tmp->address = address; + tmp->size = size; + + tmp2 = RB_INSERT(mmtree, head, tmp); + if (tmp2 != NULL) + fatal("mm_make_entry(%p): double address %p->%p(%d)", + mm, tmp2, address, size); + + return (tmp); +} + +/* Creates a shared memory area of a certain size */ + +struct mm_master * +mm_create(struct mm_master *mmalloc, size_t size) +{ + void *address; + struct mm_master *mm; + + if (mmalloc == NULL) + mm = xmalloc(sizeof(struct mm_master)); + else + mm = mm_xmalloc(mmalloc, sizeof(struct mm_master)); + + /* + * If the memory map has a mm_master it can be completely + * shared including authentication between the child + * and the client. + */ + mm->mmalloc = mmalloc; + + address = mmap(NULL, size, PROT_WRITE|PROT_READ, MAP_ANON|MAP_SHARED, + -1, 0); + if (address == MAP_FAILED) + fatal("mmap(%d)", size); + + mm->address = address; + mm->size = size; + + RB_INIT(&mm->rb_free); + RB_INIT(&mm->rb_allocated); + + mm_make_entry(mm, &mm->rb_free, address, size); + + return (mm); +} + +/* Frees either the allocated or the free list */ + +void +mm_freelist(struct mm_master *mmalloc, struct mmtree *head) +{ + struct mm_share *mms, *next; + + for (mms = RB_ROOT(head); mms; mms = next) { + next = RB_NEXT(mmtree, head, mms); + RB_REMOVE(mmtree, head, mms); + if (mmalloc == NULL) + xfree(mms); + else + mm_free(mmalloc, mms); + } +} + +/* Destroys a memory mapped area */ + +void +mm_destroy(struct mm_master *mm) +{ + mm_freelist(mm->mmalloc, &mm->rb_free); + mm_freelist(mm->mmalloc, &mm->rb_allocated); + + if (munmap(mm->address, mm->size) == -1) + fatal("munmap(%p, %d)", mm->address, mm->size); + if (mm->mmalloc == NULL) + xfree(mm); + else + mm_free(mm->mmalloc, mm); +} + +void * +mm_xmalloc(struct mm_master *mm, size_t size) +{ + void *address; + + address = mm_malloc(mm, size); + if (address == NULL) + fatal("%s: mm_malloc(%d)", __FUNCTION__, size); + return (address); +} + + +/* Allocates data from a memory mapped area */ + +void * +mm_malloc(struct mm_master *mm, size_t size) +{ + struct mm_share *mms, *tmp; + + if (size == 0) + fatal("mm_malloc: try to allocate 0 space"); + + size = ((size + MM_MINSIZE - 1) / MM_MINSIZE) * MM_MINSIZE; + + RB_FOREACH(mms, mmtree, &mm->rb_free) { + if (mms->size >= size) + break; + } + + if (mms == NULL) + return (NULL); + + /* Debug */ + memset(mms->address, 0xd0, size); + + tmp = mm_make_entry(mm, &mm->rb_allocated, mms->address, size); + + /* Does not change order in RB tree */ + mms->size -= size; + mms->address = (u_char *)mms->address + size; + + if (mms->size == 0) { + RB_REMOVE(mmtree, &mm->rb_free, mms); + if (mm->mmalloc == NULL) + xfree(mms); + else + mm_free(mm->mmalloc, mms); + } + + return (tmp->address); +} + +/* Frees memory in a memory mapped area */ + +void +mm_free(struct mm_master *mm, void *address) +{ + struct mm_share *mms, *prev, tmp; + + tmp.address = address; + mms = RB_FIND(mmtree, &mm->rb_allocated, &tmp); + if (mms == NULL) + fatal("mm_free(%p): can not find %p", mm, address); + + /* Debug */ + memset(mms->address, 0xd0, mms->size); + + /* Remove from allocated list and insert in free list */ + RB_REMOVE(mmtree, &mm->rb_allocated, mms); + if (RB_INSERT(mmtree, &mm->rb_free, mms) != NULL) + fatal("mm_free(%p): double address %p", mm, address); + + /* Find previous entry */ + prev = mms; + if (RB_LEFT(prev, next)) { + prev = RB_LEFT(prev, next); + while (RB_RIGHT(prev, next)) + prev = RB_RIGHT(prev, next); + } else { + if (RB_PARENT(prev, next) && + (prev == RB_RIGHT(RB_PARENT(prev, next), next))) + prev = RB_PARENT(prev, next); + else { + while (RB_PARENT(prev, next) && + (prev == RB_LEFT(RB_PARENT(prev, next), next))) + prev = RB_PARENT(prev, next); + prev = RB_PARENT(prev, next); + } + } + + /* Check if range does not overlap */ + if (prev != NULL && MM_ADDRESS_END(prev) > address) + fatal("mm_free: memory corruption: %p(%d) > %p", + prev->address, prev->size, address); + + /* See if we can merge backwards */ + if (prev != NULL && MM_ADDRESS_END(prev) == address) { + prev->size += mms->size; + RB_REMOVE(mmtree, &mm->rb_free, mms); + if (mm->mmalloc == NULL) + xfree(mms); + else + mm_free(mm->mmalloc, mms); + } else + prev = mms; + + if (prev == NULL) + return; + + /* Check if we can merge forwards */ + mms = RB_NEXT(mmtree, &mm->rb_free, prev); + if (mms == NULL) + return; + + if (MM_ADDRESS_END(prev) > mms->address) + fatal("mm_free: memory corruption: %p < %p(%d)", + mms->address, prev->address, prev->size); + if (MM_ADDRESS_END(prev) != mms->address) + return; + + prev->size += mms->size; + RB_REMOVE(mmtree, &mm->rb_free, mms); + + if (mm->mmalloc == NULL) + xfree(mms); + else + mm_free(mm->mmalloc, mms); +} + +void +mm_sync_list(struct mmtree *oldtree, struct mmtree *newtree, + struct mm_master *mm, struct mm_master *mmold) +{ + struct mm_master *mmalloc = mm->mmalloc; + struct mm_share *mms, *new; + + /* Sync free list */ + RB_FOREACH(mms, mmtree, oldtree) { + /* Check the values */ + mm_memvalid(mmold, mms, sizeof(struct mm_share)); + mm_memvalid(mm, mms->address, mms->size); + + new = mm_xmalloc(mmalloc, sizeof(struct mm_share)); + memcpy(new, mms, sizeof(struct mm_share)); + RB_INSERT(mmtree, newtree, new); + } +} + +void +mm_share_sync(struct mm_master **pmm, struct mm_master **pmmalloc) +{ + struct mm_master *mm; + struct mm_master *mmalloc; + struct mm_master *mmold; + struct mmtree rb_free, rb_allocated; + + debug3("%s: Share sync", __FUNCTION__); + + mm = *pmm; + mmold = mm->mmalloc; + mm_memvalid(mmold, mm, sizeof(*mm)); + + mmalloc = mm_create(NULL, mm->size); + mm = mm_xmalloc(mmalloc, sizeof(struct mm_master)); + memcpy(mm, *pmm, sizeof(struct mm_master)); + mm->mmalloc = mmalloc; + + rb_free = mm->rb_free; + rb_allocated = mm->rb_allocated; + + RB_INIT(&mm->rb_free); + RB_INIT(&mm->rb_allocated); + + mm_sync_list(&rb_free, &mm->rb_free, mm, mmold); + mm_sync_list(&rb_allocated, &mm->rb_allocated, mm, mmold); + + mm_destroy(mmold); + + *pmm = mm; + *pmmalloc = mmalloc; + + debug3("%s: Share sync end", __FUNCTION__); +} + +void +mm_memvalid(struct mm_master *mm, void *address, size_t size) +{ + void *end = (u_char *)address + size; + + if (address < mm->address) + fatal("mm_memvalid: address too small: %p", address); + if (end < address) + fatal("mm_memvalid: end < address: %p < %p", end, address); + if (end > (void *)((u_char *)mm->address + mm->size)) + fatal("mm_memvalid: address too large: %p", address); +} diff --git a/monitor_mm.h b/monitor_mm.h new file mode 100644 index 000000000..5b4b789ca --- /dev/null +++ b/monitor_mm.h @@ -0,0 +1,64 @@ +/* + * Copyright 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. + */ + +#ifndef _MM_H_ +#define _MM_H_ +#include + +struct mm_share { + RB_ENTRY(mm_share) next; + void *address; + size_t size; +}; + +struct mm_master { + RB_HEAD(mmtree, mm_share) rb_free; + struct mmtree rb_allocated; + void *address; + size_t size; + + struct mm_master *mmalloc; /* Used to completely share */ + + int write; /* used to writing to other party */ + int read; /* used for reading from other party */ +}; + +RB_PROTOTYPE(mmtree, mm_share, next, mm_compare); + +#define MM_MINSIZE 128 + +#define MM_ADDRESS_END(x) (void *)((u_char *)(x)->address + (x)->size) + +struct mm_master *mm_create(struct mm_master *, size_t); +void mm_destroy(struct mm_master *); + +void mm_share_sync(struct mm_master **, struct mm_master **); + +void *mm_malloc(struct mm_master *, size_t); +void *mm_xmalloc(struct mm_master *, size_t); +void mm_free(struct mm_master *, void *); + +void mm_memvalid(struct mm_master *, void *, size_t); +#endif /* _MM_H_ */ diff --git a/monitor_wrap.c b/monitor_wrap.c new file mode 100644 index 000000000..798e9353d --- /dev/null +++ b/monitor_wrap.c @@ -0,0 +1,538 @@ +/* + * Copyright 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" +RCSID("$OpenBSD$"); + +#include +#include + +#include "ssh.h" +#include "dh.h" +#include "kex.h" +#include "buffer.h" +#include "bufaux.h" +#include "packet.h" +#include "mac.h" +#include "log.h" +#include "zlib.h" +#include "monitor.h" +#include "monitor_wrap.h" +#include "xmalloc.h" +#include "atomicio.h" +#include "monitor_fdpass.h" +#include "getput.h" + +/* Imports */ +extern Newkeys *newkeys[]; +extern z_stream incoming_stream; +extern z_stream outgoing_stream; + +void +mm_request_send(int socket, enum monitor_reqtype type, Buffer *m) +{ + u_char buf[5]; + u_int mlen = buffer_len(m); + + debug3("%s entering: type %d", __FUNCTION__, type); + + PUT_32BIT(buf, mlen + 1); + buf[4] = (u_char) type; /* 1st byte of payload is mesg-type */ + if (atomicio(write, socket, buf, sizeof(buf)) != sizeof(buf)) + fatal("%s: write", __FUNCTION__); + if (atomicio(write, socket, buffer_ptr(m), mlen) != mlen) + fatal("%s: write", __FUNCTION__); +} + +void +mm_request_receive(int socket, Buffer *m) +{ + u_char buf[4]; + ssize_t res; + u_int msg_len; + + debug3("%s entering", __FUNCTION__); + + res = atomicio(read, socket, buf, sizeof(buf)); + if (res != sizeof(buf)) + fatal("%s: read: %d", __FUNCTION__, res); + msg_len = GET_32BIT(buf); + if (msg_len > 256 * 1024) + fatal("%s: read: bad msg_len %d", __FUNCTION__, msg_len); + buffer_clear(m); + buffer_append_space(m, msg_len); + res = atomicio(read, socket, buffer_ptr(m), msg_len); + if (res != msg_len) + fatal("%s: read: %d != msg_len", __FUNCTION__, res); +} + +void +mm_request_receive_expect(int socket, enum monitor_reqtype type, Buffer *m) +{ + u_char rtype; + + debug3("%s entering: type %d", __FUNCTION__, type); + + mm_request_receive(socket, m); + rtype = buffer_get_char(m); + if (rtype != type) + fatal("%s: read: rtype %d != type %d", __FUNCTION__, + rtype, type); +} + +DH * +mm_choose_dh(int socket, int min, int nbits, int max) +{ + BIGNUM *p, *g; + int success = 0; + Buffer m; + + buffer_init(&m); + buffer_put_int(&m, min); + buffer_put_int(&m, nbits); + buffer_put_int(&m, max); + + mm_request_send(socket, MONITOR_REQ_MODULI, &m); + + debug3("%s: waiting for MONITOR_ANS_MODULI", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_MODULI, &m); + + success = buffer_get_char(&m); + if (success == 0) + fatal("%s: MONITOR_ANS_MODULI failed", __FUNCTION__); + + if ((p = BN_new()) == NULL) + fatal("%s: BN_new failed", __FUNCTION__); + if ((g = BN_new()) == NULL) + fatal("%s: BN_new failed", __FUNCTION__); + buffer_get_bignum2(&m, p); + buffer_get_bignum2(&m, g); + + debug3("%s: remaining %d", __FUNCTION__, buffer_len(&m)); + buffer_free(&m); + + return (dh_new_group(g, p)); +} + +int +mm_key_sign(int socket, int keyind, u_char **sigp, u_int *lenp, + u_char *data, u_int datalen) +{ + Buffer m; + + debug3("%s entering", __FUNCTION__); + + buffer_init(&m); + buffer_put_int(&m, keyind); + buffer_put_string(&m, data, datalen); + + mm_request_send(socket, MONITOR_REQ_SIGN, &m); + + debug3("%s: waiting for MONITOR_ANS_SIGN", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_SIGN, &m); + *sigp = buffer_get_string(&m, lenp); + buffer_free(&m); + + return (0); +} + +struct passwd * +mm_getpwnamallow(int socket, const char *login, int *allowed) +{ + Buffer m; + struct passwd *pw; + u_int pwlen; + + debug3("%s entering", __FUNCTION__); + + buffer_init(&m); + buffer_put_cstring(&m, login); + + mm_request_send(socket, MONITOR_REQ_PWNAM, &m); + + debug3("%s: waiting for MONITOR_ANS_PWNAM", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_PWNAM, &m); + + *allowed = buffer_get_char(&m); + if (*allowed == 0) { + buffer_free(&m); + return (NULL); + } + pw = buffer_get_string(&m, &pwlen); + if (pwlen != sizeof(struct passwd)) + fatal("%s: struct passwd size mismatch", __FUNCTION__); + pw->pw_name = buffer_get_string(&m, NULL); + pw->pw_passwd = buffer_get_string(&m, NULL); + pw->pw_gecos = buffer_get_string(&m, NULL); + pw->pw_class = buffer_get_string(&m, NULL); + pw->pw_dir = buffer_get_string(&m, NULL); + pw->pw_shell = buffer_get_string(&m, NULL); + buffer_free(&m); + + return (pw); +} + +void +pwfree(struct passwd *pw) +{ + xfree(pw->pw_name); + xfree(pw->pw_passwd); + xfree(pw->pw_gecos); + xfree(pw->pw_class); + xfree(pw->pw_dir); + xfree(pw->pw_shell); + xfree(pw); +} + +/* Inform the privileged process about service and style */ + +void +mm_inform_authserv(int socket, char *service, char *style) +{ + Buffer m; + + debug3("%s entering", __FUNCTION__); + + buffer_init(&m); + buffer_put_cstring(&m, service); + buffer_put_cstring(&m, style ? style : ""); + + mm_request_send(socket, MONITOR_REQ_AUTHSERV, &m); + + buffer_free(&m); +} + +/* Do the password authentication */ +int +mm_auth_password(int socket, char *password) +{ + Buffer m; + int authenticated = 0; + + debug3("%s entering", __FUNCTION__); + + buffer_init(&m); + buffer_put_cstring(&m, password); + mm_request_send(socket, MONITOR_REQ_AUTHPASSWORD, &m); + + debug3("%s: waiting for MONITOR_ANS_AUTHPASSWORD", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_AUTHPASSWORD, &m); + + authenticated = buffer_get_int(&m); + + buffer_free(&m); + + debug3("%s: user %sauthenticated", + __FUNCTION__, authenticated ? "" : "not "); + return (authenticated); +} + +int +mm_key_allowed(int socket, enum mm_keytype type, char *user, char *host, + Key *key) +{ + Buffer m; + u_char *blob; + u_int len; + int allowed = 0; + + debug3("%s entering", __FUNCTION__); + + /* Convert the key to a blob and the pass it over */ + if (!key_to_blob(key, &blob, &len)) + return (0); + + buffer_init(&m); + buffer_put_int(&m, type); + buffer_put_cstring(&m, user ? user : ""); + buffer_put_cstring(&m, host ? host : ""); + buffer_put_string(&m, blob, len); + xfree(blob); + + mm_request_send(socket, MONITOR_REQ_KEYALLOWED, &m); + + debug3("%s: waiting for MONITOR_ANS_KEYALLOWED", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_KEYALLOWED, &m); + + allowed = buffer_get_int(&m); + + buffer_free(&m); + + return (allowed); +} + +/* + * This key verify needs to send the key type along, because the + * privileged parent makes the decision if the key is allowed + * for authentication. + */ + +int +mm_key_verify(int socket, enum mm_keytype type, char *user, char *host, + Key *key, u_char *sig, u_int siglen, u_char *data, u_int datalen) +{ + Buffer m; + u_char *blob; + u_int len; + int verified = 0; + + debug3("%s entering", __FUNCTION__); + + /* Convert the key to a blob and the pass it over */ + if (!key_to_blob(key, &blob, &len)) + return (0); + + buffer_init(&m); + buffer_put_int(&m, type); + buffer_put_cstring(&m, user ? user : ""); + buffer_put_cstring(&m, host ? host : ""); + buffer_put_string(&m, blob, len); + buffer_put_string(&m, sig, siglen); + buffer_put_string(&m, data, datalen); + xfree(blob); + + mm_request_send(socket, MONITOR_REQ_KEYVERIFY, &m); + + debug3("%s: waiting for MONITOR_ANS_KEYVERIFY", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_KEYVERIFY, &m); + + verified = buffer_get_int(&m); + + buffer_free(&m); + + return (verified); +} + +/* Export key state after authentication */ +Newkeys * +mm_newkeys_from_blob(u_char *blob, int blen) +{ + Buffer b; + int rlen; + Newkeys *newkey = NULL; + Enc *enc; + Mac *mac; + Comp *comp; + + debug3("%s: %p(%d)", __FUNCTION__, blob, blen); +#ifdef DEBUG_PK + dump_base64(stderr, blob, blen); +#endif + buffer_init(&b); + buffer_append(&b, blob, blen); + + newkey = xmalloc(sizeof(*newkey)); + enc = &newkey->enc; + mac = &newkey->mac; + comp = &newkey->comp; + + /* Enc structure */ + enc->name = buffer_get_string(&b, NULL); + buffer_get(&b, &enc->cipher, sizeof(enc->cipher)); + enc->enabled = buffer_get_int(&b); + enc->key_len = buffer_get_int(&b); + enc->block_size = buffer_get_int(&b); + enc->key = xmalloc(enc->key_len); + buffer_get(&b, enc->key, enc->key_len); + enc->iv = xmalloc(enc->block_size); + buffer_get(&b, enc->iv, enc->block_size); + + if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) + fatal("%s: bad cipher name %s or pointer %p", __FUNCTION__, + enc->name, enc->cipher); + + /* Mac structure */ + mac->name = buffer_get_string(&b, NULL); + if (mac->name == NULL || mac_init(mac, mac->name) == -1) + fatal("%s: can not init mac %s", __FUNCTION__, mac->name); + mac->enabled = buffer_get_int(&b); + mac->key = xmalloc(mac->key_len); + buffer_get(&b, mac->key, mac->key_len); + + /* Comp structure */ + comp->type = buffer_get_int(&b); + comp->enabled = buffer_get_int(&b); + comp->name = buffer_get_string(&b, NULL); + + rlen = buffer_len(&b); + if (rlen != 0) + error("newkeys_from_blob: remaining bytes in blob %d", rlen); + buffer_free(&b); + return (newkey); +} + +int +mm_newkeys_to_blob(int mode, u_char **blobp, u_int *lenp) +{ + Buffer b; + int len; + u_char *buf; + Enc *enc; + Mac *mac; + Comp *comp; + Newkeys *newkey = newkeys[mode]; + + debug3("%s: converting %p", __FUNCTION__, newkey); + + if (newkey == NULL) { + error("%s: newkey == NULL", __FUNCTION__); + return 0; + } + enc = &newkey->enc; + mac = &newkey->mac; + comp = &newkey->comp; + + buffer_init(&b); + /* Enc structure */ + buffer_put_cstring(&b, enc->name); + /* The cipher struct is constant and shared, you export pointer */ + buffer_append(&b, &enc->cipher, sizeof(enc->cipher)); + buffer_put_int(&b, enc->enabled); + buffer_put_int(&b, enc->key_len); + buffer_put_int(&b, enc->block_size); + buffer_append(&b, enc->key, enc->key_len); + packet_get_keyiv(mode, enc->iv, enc->block_size); + buffer_append(&b, enc->iv, enc->block_size); + + /* Mac structure */ + buffer_put_cstring(&b, mac->name); + buffer_put_int(&b, mac->enabled); + buffer_append(&b, mac->key, mac->key_len); + + /* Comp structure */ + buffer_put_int(&b, comp->type); + buffer_put_int(&b, comp->enabled); + buffer_put_cstring(&b, comp->name); + + len = buffer_len(&b); + buf = xmalloc(len); + memcpy(buf, buffer_ptr(&b), len); + memset(buffer_ptr(&b), 0, len); + buffer_free(&b); + if (lenp != NULL) + *lenp = len; + if (blobp != NULL) + *blobp = buf; + return len; +} + +void +mm_send_keystate(int socket) +{ + Buffer m; + u_char *blob, *p; + u_int bloblen, plen; + + debug3("%s: Sending new keys: %p %p", + __FUNCTION__, newkeys[MODE_OUT], newkeys[MODE_IN]); + + buffer_init(&m); + + /* Keys from Kex */ + if (!mm_newkeys_to_blob(MODE_OUT, &blob, &bloblen)) + fatal("%s: conversion of newkeys failed", __FUNCTION__); + + buffer_put_string(&m, blob, bloblen); + xfree(blob); + + if (!mm_newkeys_to_blob(MODE_IN, &blob, &bloblen)) + fatal("%s: conversion of newkeys failed", __FUNCTION__); + + buffer_put_string(&m, blob, bloblen); + xfree(blob); + + buffer_put_int(&m, packet_get_seqnr(MODE_OUT)); + buffer_put_int(&m, packet_get_seqnr(MODE_IN)); + + debug3("%s: New keys have been sent", __FUNCTION__); + + /* More key context */ + plen = packet_get_keycontext(MODE_OUT, NULL); + p = xmalloc(plen+1); + packet_get_keycontext(MODE_OUT, p); + buffer_put_string(&m, p, plen); + xfree(p); + + plen = packet_get_keycontext(MODE_IN, NULL); + p = xmalloc(plen+1); + packet_get_keycontext(MODE_IN, p); + buffer_put_string(&m, p, plen); + xfree(p); + + /* Compression state */ + debug3("%s: Sending compression state", __FUNCTION__); + buffer_put_string(&m, &outgoing_stream, sizeof(outgoing_stream)); + buffer_put_string(&m, &incoming_stream, sizeof(incoming_stream)); + + mm_request_send(socket, MONITOR_REQ_KEYEXPORT, &m); + debug3("%s: Finished sending state", __FUNCTION__); + + buffer_free(&m); +} + +int +mm_pty_allocown(int socket, int *ptyfd, int *ttyfd, + char *namebuf, int namebuflen) +{ + Buffer m; + u_char *p; + int success = 0; + + buffer_init(&m); + mm_request_send(socket, MONITOR_REQ_PTY, &m); + + debug3("%s: waiting for MONITOR_ANS_PTY", __FUNCTION__); + mm_request_receive_expect(socket, MONITOR_ANS_PTY, &m); + + success = buffer_get_int(&m); + if (success == 0) { + debug3("%s: pty alloc failed", __FUNCTION__); + buffer_free(&m); + return (0); + } + p = buffer_get_string(&m, NULL); + buffer_free(&m); + + strlcpy(namebuf, p, namebuflen); /* Possible truncation */ + xfree(p); + + *ptyfd = mm_receive_fd(socket); + *ttyfd = mm_receive_fd(socket); + + /* Success */ + return (1); +} + +/* Request process termination */ + +void +mm_terminate(int socket) +{ + Buffer m; + + buffer_init(&m); + mm_request_send(socket, MONITOR_REQ_TERM, &m); + buffer_free(&m); +} diff --git a/monitor_wrap.h b/monitor_wrap.h new file mode 100644 index 000000000..3c8378024 --- /dev/null +++ b/monitor_wrap.h @@ -0,0 +1,99 @@ +/* + * Copyright 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. + */ + +#ifndef _MM_WRAP_H_ +#define _MM_WRAP_H_ +#include "key.h" +#include "buffer.h" + +struct mm_moduli { + int min; + int want; + int max; +}; + +enum mm_keytype {MM_HOSTKEY, MM_USERKEY}; + +struct mm_keyallowed { + enum mm_keytype type; + char chost[MAXHOSTNAMELEN]; + char cuser[MAXLOGNAME]; +}; + +struct mm_master; + +struct passwd; +DH *mm_choose_dh(int, int, int, int); +DH *mm_read_moduli(int); +int mm_key_sign(int, int, u_char **, u_int *, u_char *, u_int); +void mm_inform_authserv(int, char *, char *); +struct passwd *mm_getpwnamallow(int, const char *, int *); +int mm_auth_password(int, char *); +int mm_key_allowed(int, enum mm_keytype, char *, char *, Key *); +#define mm_hostbased_key_allowed(x,u,h,z) \ + mm_key_allowed(x, MM_HOSTKEY, u, h, z) +#define mm_user_key_allowed(x,z) \ + mm_key_allowed(x, MM_USERKEY, NULL, NULL, z) + +int mm_key_verify(int, enum mm_keytype, char *, char *, + Key *, u_char *, u_int, u_char *, u_int); + +void mm_terminate(int); + +/* Key export functions */ +struct Newkeys *mm_newkeys_from_blob(u_char *, int); +int mm_newkeys_to_blob(int, u_char **, u_int *); + +void mm_apply_keystate(struct mm_master *); +void mm_get_keystate(int); +void mm_send_keystate(int); + +int mm_pty_allocown(int, int *, int *, char *, int); + +/* Functions on the montior that answer unprivileged requests */ + +int mm_answer_moduli(int, Buffer *); +int mm_answer_sign(int, Buffer *); +int mm_answer_pwnamallow(int, Buffer *); +int mm_answer_authserv(int, Buffer *); +int mm_answer_authpassword(int, Buffer *); +int mm_answer_keyallowed(int, Buffer *); +int mm_answer_keyverify(int, Buffer *); +int mm_answer_pty(int, Buffer *); +int mm_answer_term(int, Buffer *); + +void mm_request_send(int , enum monitor_reqtype, Buffer *); +void mm_request_receive(int, Buffer *); +void mm_request_receive_expect(int, enum monitor_reqtype, + Buffer *); + +void *mm_zalloc(struct mm_master *, u_int, u_int); +void mm_zfree(struct mm_master *, void *); +void mm_init_compression(struct mm_master *); + +/* Utility functions */ + +void pwfree(struct passwd *); +#endif /* _MM_H_ */ diff --git a/packet.c b/packet.c index 045d5a105..1c80af128 100644 --- a/packet.c +++ b/packet.c @@ -115,6 +115,8 @@ static int interactive_mode = 0; /* Session key information for Encryption and MAC */ Newkeys *newkeys[MODE_MAX]; +static u_int32_t read_seqnr = 0; +static u_int32_t send_seqnr = 0; /* roundup current message to extra_pad bytes */ static u_char extra_pad = 0; @@ -171,6 +173,87 @@ packet_connection_is_on_socket(void) return 1; } +/* + * Exports an IV from the CipherContext required to export the key + * state back from the unprivileged child to the privileged parent + * process. + */ + +void +packet_get_keyiv(int mode, u_char *iv, u_int len) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + cipher_get_keyiv(cc, iv, len); +} + +int +packet_get_keycontext(int mode, u_char *dat) +{ + int plen; + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + +#if OPENSSL_VERSION_NUMBER < 0x00907000L + plen = sizeof(cc->evp.c); +#else + plen = cc->evp.cipher->ctx_size; +#endif + + if (dat == NULL) + return (plen); + +#if OPENSSL_VERSION_NUMBER < 0x00907000L + memcpy(dat, &cc->evp.c, sizeof(cc->evp.c)); +#else + memcpy(dat, &cc->evp.cipher_data, plen); +#endif + return (plen); +} + +void +packet_set_keycontext(int mode, u_char *dat) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + +#if OPENSSL_VERSION_NUMBER < 0x00907000L + memcpy(&cc->evp.c, dat, sizeof(cc->evp.c)); +#else + memcpy(&cc->evp.cipher_data, dat, cc->evp.cipher->ctx_size); +#endif +} + +u_int32_t +packet_get_seqnr(int mode) +{ + return (mode == MODE_IN ? read_seqnr : send_seqnr); +} + +void +packet_set_seqnr(int mode, u_int32_t seqnr) +{ + if (mode == MODE_IN) + read_seqnr = seqnr; + else if (mode == MODE_OUT) + send_seqnr = seqnr; + else + fatal("%s: bad mode %d", __FUNCTION__, mode); +} + /* returns 1 if connection is via ipv4 */ int @@ -433,7 +516,7 @@ packet_send1(void) */ } -static void +void set_newkeys(int mode) { Enc *enc; @@ -477,8 +560,9 @@ set_newkeys(int mode) DBG(debug("cipher_init_context: %d", mode)); cipher_init(cc, enc->cipher, enc->key, enc->key_len, enc->iv, enc->block_size, encrypt); - memset(enc->iv, 0, enc->block_size); - memset(enc->key, 0, enc->key_len); + /* Deleting the keys does not gain extra security */ + /* memset(enc->iv, 0, enc->block_size); + memset(enc->key, 0, enc->key_len); */ if (comp->type != 0 && comp->enabled == 0) { packet_init_compression(); if (mode == MODE_OUT) @@ -495,7 +579,6 @@ set_newkeys(int mode) static void packet_send2(void) { - static u_int32_t seqnr = 0; u_char type, *cp, *macbuf = NULL; u_char padlen, pad; u_int packet_length = 0; @@ -576,10 +659,10 @@ packet_send2(void) /* compute MAC over seqnr and packet(length fields, payload, padding) */ if (mac && mac->enabled) { - macbuf = mac_compute(mac, seqnr, + macbuf = mac_compute(mac, send_seqnr, buffer_ptr(&outgoing_packet), buffer_len(&outgoing_packet)); - DBG(debug("done calc MAC out #%d", seqnr)); + DBG(debug("done calc MAC out #%d", send_seqnr)); } /* encrypt packet and append to output buffer. */ cp = buffer_append_space(&output, buffer_len(&outgoing_packet)); @@ -593,7 +676,7 @@ packet_send2(void) buffer_dump(&output); #endif /* increment sequence number for outgoing packets */ - if (++seqnr == 0) + if (++send_seqnr == 0) log("outgoing seqnr wraps around"); buffer_clear(&outgoing_packet); @@ -783,7 +866,6 @@ packet_read_poll1(void) static int packet_read_poll2(u_int32_t *seqnr_p) { - static u_int32_t seqnr = 0; static u_int packet_length = 0; u_int padlen, need; u_char *macbuf, *cp, type; @@ -845,17 +927,17 @@ packet_read_poll2(u_int32_t *seqnr_p) * increment sequence number for incoming packet */ if (mac && mac->enabled) { - macbuf = mac_compute(mac, seqnr, + macbuf = mac_compute(mac, read_seqnr, buffer_ptr(&incoming_packet), buffer_len(&incoming_packet)); if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0) packet_disconnect("Corrupted MAC on input."); - DBG(debug("MAC #%d ok", seqnr)); + DBG(debug("MAC #%d ok", read_seqnr)); buffer_consume(&input, mac->mac_len); } if (seqnr_p != NULL) - *seqnr_p = seqnr; - if (++seqnr == 0) + *seqnr_p = read_seqnr; + if (++read_seqnr == 0) log("incoming seqnr wraps around"); /* get padlen */ diff --git a/packet.h b/packet.h index d6bf2aab4..b87a03cf8 100644 --- a/packet.h +++ b/packet.h @@ -56,6 +56,13 @@ void *packet_get_string(u_int *length_ptr); void packet_disconnect(const char *fmt,...) __attribute__((format(printf, 1, 2))); void packet_send_debug(const char *fmt,...) __attribute__((format(printf, 1, 2))); +void set_newkeys(int mode); +void packet_get_keyiv(int, u_char *, u_int); +int packet_get_keycontext(int, u_char *); +void packet_set_keycontext(int, u_char *); +u_int32_t packet_get_seqnr(int); +void packet_set_seqnr(int, u_int32_t); + void packet_write_poll(void); void packet_write_wait(void); int packet_have_data_to_write(void); diff --git a/servconf.c b/servconf.c index 9bbd994ca..c3f1253e8 100644 --- a/servconf.c +++ b/servconf.c @@ -36,6 +36,8 @@ static void add_one_listen_addr(ServerOptions *, char *, u_short); /* AF_UNSPEC or AF_INET or AF_INET6 */ extern int IPv4or6; +/* Use of privilege separation or not */ +extern int use_privsep; /* Initializes the server options to their default values. */ @@ -110,6 +112,9 @@ initialize_server_options(ServerOptions *options) options->client_alive_count_max = -1; options->authorized_keys_file = NULL; options->authorized_keys_file2 = NULL; + + /* Needs to be accessable in many places */ + use_privsep = -1; } void @@ -235,6 +240,10 @@ fill_default_server_options(ServerOptions *options) } if (options->authorized_keys_file == NULL) options->authorized_keys_file = _PATH_SSH_USER_PERMITTED_KEYS; + + /* Turn privilege separation on by default */ + if (use_privsep == -1) + use_privsep = 1; } /* Keyword tokens. */ @@ -267,6 +276,7 @@ typedef enum { sBanner, sVerifyReverseMapping, sHostbasedAuthentication, sHostbasedUsesNameFromPacketOnly, sClientAliveInterval, sClientAliveCountMax, sAuthorizedKeysFile, sAuthorizedKeysFile2, + sUsePrivilegeSeparation, sDeprecated } ServerOpCodes; @@ -342,6 +352,7 @@ static struct { { "clientalivecountmax", sClientAliveCountMax }, { "authorizedkeysfile", sAuthorizedKeysFile }, { "authorizedkeysfile2", sAuthorizedKeysFile2 }, + { "useprivilegeseparation", sUsePrivilegeSeparation}, { NULL, sBadOption } }; @@ -718,6 +729,10 @@ parse_flag: intptr = &options->allow_tcp_forwarding; goto parse_flag; + case sUsePrivilegeSeparation: + intptr = &use_privsep; + goto parse_flag; + case sAllowUsers: while ((arg = strdelim(&cp)) && *arg != '\0') { if (options->num_allow_users >= MAX_ALLOW_USERS) diff --git a/session.c b/session.c index a31ff85d8..17227c9ff 100644 --- a/session.c +++ b/session.c @@ -56,6 +56,8 @@ RCSID("$OpenBSD: session.c,v 1.128 2002/02/16 00:51:44 markus Exp $"); #include "serverloop.h" #include "canohost.h" #include "session.h" +#include "monitor.h" +#include "monitor_wrap.h" #ifdef HAVE_CYGWIN #include @@ -63,39 +65,15 @@ RCSID("$OpenBSD: session.c,v 1.128 2002/02/16 00:51:44 markus Exp $"); #define is_winnt (GetVersion() < 0x80000000) #endif -/* types */ - -#define TTYSZ 64 -typedef struct Session Session; -struct Session { - int used; - int self; - struct passwd *pw; - Authctxt *authctxt; - pid_t pid; - /* tty */ - char *term; - int ptyfd, ttyfd, ptymaster; - int row, col, xpixel, ypixel; - char tty[TTYSZ]; - /* X11 */ - int display_number; - char *display; - int screen; - char *auth_display; - char *auth_proto; - char *auth_data; - int single_connection; - /* proto 2 */ - int chanid; - int is_subsystem; -}; +/* Imports */ +extern int use_privsep; +extern int mm_recvfd; /* func */ Session *session_new(void); void session_set_fds(Session *, int, int, int); -static void session_pty_cleanup(void *); +void session_pty_cleanup(void *); void session_proctitle(Session *); int session_setup_x11fwd(Session *); void do_exec_pty(Session *, const char *); @@ -112,7 +90,6 @@ int check_quietlogin(Session *, const char *); static void do_authenticated1(Authctxt *); static void do_authenticated2(Authctxt *); -static void session_close(Session *); static int session_pty_req(Session *); /* import */ @@ -1448,7 +1425,8 @@ session_pty_req(Session *s) { u_int len; int n_bytes; - + int res; + if (no_pty_flag) { debug("Allocating a pty not permitted for this authentication."); return 0; @@ -1477,7 +1455,15 @@ session_pty_req(Session *s) /* Allocate a pty and open it. */ debug("Allocating pty."); - if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) { + if (!use_privsep) { + res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, + sizeof(s->tty)); + if (res) + pty_setowner(s->pw, s->tty); + } else + res = mm_pty_allocown(mm_recvfd, + &s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)); + if (!res) { if (s->term) xfree(s->term); s->term = NULL; @@ -1498,7 +1484,6 @@ session_pty_req(Session *s) * time in case we call fatal() (e.g., the connection gets closed). */ fatal_add_cleanup(session_pty_cleanup, (void *)s); - pty_setowner(s->pw, s->tty); /* Set window size from the packet. */ pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); @@ -1661,7 +1646,7 @@ session_set_fds(Session *s, int fdin, int fdout, int fderr) * Function to perform pty cleanup. Also called if we get aborted abnormally * (e.g., due to a dropped connection). */ -static void +void session_pty_cleanup(void *session) { Session *s = session; @@ -1739,7 +1724,7 @@ session_exit_message(Session *s, int status) s->chanid = -1; } -static void +void session_close(Session *s) { debug("session_close: session %d pid %d", s->self, s->pid); diff --git a/session.h b/session.h index ec8284a5f..e3123beed 100644 --- a/session.h +++ b/session.h @@ -26,6 +26,32 @@ #ifndef SESSION_H #define SESSION_H +#define TTYSZ 64 +typedef struct Session Session; +struct Session { + int used; + int self; + struct passwd *pw; + Authctxt *authctxt; + pid_t pid; + /* tty */ + char *term; + int ptyfd, ttyfd, ptymaster; + int row, col, xpixel, ypixel; + char tty[TTYSZ]; + /* X11 */ + int display_number; + char *display; + int screen; + char *auth_display; + char *auth_proto; + char *auth_data; + int single_connection; + /* proto 2 */ + int chanid; + int is_subsystem; +}; + void do_authenticated(Authctxt *); int session_open(Authctxt*, int); @@ -34,4 +60,6 @@ void session_close_by_pid(pid_t, int); void session_close_by_channel(int, void *); void session_destroy_all(void); +Session *session_new(void); +void session_close(Session *); #endif diff --git a/sshd.c b/sshd.c index ea9293251..cbe316087 100644 --- a/sshd.c +++ b/sshd.c @@ -72,6 +72,11 @@ RCSID("$OpenBSD: sshd.c,v 1.228 2002/02/27 21:23:13 stevesk Exp $"); #include "misc.h" #include "dispatch.h" #include "channels.h" +#include "session.h" +#include "monitor_mm.h" +#include "monitor.h" +#include "monitor_wrap.h" +#include "monitor_fdpass.h" #ifdef LIBWRAP #include @@ -189,8 +194,20 @@ u_int utmp_len = MAXHOSTNAMELEN; int *startup_pipes = NULL; int startup_pipe; /* in child */ +/* variables used for privilege separation */ +#define MM_MEMSIZE 65536 +struct mm_master *mm_zback; +struct mm_master *mm_zlib; + +extern int use_privsep; +/* Socket for the child to receive a fd */ +extern int mm_recvfd; +/* Socket for the parent to send a fd */ +int mm_sendfd; + /* Prototypes for various functions defined later in this file. */ void destroy_sensitive_data(void); +void demote_sensitive_data(void); static void do_ssh1_kex(void); static void do_ssh2_kex(void); @@ -477,6 +494,69 @@ destroy_sensitive_data(void) memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH); } +/* Demote private to public keys for network child */ +void +demote_sensitive_data(void) +{ + Key *tmp; + int i; + + if (sensitive_data.server_key) { + tmp = key_demote(sensitive_data.server_key); + key_free(sensitive_data.server_key); + sensitive_data.server_key = tmp; + } + for (i = 0; i < options.num_host_key_files; i++) { + if (sensitive_data.host_keys[i]) { + tmp = key_demote(sensitive_data.host_keys[i]); + key_free(sensitive_data.host_keys[i]); + sensitive_data.host_keys[i] = tmp; + } + } + + /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */ +} + +void +privsep_postauth(Authctxt *authctxt) +{ + pid_t pid; + + if (0) { + /* File descriptor passing is broken */ + mm_apply_keystate(mm_zlib); + use_privsep = 0; + return; + } + + pid = fork(); + if (pid == -1) + fatal("fork of unprivileged child failed"); + else if (pid != 0) { + debug2("User child is on pid %d", pid); + close(mm_recvfd); + monitor_child_postauth(mm_sendfd); + + /* Teardown? */ + exit(0); + } + + close(mm_sendfd); + + /* Demote the private keys to public keys. */ + demote_sensitive_data(); + + /* Drop privileges */ + if (seteuid(authctxt->pw->pw_uid) == -1) + fatal("%s: seteuid", __FUNCTION__); + if (setuid(authctxt->pw->pw_uid) == -1) + fatal("%s: setuid", __FUNCTION__); + + /* It is safe now to apply the key state */ + mm_apply_keystate(mm_zlib); +} + + static char * list_hostkey_types(void) { @@ -518,6 +598,25 @@ get_hostkey_by_type(int type) return NULL; } +Key * +get_hostkey_by_index(int ind) +{ + if (ind < 0 || ind >= options.num_host_key_files) + return (NULL); + return (sensitive_data.host_keys[ind]); +} + +int +get_hostkey_index(Key *key) +{ + int i; + for (i = 0; i < options.num_host_key_files; i++) { + if (key == sensitive_data.host_keys[i]) + return (i); + } + return (-1); +} + /* * returns 1 if connection should be dropped, 0 otherwise. * dropping starts at connection #max_startups_begin with a probability @@ -594,6 +693,8 @@ main(int ac, char **av) int listen_sock, maxfd; int startup_p[2]; int startups = 0; + Authctxt *authctxt; + int sp[2]; Key *key; int ret, key_used = 0; @@ -1231,23 +1332,84 @@ main(int ac, char **av) packet_set_nonblocking(); + if (!use_privsep) + goto skip_privilegeseparation; + + /* Set up unprivileged child process to deal with network data */ + monitor_socketpair(sp); + mm_recvfd = sp[0]; + mm_sendfd = sp[1]; + + /* Used to share zlib space across processes */ + mm_zback = mm_create(NULL, MM_MEMSIZE); + mm_zlib = mm_create(mm_zback, 20 * MM_MEMSIZE); + + /* Compression needs to share state across borders */ + mm_init_compression(mm_zlib); + + pid = fork(); + if (pid == -1) + fatal("fork of unprivileged child failed"); + else if (pid != 0) { + debug2("Network child is on pid %d", pid); + authctxt = monitor_child_preauth(mm_sendfd); + + /* The member allocation is not visible, so sync it */ + mm_share_sync(&mm_zlib, &mm_zback); + goto authenticated; + } else { + /* Demote the private keys to public keys. */ + demote_sensitive_data(); + + /* Change our root directory - /var/empty is standard*/ + if (chroot("/var/empty") == -1) + fatal("chroot(/var/empty)"); + if (chdir("/") == -1) + fatal("chdir(/)"); + + /* Drop our privileges */ + seteuid(32767); /* XXX - Niels */ + setuid(32767); + } + + skip_privilegeseparation: + /* perform the key exchange */ /* authenticate user and start session */ if (compat20) { do_ssh2_kex(); - do_authentication2(); + authctxt = do_authentication2(); + if (use_privsep) + mm_send_keystate(mm_recvfd); } else { do_ssh1_kex(); - do_authentication(); + authctxt = do_authentication(); } - /* The connection has been terminated. */ - verbose("Closing connection to %.100s", remote_ip); + + /* If we use privilege separation, the unprivileged child exits */ + if (use_privsep) + exit(0); + + authenticated: + /* + * In privilege separation, we fork another child and prepare + * file descriptor passing. + */ + if (use_privsep) + privsep_postauth(authctxt); + + /* Perform session preparation. */ + do_authenticated(authctxt); #ifdef USE_PAM finish_pam(); #endif /* USE_PAM */ packet_close(); + + if (use_privsep) + mm_terminate(mm_recvfd); + exit(0); } @@ -1453,8 +1615,6 @@ do_ssh1_kex(void) for (i = 0; i < 16; i++) session_id[i] = session_key[i] ^ session_key[i + 16]; } - /* Destroy the private and public keys. They will no longer be needed. */ - destroy_sensitive_data(); /* Destroy the decrypted integer. It is no longer needed. */ BN_clear_free(session_key_int); @@ -1502,6 +1662,7 @@ do_ssh2_kex(void) kex->client_version_string=client_version_string; kex->server_version_string=server_version_string; kex->load_host_key=&get_hostkey_by_type; + kex->host_key_index=&get_hostkey_index; xxx_kex = kex; -- cgit v1.2.3