Remove fstring from map_username. Create a more sane interface than the called-parame...
[kai/samba.git] / source3 / smbd / sesssetup.c
index a24843ff64c8e9b22c4cb159f9ef733dab3bde16..12d046038c9ce82a9fcaeaa5b2b1a236998d3f76 100644 (file)
 */
 
 #include "includes.h"
-
-extern struct auth_context *negprot_global_auth_context;
-extern bool global_encrypted_passwords_negotiated;
-extern bool global_spnego_negotiated;
-extern enum protocol_types Protocol;
-extern int max_send;
-
-uint32 global_client_caps = 0;
+#include "smbd/globals.h"
+#include "../libcli/auth/spnego.h"
+#include "../libcli/auth/ntlmssp.h"
+#include "ntlmssp_wrap.h"
+#include "librpc/gen_ndr/messaging.h"
+#include "../librpc/gen_ndr/krb5pac.h"
+#include "libads/kerberos_proto.h"
+
+/* For split krb5 SPNEGO blobs. */
+struct pending_auth_data {
+       struct pending_auth_data *prev, *next;
+       uint16 vuid; /* Tag for this entry. */
+       uint16 smbpid; /* Alternate tag for this entry. */
+       size_t needed_len;
+       DATA_BLOB partial_data;
+};
 
 /*
   on a logon error possibly map the error to success if "map to guest"
   is set approriately
 */
