Remove fstring from map_username. Create a more sane interface than the called-parame...
[kai/samba.git] / source3 / smbd / password.c
index 9ee721089c95da04a1fa675a279d16b452325eb4..9be2b3b74659c110efd58d64954504e9173c2838 100644 (file)
@@ -1,44 +1,46 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
    Password and authentication handling
    Copyright (C) Andrew Tridgell 1992-1998
-   
+   Copyright (C) Jeremy Allison 2007.
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
+#include "smbd/globals.h"
+#include "../librpc/gen_ndr/netlogon.h"
 
-/* users from session setup */
-static char *session_userlist = NULL;
-static int len_session_userlist = 0;
-
-/* this holds info on user ids that are already validated for this VC */
-static user_struct *validated_users;
-static int next_vuid = VUID_OFFSET;
-static int num_validated_vuids;
-
-extern userdom_struct current_user_info;
-
+/* Fix up prototypes for OSX 10.4, where they're missing */
+#ifndef HAVE_SETNETGRENT_PROTOTYPE
+extern int setnetgrent(const char* netgroup);
+#endif
+#ifndef HAVE_GETNETGRENT_PROTOTYPE
+extern int getnetgrent(char **host, char **user, char **domain);
+#endif
+#ifndef HAVE_ENDNETGRENT_PROTOTYPE
+extern void endnetgrent(void);
+#endif
 
-/****************************************************************************
- Check if a uid has been validated, and return an pointer to the user_struct
- if it has. NULL if not. vuid is biased by an offset. This allows us to
- tell random client vuid's (normally zero) from valid vuids.
-****************************************************************************/
+enum server_allocated_state { SERVER_ALLOCATED_REQUIRED_YES,
+                               SERVER_ALLOCATED_REQUIRED_NO,
+                               SERVER_ALLOCATED_REQUIRED_ANY};
 