-static NTSTATUS do_map_to_guest(NTSTATUS status,
-                               auth_serversupplied_info **server_info,
-                               const char *user, const char *domain)
+NTSTATUS do_map_to_guest(NTSTATUS status,
+                       struct auth_serversupplied_info **server_info,
+                       const char *user, const char *domain)
 {
+       user = user ? user : "";
+       domain = domain ? domain : "";
+
        if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
                if ((lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_USER) ||
                    (lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_PASSWORD)) {
@@ -76,7 +87,7 @@ static int push_signature(uint8 **outbuf)
        if (tmp == -1) return -1;
        result += tmp;
 
-       if (asprintf(&lanman, "Samba %s", SAMBA_VERSION_STRING) != -1) {
+       if (asprintf(&lanman, "Samba %s", samba_version_string()) != -1) {
                tmp = message_push_string(outbuf, lanman, STR_TERMINATE);
                SAFE_FREE(lanman);
        }
@@ -95,25 +106,6 @@ static int push_signature(uint8 **outbuf)
        return result;
 }
 
-/****************************************************************************
- Start the signing engine if needed. Don't fail signing here.
-****************************************************************************/
-
-static void sessionsetup_start_signing_engine(
-                       const auth_serversupplied_info *server_info,
-                       const uint8 *inbuf)
-{
-       if (!server_info->guest && !srv_signing_started()) {
-               /* We need to start the signing engine
-                * here but a W2K client sends the old
-                * "BSRSPYL " signature instead of the
-                * correct one. Subsequent packets will
-                * be correct.
-                */
-               srv_check_sign_mac((char *)inbuf, False);
-       }
-}
-
 /****************************************************************************
  Send a security blob via a session setup reply.
 ****************************************************************************/
@@ -143,32 +135,30 @@ static void reply_sesssetup_blob(struct smb_request *req,
  Do a 'guest' logon, getting back the
 ****************************************************************************/
 
-static NTSTATUS check_guest_password(auth_serversupplied_info **server_info)
+static NTSTATUS check_guest_password(struct auth_serversupplied_info **server_info)
 {
        struct auth_context *auth_context;
-       auth_usersupplied_info *user_info = NULL;
+       struct auth_usersupplied_info *user_info = NULL;
 
        NTSTATUS nt_status;
-       unsigned char chal[8];
-
-       ZERO_STRUCT(chal);
+       static unsigned char chal[8] = { 0, };
 
        DEBUG(3,("Got anonymous request\n"));
 
-       if (!NT_STATUS_IS_OK(nt_status = make_auth_context_fixed(&auth_context,
-                                       chal))) {
+       nt_status = make_auth_context_fixed(talloc_tos(), &auth_context, chal);
+       if (!NT_STATUS_IS_OK(nt_status)) {
                return nt_status;
        }
 
        if (!make_user_info_guest(&user_info)) {
-               (auth_context->free)(&auth_context);
+               TALLOC_FREE(auth_context);
                return NT_STATUS_NO_MEMORY;
        }
 
        nt_status = auth_context->check_ntlm_password(auth_context,
                                                user_info,
                                                server_info);
-       (auth_context->free)(&auth_context);
+       TALLOC_FREE(auth_context);
        free_user_info(&user_info);
        return nt_status;
 }
@@ -251,22 +241,22 @@ static void reply_spnego_kerberos(struct smb_request *req,
 {
        TALLOC_CTX *mem_ctx;
        DATA_BLOB ticket;
-       char *client, *p, *domain;
-       fstring netbios_domain_name;
        struct passwd *pw;
-       fstring user;
        int sess_vuid = req->vuid;
        NTSTATUS ret = NT_STATUS_OK;
-       struct PAC_DATA *pac_data = NULL;
        DATA_BLOB ap_rep, ap_rep_wrapped, response;
-       auth_serversupplied_info *server_info = NULL;
+       struct auth_serversupplied_info *server_info = NULL;
        DATA_BLOB session_key = data_blob_null;
        uint8 tok_id[2];
        DATA_BLOB nullblob = data_blob_null;
-       fstring real_username;
        bool map_domainuser_to_guest = False;
        bool username_was_mapped;
        struct PAC_LOGON_INFO *logon_info = NULL;
+       struct smbd_server_connection *sconn = req->sconn;
+       char *principal;
+       char *user;
+       char *domain;
+       char *real_username;
 
        ZERO_STRUCT(ticket);
        ZERO_STRUCT(ap_rep);
@@ -282,14 +272,14 @@ static void reply_spnego_kerberos(struct smb_request *req,
                return;
        }
 
-       if (!spnego_parse_krb5_wrap(*secblob, &ticket, tok_id)) {
+       if (!spnego_parse_krb5_wrap(mem_ctx, *secblob, &ticket, tok_id)) {
                talloc_destroy(mem_ctx);
                reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
                return;
        }
 
        ret = ads_verify_ticket(mem_ctx, lp_realm(), 0, &ticket,
-                               &client, &pac_data, &ap_rep,
+                               &principal, &logon_info, &ap_rep,
                                &session_key, True);
 
        data_blob_free(&ticket);
@@ -350,181 +340,43 @@ static void reply_spnego_kerberos(struct smb_request *req,
                return;
        }
 
-       DEBUG(3,("Ticket name is [%s]\n", client));
-
-       p = strchr_m(client, '@');
-       if (!p) {
-               DEBUG(3,("Doesn't look like a valid principal\n"));
+       ret = get_user_from_kerberos_info(talloc_tos(),
+                                         sconn->client_id.name,
+                                         principal, logon_info,
+                                         &username_was_mapped,
+                                         &map_domainuser_to_guest,
+                                         &user, &domain,
+                                         &real_username, &pw);
+       if (!NT_STATUS_IS_OK(ret)) {
                data_blob_free(&ap_rep);
                data_blob_free(&session_key);
-               SAFE_FREE(client);
                talloc_destroy(mem_ctx);
                reply_nterror(req,nt_status_squash(NT_STATUS_LOGON_FAILURE));
                return;
        }
 
-       *p = 0;
-
        /* save the PAC data if we have it */
-
-       if (pac_data) {
-               logon_info = get_logon_info_from_pac(pac_data);
-               if (logon_info) {
-                       netsamlogon_cache_store( client, &logon_info->info3 );
-               }
-       }
-
-       if (!strequal(p+1, lp_realm())) {
-               DEBUG(3,("Ticket for foreign realm %s@%s\n", client, p+1));
-               if (!lp_allow_trusted_domains()) {
-                       data_blob_free(&ap_rep);
-                       data_blob_free(&session_key);
-                       SAFE_FREE(client);
-                       talloc_destroy(mem_ctx);
-                       reply_nterror(req, nt_status_squash(
-                                             NT_STATUS_LOGON_FAILURE));
-                       return;
-               }
-       }
-
-       /* this gives a fully qualified user name (ie. with full realm).
-          that leads to very long usernames, but what else can we do? */
-
-       domain = p+1;
-
-       if (logon_info && logon_info->info3.base.domain.string) {
-               fstrcpy(netbios_domain_name,
-                       logon_info->info3.base.domain.string);
-               domain = netbios_domain_name;
-               DEBUG(10, ("Mapped to [%s] (using PAC)\n", domain));
-
-       } else {
-
-               /* If we have winbind running, we can (and must) shorten the
-                  username by using the short netbios name. Otherwise we will
-                  have inconsistent user names. With Kerberos, we get the
-                  fully qualified realm, with ntlmssp we get the short
-                  name. And even w2k3 does use ntlmssp if you for example
-                  connect to an ip address. */
-
-               wbcErr wbc_status;
-               struct wbcDomainInfo *info = NULL;
-
-               DEBUG(10, ("Mapping [%s] to short name\n", domain));
-
-               wbc_status = wbcDomainInfo(domain, &info);
-
-               if (WBC_ERROR_IS_OK(wbc_status)) {
-
-                       fstrcpy(netbios_domain_name,
-                               info->short_name);
-
-                       wbcFreeMemory(info);
-                       domain = netbios_domain_name;
-                       DEBUG(10, ("Mapped to [%s] (using Winbind)\n", domain));
-               } else {
-                       DEBUG(3, ("Could not find short name: %s\n",
-                               wbcErrorString(wbc_status)));
-               }
-       }
-
-       fstr_sprintf(user, "%s%c%s", domain, *lp_winbind_separator(), client);
-
-       /* lookup the passwd struct, create a new user if necessary */
-
-       username_was_mapped = map_username( user );
-
-       pw = smb_getpwnam( mem_ctx, user, real_username, True );
-
-       if (pw) {
-               /* if a real user check pam account restrictions */
-               /* only really perfomed if "obey pam restriction" is true */
-               /* do this before an eventual mapping to guest occurs */
-               ret = smb_pam_accountcheck(pw->pw_name);
-               if (  !NT_STATUS_IS_OK(ret)) {
-                       DEBUG(1,("PAM account restriction "
-                               "prevents user login\n"));
-                       data_blob_free(&ap_rep);
-                       data_blob_free(&session_key);
-                       TALLOC_FREE(mem_ctx);
-                       reply_nterror(req, nt_status_squash(ret));
-                       return;
-               }
-       }
-
-       if (!pw) {
-
-               /* this was originally the behavior of Samba 2.2, if a user
-                  did not have a local uid but has been authenticated, then
-                  map them to a guest account */
-
-               if (lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_UID){
-                       map_domainuser_to_guest = True;
-                       fstrcpy(user,lp_guestaccount());
-                       pw = smb_getpwnam( mem_ctx, user, real_username, True );
-               }
-
-               /* extra sanity check that the guest account is valid */
-
-               if ( !pw ) {
-                       DEBUG(1,("Username %s is invalid on this system\n",
-                               user));
-                       SAFE_FREE(client);
-                       data_blob_free(&ap_rep);
-                       data_blob_free(&session_key);
-                       TALLOC_FREE(mem_ctx);
-                       reply_nterror(req, nt_status_squash(
-                                             NT_STATUS_LOGON_FAILURE));
-                       return;
-               }
+       if (logon_info) {
+               netsamlogon_cache_store(user, &logon_info->info3);
        }
 
        /* setup the string used by %U */
+       sub_set_smb_name(real_username);
 
-       sub_set_smb_name( real_username );
-       reload_services(True);
+       /* reload services so that the new %U is taken into account */
+       reload_services(sconn->msg_ctx, sconn->sock, True);
 
-       if ( map_domainuser_to_guest ) {
-               make_server_info_guest(NULL, &server_info);
-       } else if (logon_info) {
-               /* pass the unmapped username here since map_username()
-                  will be called again from inside make_server_info_info3() */
-
-               ret = make_server_info_info3(mem_ctx, client, domain,
-                                            &server_info, &logon_info->info3);
-               if ( !NT_STATUS_IS_OK(ret) ) {
-                       DEBUG(1,("make_server_info_info3 failed: %s!\n",
-                                nt_errstr(ret)));
-                       SAFE_FREE(client);
-                       data_blob_free(&ap_rep);
-                       data_blob_free(&session_key);
-                       TALLOC_FREE(mem_ctx);
-                       reply_nterror(req, nt_status_squash(ret));
-                       return;
-               }
-
-       } else {
-               ret = make_server_info_pw(&server_info, real_username, pw);
-
-               if ( !NT_STATUS_IS_OK(ret) ) {
-                       DEBUG(1,("make_server_info_pw failed: %s!\n",
-                                nt_errstr(ret)));
-                       SAFE_FREE(client);
-                       data_blob_free(&ap_rep);
-                       data_blob_free(&session_key);
-                       TALLOC_FREE(mem_ctx);
-                       reply_nterror(req, nt_status_squash(ret));
-                       return;
-               }
-
-               /* make_server_info_pw does not set the domain. Without this
-                * we end up with the local netbios name in substitutions for
-                * %D. */
-
-               if (server_info->sam_account != NULL) {
-                       pdb_set_domain(server_info->sam_account,
-                                       domain, PDB_SET);
-               }
+       ret = make_server_info_krb5(mem_ctx,
+                                   user, domain, real_username, pw,
+                                   logon_info, map_domainuser_to_guest,
+                                   &server_info);
+       if (!NT_STATUS_IS_OK(ret)) {
+               DEBUG(1, ("make_server_info_krb5 failed!\n"));
+               data_blob_free(&ap_rep);
+               data_blob_free(&session_key);
+               TALLOC_FREE(mem_ctx);
+               reply_nterror(req, nt_status_squash(ret));
+               return;
        }
 
        server_info->nss_token |= username_was_mapped;
@@ -537,7 +389,6 @@ static void reply_spnego_kerberos(struct smb_request *req,
                if ( !NT_STATUS_IS_OK(ret) ) {
                        DEBUG(10,("failed to create local token: %s\n",
                                nt_errstr(ret)));
-                       SAFE_FREE(client);
                        data_blob_free(&ap_rep);
                        data_blob_free(&session_key);
                        TALLOC_FREE( mem_ctx );
@@ -547,25 +398,24 @@ static void reply_spnego_kerberos(struct smb_request *req,
                }
        }
 
-       /* register_existing_vuid keeps the server info */
-       /* register_existing_vuid takes ownership of session_key on success,
-        * no need to free after this on success. A better interface would copy
-        * it.... */
-
-       if (!is_partial_auth_vuid(sess_vuid)) {
-               sess_vuid = register_initial_vuid();
+       if (!is_partial_auth_vuid(sconn, sess_vuid)) {
+               sess_vuid = register_initial_vuid(sconn);
        }
 
        data_blob_free(&server_info->user_session_key);
+       /* Set the kerberos-derived session key onto the server_info */
        server_info->user_session_key = session_key;
+       talloc_steal(server_info, session_key.data);
+
        session_key = data_blob_null;
 
-       sess_vuid = register_existing_vuid(sess_vuid,
-                                       server_info,
-                                       nullblob,
-                                       client);
+       /* register_existing_vuid keeps the server info */
+       /* register_existing_vuid takes ownership of session_key on success,
+        * no need to free after this on success. A better interface would copy
+        * it.... */
 
-       SAFE_FREE(client);
+       sess_vuid = register_existing_vuid(sconn, sess_vuid,
+                                          server_info, nullblob, user);
 
        reply_outbuf(req, 4, 0);
        SSVAL(req->outbuf,smb_uid,sess_vuid);
@@ -574,7 +424,7 @@ static void reply_spnego_kerberos(struct smb_request *req,
                ret = NT_STATUS_LOGON_FAILURE;
        } else {
                /* current_user_info is changed on new vuid */
-               reload_services( True );
+               reload_services(sconn->msg_ctx, sconn->sock, True);
 
                SSVAL(req->outbuf, smb_vwv3, 0);
 
@@ -584,19 +434,18 @@ static void reply_spnego_kerberos(struct smb_request *req,
 
                SSVAL(req->outbuf, smb_uid, sess_vuid);
 
-               sessionsetup_start_signing_engine(server_info, req->inbuf);
                /* Successful logon. Keep this vuid. */
                *p_invalidate_vuid = False;
        }
 
         /* wrap that up in a nice GSS-API wrapping */
        if (NT_STATUS_IS_OK(ret)) {
-               ap_rep_wrapped = spnego_gen_krb5_wrap(ap_rep,
+               ap_rep_wrapped = spnego_gen_krb5_wrap(talloc_tos(), ap_rep,
                                TOK_ID_KRB_AP_REP);
        } else {
                ap_rep_wrapped = data_blob_null;
        }
-       response = spnego_gen_auth_response(&ap_rep_wrapped, ret,
+       response = spnego_gen_auth_response(talloc_tos(), &ap_rep_wrapped, ret,
                        mechOID);
        reply_sesssetup_blob(req, response, ret);
 
@@ -618,21 +467,28 @@ static void reply_spnego_kerberos(struct smb_request *req,
 
 static void reply_spnego_ntlmssp(struct smb_request *req,
                                 uint16 vuid,
-                                AUTH_NTLMSSP_STATE **auth_ntlmssp_state,
+                                struct auth_ntlmssp_state **auth_ntlmssp_state,
                                 DATA_BLOB *ntlmssp_blob, NTSTATUS nt_status,
                                 const char *OID,
                                 bool wrap)
 {
+       bool do_invalidate = true;
        DATA_BLOB response;
        struct auth_serversupplied_info *server_info = NULL;
+       struct smbd_server_connection *sconn = req->sconn;
 
        if (NT_STATUS_IS_OK(nt_status)) {
-               server_info = (*auth_ntlmssp_state)->server_info;
+               nt_status = auth_ntlmssp_steal_server_info(talloc_tos(),
+                                       (*auth_ntlmssp_state), &server_info);
        } else {
+               /* Note that this server_info won't have a session
+                * key.  But for map to guest, that's exactly the right
+                * thing - we can't reasonably guess the key the
+                * client wants, as the password was wrong */
                nt_status = do_map_to_guest(nt_status,
-                           &server_info,
-                           (*auth_ntlmssp_state)->ntlmssp_state->user,
-                           (*auth_ntlmssp_state)->ntlmssp_state->domain);
+                                           &server_info,
+                                           auth_ntlmssp_get_username(*auth_ntlmssp_state),
+                                           auth_ntlmssp_get_domain(*auth_ntlmssp_state));
        }
 
        reply_outbuf(req, 4, 0);
@@ -642,46 +498,40 @@ static void reply_spnego_ntlmssp(struct smb_request *req,
        if (NT_STATUS_IS_OK(nt_status)) {
                DATA_BLOB nullblob = data_blob_null;
 
-               if (!is_partial_auth_vuid(vuid)) {
+               if (!is_partial_auth_vuid(sconn, vuid)) {
                        nt_status = NT_STATUS_LOGON_FAILURE;
                        goto out;
                }
 
-               data_blob_free(&server_info->user_session_key);
-               server_info->user_session_key =
-                       data_blob_talloc(
-                       server_info,
-                       (*auth_ntlmssp_state)->ntlmssp_state->session_key.data,
-                       (*auth_ntlmssp_state)->ntlmssp_state->session_key.length);
-
                /* register_existing_vuid keeps the server info */
-               if (register_existing_vuid(vuid,
-                               server_info, nullblob,
-                               (*auth_ntlmssp_state)->ntlmssp_state->user) !=
-                                       vuid) {
+               if (register_existing_vuid(sconn, vuid,
+                                          server_info, nullblob,
+                                          auth_ntlmssp_get_username(*auth_ntlmssp_state)) !=
+                                          vuid) {
+                       /* The problem is, *auth_ntlmssp_state points
+                        * into the vuser this will have
+                        * talloc_free()'ed in
+                        * register_existing_vuid() */
+                       do_invalidate = false;
                        nt_status = NT_STATUS_LOGON_FAILURE;
                        goto out;
                }
 
-               (*auth_ntlmssp_state)->server_info = NULL;
-
                /* current_user_info is changed on new vuid */
-               reload_services( True );
+               reload_services(sconn->msg_ctx, sconn->sock, True);
 
                SSVAL(req->outbuf, smb_vwv3, 0);
 
                if (server_info->guest) {
                        SSVAL(req->outbuf,smb_vwv2,1);
                }
-
-               sessionsetup_start_signing_engine(server_info,
-                                                 (uint8 *)req->inbuf);
        }
 
   out:
 
        if (wrap) {
-               response = spnego_gen_auth_response(ntlmssp_blob,
+               response = spnego_gen_auth_response(talloc_tos(),
+                               ntlmssp_blob,
                                nt_status, OID);
        } else {
                response = *ntlmssp_blob;
@@ -697,10 +547,12 @@ static void reply_spnego_ntlmssp(struct smb_request *req,
 
        if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
                /* NB. This is *NOT* an error case. JRA */
-               auth_ntlmssp_end(auth_ntlmssp_state);
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       /* Kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+               if (do_invalidate) {
+                       TALLOC_FREE(*auth_ntlmssp_state);
+                       if (!NT_STATUS_IS_OK(nt_status)) {
+                               /* Kill the intermediate vuid */
+                               invalidate_vuid(sconn, vuid);
+                       }
                }
        }
 }
@@ -709,7 +561,8 @@ static void reply_spnego_ntlmssp(struct smb_request *req,
  Is this a krb5 mechanism ?
 ****************************************************************************/
 
-NTSTATUS parse_spnego_mechanisms(DATA_BLOB blob_in,
+NTSTATUS parse_spnego_mechanisms(TALLOC_CTX *ctx,
+               DATA_BLOB blob_in,
                DATA_BLOB *pblob_out,
                char **kerb_mechOID)
 {
@@ -720,7 +573,8 @@ NTSTATUS parse_spnego_mechanisms(DATA_BLOB blob_in,
        *kerb_mechOID = NULL;
 
        /* parse out the OIDs and the first sec blob */
-       if (!parse_negTokenTarg(blob_in, OIDs, pblob_out)) {
+       if (!spnego_parse_negTokenInit(ctx, blob_in, OIDs, NULL, pblob_out) ||
+                       (OIDs[0] == NULL)) {
                return NT_STATUS_LOGON_FAILURE;
        }
 
@@ -737,7 +591,7 @@ NTSTATUS parse_spnego_mechanisms(DATA_BLOB blob_in,
 #ifdef HAVE_KRB5
        if (strcmp(OID_KERBEROS5, OIDs[0]) == 0 ||
            strcmp(OID_KERBEROS5_OLD, OIDs[0]) == 0) {
-               *kerb_mechOID = SMB_STRDUP(OIDs[0]);
+               *kerb_mechOID = talloc_strdup(ctx, OIDs[0]);
                if (*kerb_mechOID == NULL) {
                        ret = NT_STATUS_NO_MEMORY;
                }
@@ -766,7 +620,7 @@ static void reply_spnego_downgrade_to_ntlmssp(struct smb_request *req,
        DEBUG(3,("reply_spnego_downgrade_to_ntlmssp: Got krb5 ticket in SPNEGO "
                "but set to downgrade to NTLMSSP\n"));
 
-       response = spnego_gen_auth_response(NULL,
+       response = spnego_gen_auth_response(talloc_tos(), NULL,
                        NT_STATUS_MORE_PROCESSING_REQUIRED,
                        OID_NTLMSSP);
        reply_sesssetup_blob(req, response, NT_STATUS_MORE_PROCESSING_REQUIRED);
@@ -780,17 +634,19 @@ static void reply_spnego_downgrade_to_ntlmssp(struct smb_request *req,
 static void reply_spnego_negotiate(struct smb_request *req,
                                   uint16 vuid,
                                   DATA_BLOB blob1,
-                                  AUTH_NTLMSSP_STATE **auth_ntlmssp_state)
+                                  struct auth_ntlmssp_state **auth_ntlmssp_state)
 {
        DATA_BLOB secblob;
        DATA_BLOB chal;
        char *kerb_mech = NULL;
        NTSTATUS status;
+       struct smbd_server_connection *sconn = req->sconn;
 
-       status = parse_spnego_mechanisms(blob1, &secblob, &kerb_mech);
+       status = parse_spnego_mechanisms(talloc_tos(),
+                       blob1, &secblob, &kerb_mech);
        if (!NT_STATUS_IS_OK(status)) {
                /* Kill the intermediate vuid */
-               invalidate_vuid(vuid);
+               invalidate_vuid(sconn, vuid);
                reply_nterror(req, nt_status_squash(status));
                return;
        }
@@ -800,22 +656,22 @@ static void reply_spnego_negotiate(struct smb_request *req,
 
 #ifdef HAVE_KRB5
        if (kerb_mech && ((lp_security()==SEC_ADS) ||
-                               lp_use_kerberos_keytab()) ) {
+                               USE_KERBEROS_KEYTAB) ) {
                bool destroy_vuid = True;
                reply_spnego_kerberos(req, &secblob, kerb_mech,
                                      vuid, &destroy_vuid);
                data_blob_free(&secblob);
                if (destroy_vuid) {
                        /* Kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+                       invalidate_vuid(sconn, vuid);
                }
-               SAFE_FREE(kerb_mech);
+               TALLOC_FREE(kerb_mech);
                return;
        }
 #endif
 
        if (*auth_ntlmssp_state) {
-               auth_ntlmssp_end(auth_ntlmssp_state);
+               TALLOC_FREE(*auth_ntlmssp_state);
        }
 
        if (kerb_mech) {
@@ -823,14 +679,14 @@ static void reply_spnego_negotiate(struct smb_request *req,
                /* The mechtoken is a krb5 ticket, but
                 * we need to fall back to NTLM. */
                reply_spnego_downgrade_to_ntlmssp(req, vuid);
-               SAFE_FREE(kerb_mech);
+               TALLOC_FREE(kerb_mech);
                return;
        }
 
        status = auth_ntlmssp_start(auth_ntlmssp_state);
        if (!NT_STATUS_IS_OK(status)) {
                /* Kill the intermediate vuid */
-               invalidate_vuid(vuid);
+               invalidate_vuid(sconn, vuid);
                reply_nterror(req, nt_status_squash(status));
                return;
        }
@@ -856,19 +712,20 @@ static void reply_spnego_negotiate(struct smb_request *req,
 static void reply_spnego_auth(struct smb_request *req,
                              uint16 vuid,
                              DATA_BLOB blob1,
-                             AUTH_NTLMSSP_STATE **auth_ntlmssp_state)
+                             struct auth_ntlmssp_state **auth_ntlmssp_state)
 {
        DATA_BLOB auth = data_blob_null;
        DATA_BLOB auth_reply = data_blob_null;
        DATA_BLOB secblob = data_blob_null;
        NTSTATUS status = NT_STATUS_LOGON_FAILURE;
+       struct smbd_server_connection *sconn = req->sconn;
 
-       if (!spnego_parse_auth(blob1, &auth)) {
+       if (!spnego_parse_auth(talloc_tos(), blob1, &auth)) {
 #if 0
                file_save("auth.dat", blob1.data, blob1.length);
 #endif
                /* Kill the intermediate vuid */
-               invalidate_vuid(vuid);
+               invalidate_vuid(sconn, vuid);
 
                reply_nterror(req, nt_status_squash(
                                      NT_STATUS_LOGON_FAILURE));
@@ -879,11 +736,12 @@ static void reply_spnego_auth(struct smb_request *req,
                /* Might be a second negTokenTarg packet */
                char *kerb_mech = NULL;
 
-               status = parse_spnego_mechanisms(auth, &secblob, &kerb_mech);
+               status = parse_spnego_mechanisms(talloc_tos(),
+                               auth, &secblob, &kerb_mech);
 
                if (!NT_STATUS_IS_OK(status)) {
                        /* Kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+                       invalidate_vuid(sconn, vuid);
                        reply_nterror(req, nt_status_squash(status));
                        return;
                }
@@ -892,7 +750,7 @@ static void reply_spnego_auth(struct smb_request *req,
                                (unsigned long)secblob.length));
 #ifdef HAVE_KRB5
                if (kerb_mech && ((lp_security()==SEC_ADS) ||
-                                       lp_use_kerberos_keytab()) ) {
+                                       USE_KERBEROS_KEYTAB)) {
                        bool destroy_vuid = True;
                        reply_spnego_kerberos(req, &secblob, kerb_mech,
                                              vuid, &destroy_vuid);
@@ -900,9 +758,9 @@ static void reply_spnego_auth(struct smb_request *req,
                        data_blob_free(&auth);
                        if (destroy_vuid) {
                                /* Kill the intermediate vuid */
-                               invalidate_vuid(vuid);
+                               invalidate_vuid(sconn, vuid);
                        }
-                       SAFE_FREE(kerb_mech);
+                       TALLOC_FREE(kerb_mech);
                        return;
                }
 #endif
@@ -911,14 +769,14 @@ static void reply_spnego_auth(struct smb_request *req,
 
                if (kerb_mech) {
                        /* Kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+                       invalidate_vuid(sconn, vuid);
                        DEBUG(3,("reply_spnego_auth: network "
                                "misconfiguration, client sent us a "
                                "krb5 ticket and kerberos security "
                                "not enabled\n"));
                        reply_nterror(req, nt_status_squash(
                                        NT_STATUS_LOGON_FAILURE));
-                       SAFE_FREE(kerb_mech);
+                       TALLOC_FREE(kerb_mech);
                }
        }
 
@@ -929,7 +787,7 @@ static void reply_spnego_auth(struct smb_request *req,
                status = auth_ntlmssp_start(auth_ntlmssp_state);
                if (!NT_STATUS_IS_OK(status)) {
                        /* Kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+                       invalidate_vuid(sconn, vuid);
                        reply_nterror(req, nt_status_squash(status));
                        return;
                }
@@ -952,22 +810,17 @@ static void reply_spnego_auth(struct smb_request *req,
        return;
 }
 
-/****************************************************************************
- List to store partial SPNEGO auth fragments.
-****************************************************************************/
-
-static struct pending_auth_data *pd_list;
-
 /****************************************************************************
  Delete an entry on the list.
 ****************************************************************************/
 
-static void delete_partial_auth(struct pending_auth_data *pad)
+static void delete_partial_auth(struct smbd_server_connection *sconn,
+                               struct pending_auth_data *pad)
 {
        if (!pad) {
                return;
        }
-       DLIST_REMOVE(pd_list, pad);
+       DLIST_REMOVE(sconn->smb1.pd_list, pad);
        data_blob_free(&pad->partial_data);
        SAFE_FREE(pad);
 }
@@ -976,11 +829,17 @@ static void delete_partial_auth(struct pending_auth_data *pad)
  Search for a partial SPNEGO auth fragment matching an smbpid.
 ****************************************************************************/
 
-static struct pending_auth_data *get_pending_auth_data(uint16 smbpid)
+static struct pending_auth_data *get_pending_auth_data(
+               struct smbd_server_connection *sconn,
+               uint16_t smbpid)
 {
        struct pending_auth_data *pad;
-
-       for (pad = pd_list; pad; pad = pad->next) {
+/*
+ * NOTE: using the smbpid here is completely wrong...
+ *       see [MS-SMB]
+ *       3.3.5.3 Receiving an SMB_COM_SESSION_SETUP_ANDX Request
+ */
+       for (pad = sconn->smb1.pd_list; pad; pad = pad->next) {
                if (pad->smbpid == smbpid) {
                        break;
                }
@@ -994,20 +853,21 @@ static struct pending_auth_data *get_pending_auth_data(uint16 smbpid)
  the blob to be more than 64k.
 ****************************************************************************/
 
-static NTSTATUS check_spnego_blob_complete(uint16 smbpid, uint16 vuid,
-               DATA_BLOB *pblob)
+static NTSTATUS check_spnego_blob_complete(struct smbd_server_connection *sconn,
+                                          uint16 smbpid, uint16 vuid,
+                                          DATA_BLOB *pblob)
 {
        struct pending_auth_data *pad = NULL;
        ASN1_DATA *data;
        size_t needed_len = 0;
 
-       pad = get_pending_auth_data(smbpid);
+       pad = get_pending_auth_data(sconn, smbpid);
 
        /* Ensure we have some data. */
        if (pblob->length == 0) {
                /* Caller can cope. */
                DEBUG(2,("check_spnego_blob_complete: zero blob length !\n"));
-               delete_partial_auth(pad);
+               delete_partial_auth(sconn, pad);
                return NT_STATUS_OK;
        }
 
@@ -1028,7 +888,7 @@ static NTSTATUS check_spnego_blob_complete(uint16 smbpid, uint16 vuid,
                                (unsigned int)pad->partial_data.length,
                                (unsigned int)copy_len ));
 
-                       delete_partial_auth(pad);
+                       delete_partial_auth(sconn, pad);
                        return NT_STATUS_INVALID_PARAMETER;
                }
 
@@ -1064,7 +924,7 @@ static NTSTATUS check_spnego_blob_complete(uint16 smbpid, uint16 vuid,
                        data_blob_free(pblob);
                        *pblob = pad->partial_data;
                        ZERO_STRUCT(pad->partial_data);
-                       delete_partial_auth(pad);
+                       delete_partial_auth(sconn, pad);
                        return NT_STATUS_OK;
                }
 
@@ -1149,7 +1009,7 @@ static NTSTATUS check_spnego_blob_complete(uint16 smbpid, uint16 vuid,
        }
        pad->smbpid = smbpid;
        pad->vuid = vuid;
-       DLIST_ADD(pd_list, pad);
+       DLIST_ADD(sconn->smb1.pd_list, pad);
 
        return NT_STATUS_MORE_PROCESSING_REQUIRED;
 }
@@ -1175,6 +1035,7 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
        user_struct *vuser = NULL;
        NTSTATUS status = NT_STATUS_OK;
        uint16 smbpid = req->smbpid;
+       struct smbd_server_connection *sconn = req->sconn;
 
        DEBUG(3,("Doing spnego session setup\n"));
 
@@ -1203,7 +1064,7 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
        file_save("negotiate.dat", blob1.data, blob1.length);
 #endif
 
-       p2 = (char *)req->buf + data_blob_len;
+       p2 = (char *)req->buf + blob1.length;
 
        p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
                                     STR_TERMINATE);
@@ -1237,10 +1098,11 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
        }
 
        /* Did we get a valid vuid ? */
-       if (!is_partial_auth_vuid(vuid)) {
+       if (!is_partial_auth_vuid(sconn, vuid)) {
                /* No, then try and see if this is an intermediate sessionsetup
                 * for a large SPNEGO packet. */
-               struct pending_auth_data *pad = get_pending_auth_data(smbpid);
+               struct pending_auth_data *pad;
+               pad = get_pending_auth_data(sconn, smbpid);
                if (pad) {
                        DEBUG(10,("reply_sesssetup_and_X_spnego: found "
                                "pending vuid %u\n",
@@ -1250,9 +1112,9 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
        }
 
        /* Do we have a valid vuid now ? */
-       if (!is_partial_auth_vuid(vuid)) {
+       if (!is_partial_auth_vuid(sconn, vuid)) {
                /* No, start a new authentication setup. */
-               vuid = register_initial_vuid();
+               vuid = register_initial_vuid(sconn);
                if (vuid == UID_FIELD_INVALID) {
                        data_blob_free(&blob1);
                        reply_nterror(req, nt_status_squash(
@@ -1261,7 +1123,7 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
                }
        }
 
-       vuser = get_partial_auth_user_struct(vuid);
+       vuser = get_partial_auth_user_struct(sconn, vuid);
        /* This MUST be valid. */
        if (!vuser) {
                smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
@@ -1272,12 +1134,12 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
         * field is 4k. Bug #4400. JRA.
         */
 
-       status = check_spnego_blob_complete(smbpid, vuid, &blob1);
+       status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
        if (!NT_STATUS_IS_OK(status)) {
                if (!NT_STATUS_EQUAL(status,
                                NT_STATUS_MORE_PROCESSING_REQUIRED)) {
                        /* Real error - kill the intermediate vuid */
-                       invalidate_vuid(vuid);
+                       invalidate_vuid(sconn, vuid);
                }
                data_blob_free(&blob1);
                reply_nterror(req, nt_status_squash(status));
@@ -1311,7 +1173,7 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
                        status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
                        if (!NT_STATUS_IS_OK(status)) {
                                /* Kill the intermediate vuid */
-                               invalidate_vuid(vuid);
+                               invalidate_vuid(sconn, vuid);
                                data_blob_free(&blob1);
                                reply_nterror(req, nt_status_squash(status));
                                return;
@@ -1344,37 +1206,46 @@ static void reply_sesssetup_and_X_spnego(struct smb_request *req)
  a new session setup with VC==0 is ignored.
 ****************************************************************************/
 
-static int shutdown_other_smbds(struct db_record *rec,
-                               const struct connections_key *key,
+struct shutdown_state {
+       const char *ip;
+       struct messaging_context *msg_ctx;
+};
+
+static int shutdown_other_smbds(const struct connections_key *key,
                                const struct connections_data *crec,
                                void *private_data)
 {
-       const char *ip = (const char *)private_data;
+       struct shutdown_state *state = (struct shutdown_state *)private_data;
+
+       DEBUG(10, ("shutdown_other_smbds: %s, %s\n",
+                  procid_str(talloc_tos(), &crec->pid), crec->addr));
 
        if (!process_exists(crec->pid)) {
+               DEBUG(10, ("process does not exist\n"));
                return 0;
        }
 
        if (procid_is_me(&crec->pid)) {
+               DEBUG(10, ("It's me\n"));
                return 0;
        }
 
-       if (strcmp(ip, crec->addr) != 0) {
+       if (strcmp(state->ip, crec->addr) != 0) {
+               DEBUG(10, ("%s does not match %s\n", state->ip, crec->addr));
                return 0;
        }
 
-       DEBUG(0,("shutdown_other_smbds: shutting down pid %d "
-                "(IP %s)\n", procid_to_pid(&crec->pid), ip));
+       DEBUG(1, ("shutdown_other_smbds: shutting down pid %u "
+                 "(IP %s)\n", (unsigned int)procid_to_pid(&crec->pid),
+                 state->ip));
 
-       messaging_send(smbd_messaging_context(), crec->pid, MSG_SHUTDOWN,
+       messaging_send(state->msg_ctx, crec->pid, MSG_SHUTDOWN,
                       &data_blob_null);
        return 0;
 }
 
-static void setup_new_vc_session(void)
+static void setup_new_vc_session(struct smbd_server_connection *sconn)
 {
-       char addr[INET6_ADDRSTRLEN];
-
        DEBUG(2,("setup_new_vc_session: New VC == 0, if NT4.x "
                "compatible we would close all old resources.\n"));
 #if 0
@@ -1382,9 +1253,18 @@ static void setup_new_vc_session(void)
        invalidate_all_vuids();
 #endif
        if (lp_reset_on_zero_vc()) {
-               connections_forall(shutdown_other_smbds,
-                       CONST_DISCARD(void *,
-                       client_addr(get_client_fd(),addr,sizeof(addr))));
+               char *addr;
+               struct shutdown_state state;
+
+               addr = tsocket_address_inet_addr_string(
+                       sconn->remote_address, talloc_tos());
+               if (addr == NULL) {
+                       return;
+               }
+               state.ip = addr;
+               state.msg_ctx = sconn->msg_ctx;
+               connections_forall_read(shutdown_other_smbds, &state);
+               TALLOC_FREE(addr);
        }
 }
 
@@ -1401,19 +1281,19 @@ void reply_sesssetup_and_X(struct smb_request *req)
        DATA_BLOB plaintext_password;
        char *tmp;
        const char *user;
-       fstring sub_user; /* Sainitised username for substituion */
+       fstring sub_user; /* Sanitised username for substituion */
        const char *domain;
        const char *native_os;
        const char *native_lanman;
        const char *primary_domain;
-       static bool done_sesssetup = False;
-       auth_usersupplied_info *user_info = NULL;
-       auth_serversupplied_info *server_info = NULL;
+       struct auth_usersupplied_info *user_info = NULL;
+       struct auth_serversupplied_info *server_info = NULL;
        uint16 smb_flag2 = req->flags2;
 
        NTSTATUS nt_status;
+       struct smbd_server_connection *sconn = req->sconn;
 
-       bool doencrypt = global_encrypted_passwords_negotiated;
+       bool doencrypt = sconn->smb1.negprot.encrypted_passwords;
 
        START_PROFILE(SMBsesssetupX);
 
@@ -1428,7 +1308,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
        if (req->wct == 12 &&
            (req->flags2 & FLAGS2_EXTENDED_SECURITY)) {
 
-               if (!global_spnego_negotiated) {
+               if (!sconn->smb1.negprot.spnego) {
                        DEBUG(0,("reply_sesssetup_and_X:  Rejecting attempt "
                                 "at SPNEGO session setup when it was not "
                                 "negotiated.\n"));
@@ -1439,7 +1319,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
                }
 
                if (SVAL(req->vwv+4, 0) == 0) {
-                       setup_new_vc_session();
+                       setup_new_vc_session(req->sconn);
                }
 
                reply_sesssetup_and_X_spnego(req);
@@ -1449,7 +1329,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
 
        smb_bufsize = SVAL(req->vwv+2, 0);
 
-       if (Protocol < PROTOCOL_NT1) {
+       if (get_Protocol() < PROTOCOL_NT1) {
                uint16 passlen1 = SVAL(req->vwv+7, 0);
 
                /* Never do NT status codes with protocols before NT1 as we
@@ -1636,14 +1516,14 @@ void reply_sesssetup_and_X(struct smb_request *req)
        }
 
        if (SVAL(req->vwv+4, 0) == 0) {
-               setup_new_vc_session();
+               setup_new_vc_session(req->sconn);
        }
 
        DEBUG(3,("sesssetupX:name=[%s]\\[%s]@[%s]\n",
                                domain, user, get_remote_machine_name()));
 
        if (*user) {
-               if (global_spnego_negotiated) {
+               if (sconn->smb1.negprot.spnego) {
 
                        /* This has to be here, because this is a perfectly
                         * valid behaviour for guest logons :-( */
@@ -1663,18 +1543,25 @@ void reply_sesssetup_and_X(struct smb_request *req)
 
        sub_set_smb_name(sub_user);
 
-       reload_services(True);
+       reload_services(sconn->msg_ctx, sconn->sock, True);
 
        if (lp_security() == SEC_SHARE) {
+               char *sub_user_mapped = NULL;
                /* In share level we should ignore any passwords */
 
                data_blob_free(&lm_resp);
                data_blob_free(&nt_resp);
                data_blob_clear_free(&plaintext_password);
 
-               map_username(sub_user);
-               add_session_user(sub_user);
-               add_session_workgroup(domain);
+               (void)map_username(talloc_tos(), sub_user, &sub_user_mapped);
+               if (!sub_user_mapped) {
+                       reply_nterror(req, NT_STATUS_NO_MEMORY);
+                       END_PROFILE(SMBsesssetupX);
+                       return;
+               }
+               fstrcpy(sub_user, sub_user_mapped);
+               add_session_user(sconn, sub_user);
+               add_session_workgroup(sconn, domain);
                /* Then force it to null for the benfit of the code below */
                user = "";
        }
@@ -1684,7 +1571,9 @@ void reply_sesssetup_and_X(struct smb_request *req)
                nt_status = check_guest_password(&server_info);
 
        } else if (doencrypt) {
-               if (!negprot_global_auth_context) {
+               struct auth_context *negprot_auth_context = NULL;
+               negprot_auth_context = sconn->smb1.negprot.auth_context;
+               if (!negprot_auth_context) {
                        DEBUG(0, ("reply_sesssetup_and_X:  Attempted encrypted "
                                "session setup without negprot denied!\n"));
                        reply_nterror(req, nt_status_squash(
@@ -1696,21 +1585,22 @@ void reply_sesssetup_and_X(struct smb_request *req)
                                                domain,
                                                lm_resp, nt_resp);
                if (NT_STATUS_IS_OK(nt_status)) {
-                       nt_status = negprot_global_auth_context->check_ntlm_password(
-                                       negprot_global_auth_context,
+                       nt_status = negprot_auth_context->check_ntlm_password(
+                                       negprot_auth_context,
                                        user_info,
                                        &server_info);
                }
        } else {
                struct auth_context *plaintext_auth_context = NULL;
-               const uint8 *chal;
 
                nt_status = make_auth_context_subsystem(
-                               &plaintext_auth_context);
+                       talloc_tos(), &plaintext_auth_context);
 
                if (NT_STATUS_IS_OK(nt_status)) {
-                       chal = plaintext_auth_context->get_ntlm_challenge(
-                                       plaintext_auth_context);
+                       uint8_t chal[8];
+
+                       plaintext_auth_context->get_ntlm_challenge(
+                                       plaintext_auth_context, chal);
 
                        if (!make_user_info_for_reply(&user_info,
                                                      user, domain, chal,
@@ -1724,8 +1614,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
                                                user_info,
                                                &server_info);
 
-                               (plaintext_auth_context->free)(
-                                               &plaintext_auth_context);
+                               TALLOC_FREE(plaintext_auth_context);
                        }
                }
        }
@@ -1773,7 +1662,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
 
        /* it's ok - setup a reply */
        reply_outbuf(req, 3, 0);
-       if (Protocol >= PROTOCOL_NT1) {
+       if (get_Protocol() >= PROTOCOL_NT1) {
                push_signature(&req->outbuf);
                /* perhaps grab OS version here?? */
        }
@@ -1790,7 +1679,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
                TALLOC_FREE(server_info);
        } else {
                /* Ignore the initial vuid. */
-               sess_vuid = register_initial_vuid();
+               sess_vuid = register_initial_vuid(sconn);
                if (sess_vuid == UID_FIELD_INVALID) {
                        data_blob_free(&nt_resp);
                        data_blob_free(&lm_resp);
@@ -1800,7 +1689,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
                        return;
                }
                /* register_existing_vuid keeps the server info */
-               sess_vuid = register_existing_vuid(sess_vuid,
+               sess_vuid = register_existing_vuid(sconn, sess_vuid,
                                        server_info,
                                        nt_resp.data ? nt_resp : lm_resp,
                                        sub_user);
@@ -1814,9 +1703,7 @@ void reply_sesssetup_and_X(struct smb_request *req)
                }
 
                /* current_user_info is changed on new vuid */
-               reload_services( True );
-
-               sessionsetup_start_signing_engine(server_info, req->inbuf);
+               reload_services(sconn->msg_ctx, sconn->sock, True);
        }
 
        data_blob_free(&nt_resp);
@@ -1824,11 +1711,13 @@ void reply_sesssetup_and_X(struct smb_request *req)
 
        SSVAL(req->outbuf,smb_uid,sess_vuid);
        SSVAL(req->inbuf,smb_uid,sess_vuid);
+       req->vuid = sess_vuid;
 
-       if (!done_sesssetup)
-               max_send = MIN(max_send,smb_bufsize);
-
-       done_sesssetup = True;
+       if (!sconn->smb1.sessions.done_sesssetup) {
+               sconn->smb1.sessions.max_send =
+                       MIN(sconn->smb1.sessions.max_send,smb_bufsize);
+       }
+       sconn->smb1.sessions.done_sesssetup = true;
 
        END_PROFILE(SMBsesssetupX);
        chain_reply(req);