-user_struct *get_valid_user_struct(uint16 vuid)
+static user_struct *get_valid_user_struct_internal(
+                       struct smbd_server_connection *sconn,
+                       uint16 vuid,
+                       enum server_allocated_state server_allocated)
 {
        user_struct *usp;
        int count=0;
@@ -46,10 +48,25 @@ user_struct *get_valid_user_struct(uint16 vuid)
        if (vuid == UID_FIELD_INVALID)
                return NULL;
 
-       for (usp=validated_users;usp;usp=usp->next,count++) {
-               if (vuid == usp->vuid && usp->server_info) {
+       usp=sconn->smb1.sessions.validated_users;
+       for (;usp;usp=usp->next,count++) {
+               if (vuid == usp->vuid) {
+                       switch (server_allocated) {
+                               case SERVER_ALLOCATED_REQUIRED_YES:
+                                       if (usp->server_info == NULL) {
+                                               continue;
+                                       }
+                                       break;
+                               case SERVER_ALLOCATED_REQUIRED_NO:
+                                       if (usp->server_info != NULL) {
+                                               continue;
+                                       }
+                               case SERVER_ALLOCATED_REQUIRED_ANY:
+                                       break;
+                       }
                        if (count > 10) {
-                               DLIST_PROMOTE(validated_users, usp);
+                               DLIST_PROMOTE(sconn->smb1.sessions.validated_users,
+                                             usp);
                        }
                        return usp;
                }
@@ -59,354 +76,399 @@ user_struct *get_valid_user_struct(uint16 vuid)
 }
 
 /****************************************************************************
- Get the user struct of a partial NTLMSSP login
+ Check if a uid has been validated, and return an pointer to the user_struct
+ if it has. NULL if not. vuid is biased by an offset. This allows us to
+ tell random client vuid's (normally zero) from valid vuids.
 ****************************************************************************/
 
-user_struct *get_partial_auth_user_struct(uint16 vuid)
+user_struct *get_valid_user_struct(struct smbd_server_connection *sconn,
+                                  uint16 vuid)
 {
-       user_struct *usp;
-       int count=0;
+       return get_valid_user_struct_internal(sconn, vuid,
+                       SERVER_ALLOCATED_REQUIRED_YES);
+}
 
-       if (vuid == UID_FIELD_INVALID)
-               return NULL;
+bool is_partial_auth_vuid(struct smbd_server_connection *sconn, uint16 vuid)
+{
+       return (get_partial_auth_user_struct(sconn, vuid) != NULL);
+}
 
-       for (usp=validated_users;usp;usp=usp->next,count++) {
-               if (vuid == usp->vuid && !usp->server_info) {
-                       if (count > 10) {
-                               DLIST_PROMOTE(validated_users, usp);
-                       }
-                       return usp;
-               }
-       }
+/****************************************************************************
+ Get the user struct of a partial NTLMSSP login
+****************************************************************************/
 
-       return NULL;
+user_struct *get_partial_auth_user_struct(struct smbd_server_connection *sconn,
+                                         uint16 vuid)
+{
+       return get_valid_user_struct_internal(sconn, vuid,
+                       SERVER_ALLOCATED_REQUIRED_NO);
 }
 
 /****************************************************************************
  Invalidate a uid.
 ****************************************************************************/
 
-void invalidate_vuid(uint16 vuid)
+void invalidate_vuid(struct smbd_server_connection *sconn, uint16 vuid)
 {
-       user_struct *vuser = get_valid_user_struct(vuid);
+       user_struct *vuser = NULL;
 
-       if (vuser == NULL)
+       vuser = get_valid_user_struct_internal(sconn, vuid,
+                       SERVER_ALLOCATED_REQUIRED_ANY);
+       if (vuser == NULL) {
                return;
-       
-       SAFE_FREE(vuser->homedir);
-       SAFE_FREE(vuser->unix_homedir);
-       SAFE_FREE(vuser->logon_script);
-       
-       session_yield(vuser);
-       SAFE_FREE(vuser->session_keystr);
+       }
 
-       free_server_info(&vuser->server_info);
+       session_yield(vuser);
 
-       data_blob_free(&vuser->session_key);
+       if (vuser->auth_ntlmssp_state) {
+               TALLOC_FREE(vuser->auth_ntlmssp_state);
+       }
 
-       DLIST_REMOVE(validated_users, vuser);
+       DLIST_REMOVE(sconn->smb1.sessions.validated_users, vuser);
 
        /* clear the vuid from the 'cache' on each connection, and
           from the vuid 'owner' of connections */
-       conn_clear_vuid_cache(vuid);
+       conn_clear_vuid_caches(sconn, vuid);
 
-       SAFE_FREE(vuser->groups);
-       delete_nt_token(&vuser->nt_user_token);
-       SAFE_FREE(vuser);
-       num_validated_vuids--;
+       TALLOC_FREE(vuser);
+       sconn->smb1.sessions.num_validated_vuids--;
 }
 
 /****************************************************************************
  Invalidate all vuid entries for this process.
 ****************************************************************************/
 
-void invalidate_all_vuids(void)
+void invalidate_all_vuids(struct smbd_server_connection *sconn)
 {
-       user_struct *usp, *next=NULL;
+       if (sconn->using_smb2) {
+               return;
+       }
 
-       for (usp=validated_users;usp;usp=next) {
-               next = usp->next;
-               
-               invalidate_vuid(usp->vuid);
+       while (sconn->smb1.sessions.validated_users != NULL) {
+               invalidate_vuid(sconn,
+                               sconn->smb1.sessions.validated_users->vuid);
        }
 }
 
-/**
- *  register that a valid login has been performed, establish 'session'.
- *  @param server_info The token returned from the authentication process. 
- *   (now 'owned' by register_vuid)
- *
- *  @param session_key The User session key for the login session (now also 'owned' by register_vuid)
- *
- *  @param respose_blob The NT challenge-response, if available.  (May be freed after this call)
- *
- *  @param smb_name The untranslated name of the user
- *
- *  @return Newly allocated vuid, biased by an offset. (This allows us to
- *   tell random client vuid's (normally zero) from valid vuids.)
- *
- */
+static void increment_next_vuid(uint16_t *vuid)
+{
+       *vuid += 1;
+
+       /* Check for vuid wrap. */
+       if (*vuid == UID_FIELD_INVALID) {
+               *vuid = VUID_OFFSET;
+       }
+}
+
+/****************************************************
+ Create a new partial auth user struct.
+*****************************************************/
 
-int register_vuid(auth_serversupplied_info *server_info, DATA_BLOB session_key, DATA_BLOB response_blob, const char *smb_name)
+int register_initial_vuid(struct smbd_server_connection *sconn)
 {
-       user_struct *vuser = NULL;
+       user_struct *vuser;
 
-       /* Ensure no vuid gets registered in share level security. */
+       /* Paranoia check. */
        if(lp_security() == SEC_SHARE) {
-               data_blob_free(&session_key);
-               return UID_FIELD_INVALID;
+               smb_panic("register_initial_vuid: "
+                       "Tried to register uid in security=share");
        }
 
        /* Limit allowed vuids to 16bits - VUID_OFFSET. */
-       if (num_validated_vuids >= 0xFFFF-VUID_OFFSET) {
-               data_blob_free(&session_key);
+       if (sconn->smb1.sessions.num_validated_vuids >= 0xFFFF-VUID_OFFSET) {
                return UID_FIELD_INVALID;
        }
 
-       if((vuser = SMB_MALLOC_P(user_struct)) == NULL) {
-               DEBUG(0,("Failed to malloc users struct!\n"));
-               data_blob_free(&session_key);
+       if((vuser = talloc_zero(NULL, user_struct)) == NULL) {
+               DEBUG(0,("register_initial_vuid: "
+                               "Failed to talloc users struct!\n"));
                return UID_FIELD_INVALID;
        }
 
-       ZERO_STRUCTP(vuser);
-
-       /* Allocate a free vuid. Yes this is a linear search... :-) */
-       while( get_valid_user_struct(next_vuid) != NULL ) {
-               next_vuid++;
-               /* Check for vuid wrap. */
-               if (next_vuid == UID_FIELD_INVALID)
-                       next_vuid = VUID_OFFSET;
+       /* Allocate a free vuid. Yes this is a linear search... */
+       while( get_valid_user_struct_internal(sconn,
+                       sconn->smb1.sessions.next_vuid,
+                       SERVER_ALLOCATED_REQUIRED_ANY) != NULL ) {
+               increment_next_vuid(&sconn->smb1.sessions.next_vuid);
        }
 
-       DEBUG(10,("register_vuid: allocated vuid = %u\n", (unsigned int)next_vuid ));
+       DEBUG(10,("register_initial_vuid: allocated vuid = %u\n",
+               (unsigned int)sconn->smb1.sessions.next_vuid ));
 
-       vuser->vuid = next_vuid;
-
-       if (!server_info) {
-               next_vuid++;
-               num_validated_vuids++;
-               
-               vuser->server_info = NULL;
-               
-               DLIST_ADD(validated_users, vuser);
-               
-               return vuser->vuid;
-       }
+       vuser->vuid = sconn->smb1.sessions.next_vuid;
 
-       /* the next functions should be done by a SID mapping system (SMS) as
-        * the new real sam db won't have reference to unix uids or gids
+       /*
+        * This happens in an unfinished NTLMSSP session setup. We
+        * need to allocate a vuid between the first and second calls
+        * to NTLMSSP.
         */
-       
-       vuser->uid = server_info->uid;
-       vuser->gid = server_info->gid;
-       
-       vuser->n_groups = server_info->n_groups;
-       if (vuser->n_groups) {
-               if (!(vuser->groups = (gid_t *)memdup(server_info->groups, sizeof(gid_t) * vuser->n_groups))) {
-                       DEBUG(0,("register_vuid: failed to memdup vuser->groups\n"));
-                       data_blob_free(&session_key);
-                       free(vuser);
-                       free_server_info(&server_info);
-                       return UID_FIELD_INVALID;
-               }
-       }
+       increment_next_vuid(&sconn->smb1.sessions.next_vuid);
+       sconn->smb1.sessions.num_validated_vuids++;
 
-       vuser->guest = server_info->guest;
-       fstrcpy(vuser->user.unix_name, server_info->unix_name); 
+       DLIST_ADD(sconn->smb1.sessions.validated_users, vuser);
+       return vuser->vuid;
+}
 
-       /* This is a potentially untrusted username */
-       alpha_strcpy(vuser->user.smb_name, smb_name, ". _-$", sizeof(vuser->user.smb_name));
+int register_homes_share(const char *username)
+{
+       int result;
+       struct passwd *pwd;
+
+       result = lp_servicenumber(username);
+       if (result != -1) {
+               DEBUG(3, ("Using static (or previously created) service for "
+                         "user '%s'; path = '%s'\n", username,
+                         lp_pathname(result)));
+               return result;
+       }
 
-       fstrcpy(vuser->user.domain, pdb_get_domain(server_info->sam_account));
-       fstrcpy(vuser->user.full_name, pdb_get_fullname(server_info->sam_account));
+       pwd = Get_Pwnam_alloc(talloc_tos(), username);
 
-       {
-               /* Keep the homedir handy */
-               const char *homedir = pdb_get_homedir(server_info->sam_account);
-               const char *logon_script = pdb_get_logon_script(server_info->sam_account);
-
-               if (!IS_SAM_DEFAULT(server_info->sam_account, PDB_UNIXHOMEDIR)) {
-                       const char *unix_homedir = pdb_get_unix_homedir(server_info->sam_account);
-                       if (unix_homedir) {
-                               vuser->unix_homedir = smb_xstrdup(unix_homedir);
-                       }
-               } else {
-                       struct passwd *passwd = getpwnam_alloc(vuser->user.unix_name);
-                       if (passwd) {
-                               vuser->unix_homedir = smb_xstrdup(passwd->pw_dir);
-                               passwd_free(&passwd);
-                       }
-               }
-               
-               if (homedir) {
-                       vuser->homedir = smb_xstrdup(homedir);
-               }
-               if (logon_script) {
-                       vuser->logon_script = smb_xstrdup(logon_script);
-               }
+       if ((pwd == NULL) || (pwd->pw_dir[0] == '\0')) {
+               DEBUG(3, ("No home directory defined for user '%s'\n",
+                         username));
+               TALLOC_FREE(pwd);
+               return -1;
        }
 
-       vuser->session_key = session_key;
+       DEBUG(3, ("Adding homes service for user '%s' using home directory: "
+                 "'%s'\n", username, pwd->pw_dir));
+
+       result = add_home_service(username, username, pwd->pw_dir);
 
-       DEBUG(10,("register_vuid: (%u,%u) %s %s %s guest=%d\n", 
-                 (unsigned int)vuser->uid, 
-                 (unsigned int)vuser->gid,
-                 vuser->user.unix_name, vuser->user.smb_name, vuser->user.domain, vuser->guest ));
+       TALLOC_FREE(pwd);
+       return result;
+}
 
-       DEBUG(3, ("User name: %s\tReal name: %s\n",vuser->user.unix_name,vuser->user.full_name));       
+/**
+ *  register that a valid login has been performed, establish 'session'.
+ *  @param server_info The token returned from the authentication process.
+ *   (now 'owned' by register_existing_vuid)
+ *
+ *  @param session_key The User session key for the login session (now also
+ *  'owned' by register_existing_vuid)
+ *
+ *  @param respose_blob The NT challenge-response, if available.  (May be
+ *  freed after this call)
+ *
+ *  @param smb_name The untranslated name of the user
+ *
+ *  @return Newly allocated vuid, biased by an offset. (This allows us to
+ *   tell random client vuid's (normally zero) from valid vuids.)
+ *
+ */
 
-       if (server_info->ptok) {
-               vuser->nt_user_token = dup_nt_token(server_info->ptok);
-       } else {
-               DEBUG(1, ("server_info does not contain a user_token - cannot continue\n"));
-               free_server_info(&server_info);
-               data_blob_free(&session_key);
-               SAFE_FREE(vuser->homedir);
-               SAFE_FREE(vuser->unix_homedir);
-               SAFE_FREE(vuser->logon_script);
+int register_existing_vuid(struct smbd_server_connection *sconn,
+                       uint16 vuid,
+                       struct auth_serversupplied_info *server_info,
+                       DATA_BLOB response_blob,
+                       const char *smb_name)
+{
+       fstring tmp;
+       user_struct *vuser;
 
-               SAFE_FREE(vuser);
-               return UID_FIELD_INVALID;
+       vuser = get_partial_auth_user_struct(sconn, vuid);
+       if (!vuser) {
+               goto fail;
        }
 
-       /* use this to keep tabs on all our info from the authentication */
-       vuser->server_info = server_info;
-
-       DEBUG(3,("UNIX uid %d is UNIX user %s, and will be vuid %u\n",(int)vuser->uid,vuser->user.unix_name, vuser->vuid));
+       /* Use this to keep tabs on all our info from the authentication */
+       vuser->server_info = talloc_move(vuser, &server_info);
 
-       next_vuid++;
-       num_validated_vuids++;
+       /* This is a potentially untrusted username */
+       alpha_strcpy(tmp, smb_name, ". _-$", sizeof(tmp));
+
+       vuser->server_info->sanitized_username = talloc_strdup(
+               vuser->server_info, tmp);
+
+       DEBUG(10,("register_existing_vuid: (%u,%u) %s %s %s guest=%d\n",
+                 (unsigned int)vuser->server_info->utok.uid,
+                 (unsigned int)vuser->server_info->utok.gid,
+                 vuser->server_info->unix_name,
+                 vuser->server_info->sanitized_username,
+                 vuser->server_info->info3->base.domain.string,
+                 vuser->server_info->guest ));
+
+       DEBUG(3, ("register_existing_vuid: User name: %s\t"
+                 "Real name: %s\n", vuser->server_info->unix_name,
+                 vuser->server_info->info3->base.full_name.string));
+
+       if (!vuser->server_info->ptok) {
+               DEBUG(1, ("register_existing_vuid: server_info does not "
+                       "contain a user_token - cannot continue\n"));
+               goto fail;
+       }
 
-       DLIST_ADD(validated_users, vuser);
+       DEBUG(3,("register_existing_vuid: UNIX uid %d is UNIX user %s, "
+               "and will be vuid %u\n", (int)vuser->server_info->utok.uid,
+                vuser->server_info->unix_name, vuser->vuid));
 
-       if (!session_claim(vuser)) {
-               DEBUG(1,("Failed to claim session for vuid=%d\n", vuser->vuid));
-               invalidate_vuid(vuser->vuid);
-               return -1;
+       if (!session_claim(sconn, vuser)) {
+               DEBUG(1, ("register_existing_vuid: Failed to claim session "
+                       "for vuid=%d\n",
+                       vuser->vuid));
+               goto fail;
        }
 
-       /* Register a home dir service for this user iff
-       
-          (a) This is not a guest connection,
-          (b) we have a home directory defined 
-          (c) there s not an existing static share by that name
-          
-          If a share exists by this name (autoloaded or not) reuse it . */
+       /* Register a home dir service for this user if
+       (a) This is not a guest connection,
+       (b) we have a home directory defined
+       (c) there s not an existing static share by that name
+       If a share exists by this name (autoloaded or not) reuse it . */
 
        vuser->homes_snum = -1;
 
-       if ( (!vuser->guest) && vuser->unix_homedir && *(vuser->unix_homedir)) 
-       {
-               int servicenumber = lp_servicenumber(vuser->user.unix_name);
+       if (!vuser->server_info->guest) {
+               vuser->homes_snum = register_homes_share(
+                       vuser->server_info->unix_name);
+       }
 
-               if ( servicenumber == -1 ) {
-                       DEBUG(3, ("Adding homes service for user '%s' using home directory: '%s'\n", 
-                               vuser->user.unix_name, vuser->unix_homedir));
-                       vuser->homes_snum = add_home_service(vuser->user.unix_name, 
-                                               vuser->user.unix_name, vuser->unix_homedir);
-               } else {
-                       DEBUG(3, ("Using static (or previously created) service for user '%s'; path = '%s'\n", 
-                               vuser->user.unix_name, lp_pathname(servicenumber) ));
-                       vuser->homes_snum = servicenumber;
-               }
-       } 
-       
-       if (srv_is_signing_negotiated() && !vuser->guest && !srv_signing_started()) {
-               /* Try and turn on server signing on the first non-guest sessionsetup. */
-               srv_set_signing(vuser->session_key, response_blob);
+       if (srv_is_signing_negotiated(sconn) &&
+           !vuser->server_info->guest) {
+               /* Try and turn on server signing on the first non-guest
+                * sessionsetup. */
+               srv_set_signing(sconn,
+                               vuser->server_info->user_session_key,
+                               response_blob);
        }
-       
-       /* fill in the current_user_info struct */
-       set_current_user_info( &vuser->user );
 
+       /* fill in the current_user_info struct */
+       set_current_user_info(
+               vuser->server_info->sanitized_username,
+               vuser->server_info->unix_name,
+               vuser->server_info->info3->base.domain.string);
 
        return vuser->vuid;
+
+  fail:
+
+       if (vuser) {
+               invalidate_vuid(sconn, vuid);
+       }
+       return UID_FIELD_INVALID;
 }
 
 /****************************************************************************
  Add a name to the session users list.
 ****************************************************************************/
 
-void add_session_user(const char *user)
+void add_session_user(struct smbd_server_connection *sconn,
+                     const char *user)
 {
-       fstring suser;
-       struct passwd *passwd;
+       struct passwd *pw;
+       char *tmp;
+
+       pw = Get_Pwnam_alloc(talloc_tos(), user);
 
-       if (!(passwd = Get_Pwnam(user)))
+       if (pw == NULL) {
                return;
+       }
 
-       fstrcpy(suser,passwd->pw_name);
+       if (sconn->smb1.sessions.session_userlist == NULL) {
+               sconn->smb1.sessions.session_userlist = SMB_STRDUP(pw->pw_name);
+               goto done;
+       }
 
-       if(!*suser)
-               return;
+       if (in_list(pw->pw_name,sconn->smb1.sessions.session_userlist,false)) {
+               goto done;
+       }
 
-       if( session_userlist && in_list(suser,session_userlist,False) )
-               return;
+       if (strlen(sconn->smb1.sessions.session_userlist) > 128 * 1024) {
+               DEBUG(3,("add_session_user: session userlist already "
+                        "too large.\n"));
+               goto done;
+       }
 
-       if( !session_userlist || (strlen(suser) + strlen(session_userlist) + 2 >= len_session_userlist) ) {
-               char *newlist;
+       if (asprintf(&tmp, "%s %s",
+                    sconn->smb1.sessions.session_userlist, pw->pw_name) == -1) {
+               DEBUG(3, ("asprintf failed\n"));
+               goto done;
+       }
 
-               if (len_session_userlist > 128 * PSTRING_LEN) {
-                       DEBUG(3,("add_session_user: session userlist already too large.\n"));
-                       return;
-               }
-               newlist = (char *)SMB_REALLOC( session_userlist, len_session_userlist + PSTRING_LEN );
-               if( newlist == NULL ) {
-                       DEBUG(1,("Unable to resize session_userlist\n"));
-                       return;
-               }
-               if (!session_userlist) {
-                       *newlist = '\0';
-               }
-               session_userlist = newlist;
-               len_session_userlist += PSTRING_LEN;
+       SAFE_FREE(sconn->smb1.sessions.session_userlist);
+       sconn->smb1.sessions.session_userlist = tmp;
+ done:
+       TALLOC_FREE(pw);
+}
+
+/****************************************************************************
+ In security=share mode we need to store the client workgroup, as that's
+  what Vista uses for the NTLMv2 calculation.
+****************************************************************************/
+
+void add_session_workgroup(struct smbd_server_connection *sconn,
+                          const char *workgroup)
+{
+       if (sconn->smb1.sessions.session_workgroup) {
+               SAFE_FREE(sconn->smb1.sessions.session_workgroup);
        }
+       sconn->smb1.sessions.session_workgroup = smb_xstrdup(workgroup);
+}
 
-       safe_strcat(session_userlist," ",len_session_userlist-1);
-       safe_strcat(session_userlist,suser,len_session_userlist-1);
+/****************************************************************************
+ In security=share mode we need to return the client workgroup, as that's
+  what Vista uses for the NTLMv2 calculation.
+****************************************************************************/
+
+const char *get_session_workgroup(struct smbd_server_connection *sconn)
+{
+       return sconn->smb1.sessions.session_workgroup;
 }
 
 /****************************************************************************
  Check if a username is valid.
 ****************************************************************************/
 
-BOOL user_ok(const char *user,int snum, gid_t *groups, size_t n_groups)
+static bool user_ok(const char *user, int snum)
 {
-       char **valid, **invalid;
-       BOOL ret;
+       bool ret;
 
-       valid = invalid = NULL;
        ret = True;
 
        if (lp_invalid_users(snum)) {
-               str_list_copy(&invalid, lp_invalid_users(snum));
-               if (invalid && str_list_substitute(invalid, "%S", lp_servicename(snum))) {
-                       if ( invalid && str_list_sub_basic(invalid, current_user_info.smb_name) ) {
-                               ret = !user_in_list(user, (const char **)invalid, groups, n_groups);
+               char **invalid = str_list_copy(talloc_tos(),
+                       lp_invalid_users(snum));
+               if (invalid &&
+                   str_list_substitute(invalid, "%S", lp_servicename(snum))) {
+
+                       /* This is used in sec=share only, so no current user
+                        * around to pass to str_list_sub_basic() */
+
+                       if ( invalid && str_list_sub_basic(invalid, "", "") ) {
+                               ret = !user_in_list(talloc_tos(), user,
+                                                   (const char **)invalid);
                        }
                }
+               TALLOC_FREE(invalid);
        }
-       if (invalid)
-               str_list_free (&invalid);
 
        if (ret && lp_valid_users(snum)) {
-               str_list_copy(&valid, lp_valid_users(snum));
-               if ( valid && str_list_substitute(valid, "%S", lp_servicename(snum)) ) {
-                       if ( valid && str_list_sub_basic(valid, current_user_info.smb_name) ) {
-                               ret = user_in_list(user, (const char **)valid, groups, n_groups);
+               char **valid = str_list_copy(talloc_tos(),
+                       lp_valid_users(snum));
+               if ( valid &&
+                    str_list_substitute(valid, "%S", lp_servicename(snum)) ) {
+
+                       /* This is used in sec=share only, so no current user
+                        * around to pass to str_list_sub_basic() */
+
+                       if ( valid && str_list_sub_basic(valid, "", "") ) {
+                               ret = user_in_list(talloc_tos(), user,
+                                                  (const char **)valid);
                        }
                }
+               TALLOC_FREE(valid);
        }
-       if (valid)
-               str_list_free (&valid);
 
        if (ret && lp_onlyuser(snum)) {
-               char **user_list = str_list_make (lp_username(snum), NULL);
-               if (user_list && str_list_substitute(user_list, "%S", lp_servicename(snum))) {
-                       ret = user_in_list(user, (const char **)user_list, groups, n_groups);
+               char **user_list = str_list_make_v3(
+                       talloc_tos(), lp_username(snum), NULL);
+               if (user_list &&
+                   str_list_substitute(user_list, "%S",
+                                       lp_servicename(snum))) {
+                       ret = user_in_list(talloc_tos(), user,
+                                          (const char **)user_list);
                }
-               if (user_list) str_list_free (&user_list);
+               TALLOC_FREE(user_list);
        }
 
        return(ret);
@@ -416,16 +478,21 @@ BOOL user_ok(const char *user,int snum, gid_t *groups, size_t n_groups)
  Validate a group username entry. Return the username or NULL.
 ****************************************************************************/
 
-static char *validate_group(char *group, DATA_BLOB password,int snum)
+static char *validate_group(struct smbd_server_connection *sconn,
+                           char *group, DATA_BLOB password,int snum)
 {
 #ifdef HAVE_NETGROUP
        {
                char *host, *user, *domain;
+               struct auth_context *actx = sconn->smb1.negprot.auth_context;
+               bool enc = sconn->smb1.negprot.encrypted_passwords;
                setnetgrent(group);
                while (getnetgrent(&host, &user, &domain)) {
                        if (user) {
-                               if (user_ok(user, snum, NULL, 0) && 
-                                   password_ok(user,password)) {
+                               if (user_ok(user, snum) &&
+                                   password_ok(actx, enc,
+                                               get_session_workgroup(sconn),
+                                               user,password)) {
                                        endnetgrent();
                                        return(user);
                                }
@@ -434,10 +501,13 @@ static char *validate_group(char *group, DATA_BLOB password,int snum)
                endnetgrent();
        }
 #endif
-  
+
 #ifdef HAVE_GETGRENT
        {
                struct group *gptr;
+               struct auth_context *actx = sconn->smb1.negprot.auth_context;
+               bool enc = sconn->smb1.negprot.encrypted_passwords;
+
                setgrent();
                while ((gptr = (struct group *)getgrent())) {
                        if (strequal(gptr->gr_name,group))
@@ -446,49 +516,62 @@ static char *validate_group(char *group, DATA_BLOB password,int snum)
 
                /*
                 * As user_ok can recurse doing a getgrent(), we must
-                * copy the member list into a pstring on the stack before
+                * copy the member list onto the heap before
                 * use. Bug pointed out by leon@eatworms.swmed.edu.
                 */
 
                if (gptr) {
-                       pstring member_list;
+                       char *member_list = NULL;
+                       size_t list_len = 0;
                        char *member;
-                       size_t copied_len = 0;
                        int i;
 
+                       for(i = 0; gptr->gr_mem && gptr->gr_mem[i]; i++) {
+                               list_len += strlen(gptr->gr_mem[i])+1;
+                       }
+                       list_len++;
+
+                       member_list = (char *)SMB_MALLOC(list_len);
+                       if (!member_list) {
+                               endgrent();
+                               return NULL;
+                       }
+
                        *member_list = '\0';
                        member = member_list;
 
                        for(i = 0; gptr->gr_mem && gptr->gr_mem[i]; i++) {
-                               size_t member_len = strlen(gptr->gr_mem[i]) + 1;
-                               if( copied_len + member_len < sizeof(pstring)) { 
+                               size_t member_len = strlen(gptr->gr_mem[i])+1;
 
-                                       DEBUG(10,("validate_group: = gr_mem = %s\n", gptr->gr_mem[i]));
+                               DEBUG(10,("validate_group: = gr_mem = "
+                                         "%s\n", gptr->gr_mem[i]));
 
-                                       safe_strcpy(member, gptr->gr_mem[i], sizeof(pstring) - copied_len - 1);
-                                       copied_len += member_len;
-                                       member += copied_len;
-                               } else {
-                                       *member = '\0';
-                               }
+                               safe_strcpy(member, gptr->gr_mem[i],
+                                       list_len - (member-member_list));
+                               member += member_len;
                        }
 
                        endgrent();
 
                        member = member_list;
                        while (*member) {
-                               static fstring name;
-                               fstrcpy(name,member);
-                               if (user_ok(name,snum, NULL, 0) &&
-                                   password_ok(name,password)) {
-                                       endgrent();
-                                       return(&name[0]);
+                               if (user_ok(member,snum) &&
+                                   password_ok(actx, enc,
+                                               get_session_workgroup(sconn),
+                                               member,password)) {
+                                       char *name = talloc_strdup(talloc_tos(),
+                                                               member);
+                                       SAFE_FREE(member_list);
+                                       return name;
                                }
 
-                               DEBUG(10,("validate_group = member = %s\n", member));
+                               DEBUG(10,("validate_group = member = %s\n",
+                                         member));
 
                                member += strlen(member) + 1;
                        }
+
+                       SAFE_FREE(member_list);
                } else {
                        endgrent();
                        return NULL;
@@ -503,25 +586,30 @@ static char *validate_group(char *group, DATA_BLOB password,int snum)
  Note this is *NOT* used when logging on using sessionsetup_and_X.
 ****************************************************************************/
 
-BOOL authorise_login(int snum, fstring user, DATA_BLOB password, 
-                    BOOL *guest)
+bool authorise_login(struct smbd_server_connection *sconn,
+                    int snum, fstring user, DATA_BLOB password,
+                    bool *guest)
 {
-       BOOL ok = False;
-       
+       bool ok = False;
+       struct auth_context *actx = sconn->smb1.negprot.auth_context;
+       bool enc = sconn->smb1.negprot.encrypted_passwords;
+
 #ifdef DEBUG_PASSWORD
-       DEBUG(100,("authorise_login: checking authorisation on user=%s pass=%s\n",
-                  user,password.data));
+       DEBUG(100,("authorise_login: checking authorisation on "
+                  "user=%s pass=%s\n", user,password.data));
 #endif
 
        *guest = False;
-  
+
        /* there are several possibilities:
                1) login as the given user with given password
-               2) login as a previously registered username with the given password
+               2) login as a previously registered username with the given
+                  password
                3) login as a session list username with the given password
                4) login as a previously validated user/password pair
                5) login as the "user =" user with given password
-               6) login as the "user =" user with no password (guest connection)
+               6) login as the "user =" user with no password
+                  (guest connection)
                7) login as guest user with no password
 
                if the service is guest_only then steps 1 to 5 are skipped
@@ -531,80 +619,111 @@ BOOL authorise_login(int snum, fstring user, DATA_BLOB password,
        if (!ok) {
                char *auser;
                char *user_list = NULL;
+               char *saveptr;
 
-               if ( session_userlist )
-                       user_list = SMB_STRDUP(session_userlist);
+               if (sconn->smb1.sessions.session_userlist)
+                       user_list = SMB_STRDUP(sconn->smb1.sessions.session_userlist);
                else
                        user_list = SMB_STRDUP("");
 
                if (!user_list)
                        return(False);
-               
-               for (auser=strtok(user_list,LIST_SEP); !ok && auser;
-                    auser = strtok(NULL,LIST_SEP)) {
+
+               for (auser = strtok_r(user_list, LIST_SEP, &saveptr);
+                    !ok && auser;
+                    auser = strtok_r(NULL, LIST_SEP, &saveptr)) {
                        fstring user2;
                        fstrcpy(user2,auser);
-                       if (!user_ok(user2,snum, NULL, 0))
+                       if (!user_ok(user2,snum))
                                continue;
-                       
-                       if (password_ok(user2,password)) {
+
+                       if (password_ok(actx, enc,
+                                       get_session_workgroup(sconn),
+                                       user2,password)) {
                                ok = True;
                                fstrcpy(user,user2);
-                               DEBUG(3,("authorise_login: ACCEPTED: session list username (%s) \
-and given password ok\n", user));
+                               DEBUG(3,("authorise_login: ACCEPTED: session "
+                                        "list username (%s) and given "
+                                        "password ok\n", user));
                        }
                }
-               
+
                SAFE_FREE(user_list);
        }
-       
+
        /* check the user= fields and the given password */
        if (!ok && lp_username(snum)) {
+               TALLOC_CTX *ctx = talloc_tos();
                char *auser;
-               pstring user_list;
-               pstrcpy(user_list,lp_username(snum));
-               
-               pstring_sub(user_list,"%S",lp_servicename(snum));
-               
-               for (auser=strtok(user_list,LIST_SEP); auser && !ok;
-                    auser = strtok(NULL,LIST_SEP)) {
+               char *user_list = talloc_strdup(ctx, lp_username(snum));
+               char *saveptr;
+
+               if (!user_list) {
+                       goto check_guest;
+               }
+
+               user_list = talloc_string_sub(ctx,
+                               user_list,
+                               "%S",
+                               lp_servicename(snum));
+
+               if (!user_list) {
+                       goto check_guest;
+               }
+
+               for (auser = strtok_r(user_list, LIST_SEP, &saveptr);
+                    auser && !ok;
+                    auser = strtok_r(NULL, LIST_SEP, &saveptr)) {
                        if (*auser == '@') {
-                               auser = validate_group(auser+1,password,snum);
+                               auser = validate_group(sconn,auser+1,
+                                                      password,snum);
                                if (auser) {
                                        ok = True;
                                        fstrcpy(user,auser);
-                                       DEBUG(3,("authorise_login: ACCEPTED: group username \
-and given password ok (%s)\n", user));
+                                       DEBUG(3,("authorise_login: ACCEPTED: "
+                                                "group username and given "
+                                                "password ok (%s)\n", user));
                                }
                        } else {
                                fstring user2;
                                fstrcpy(user2,auser);
-                               if (user_ok(user2,snum, NULL, 0) && password_ok(user2,password)) {
+                               if (user_ok(user2,snum) &&
+                                   password_ok(actx, enc,
+                                               get_session_workgroup(sconn),
+                                               user2,password)) {
                                        ok = True;
                                        fstrcpy(user,user2);
-                                       DEBUG(3,("authorise_login: ACCEPTED: user list username \
-and given password ok (%s)\n", user));
+                                       DEBUG(3,("authorise_login: ACCEPTED: "
+                                                "user list username and "
+                                                "given password ok (%s)\n",
+                                                user));
                                }
                        }
                }
        }
 
+  check_guest:
+
        /* check for a normal guest connection */
        if (!ok && GUEST_OK(snum)) {
+               struct passwd *guest_pw;
                fstring guestname;
                fstrcpy(guestname,lp_guestaccount());
-               if (Get_Pwnam(guestname)) {
+               guest_pw = Get_Pwnam_alloc(talloc_tos(), guestname);
+               if (guest_pw != NULL) {
                        fstrcpy(user,guestname);
                        ok = True;
-                       DEBUG(3,("authorise_login: ACCEPTED: guest account and guest ok (%s)\n",
-                                       user));
+                       DEBUG(3,("authorise_login: ACCEPTED: guest account "
+                                "and guest ok (%s)\n", user));
                } else {
-                       DEBUG(0,("authorise_login: Invalid guest account %s??\n",guestname));
+                       DEBUG(0,("authorise_login: Invalid guest account "
+                                "%s??\n",guestname));
                }
+               TALLOC_FREE(guest_pw);
                *guest = True;
        }
 
-       if (ok && !user_ok(user, snum, NULL, 0)) {
+       if (ok && !user_ok(user, snum)) {
                DEBUG(0,("authorise_login: rejected invalid user %s\n",user));
                ok = False;
        }