reset time and duration are set in minutes, not seconds. Works from usrmgr.
[ira/wip.git] / source / rpc_server / srv_samr_nt.c
index f174114473b509fe762159f1031f0f7f323a3c4b..10069abb76c50310a7d7a7d66f42c4bc5351ad00 100644 (file)
@@ -6,9 +6,9 @@
  *  Copyright (C) Paul Ashton                       1997,
  *  Copyright (C) Marc Jacobsen                            1999,
  *  Copyright (C) Jeremy Allison               2001-2002,
- *  Copyright (C) Jean François Micouleau      1998-2001,
- *  Copyright (C) Anthony Liguori                   2002,
- *  Copyright (C) Jim McDonough                     2002.
+ *  Copyright (C) Jean François Micouleau      1998-2001,
+ *  Copyright (C) Jim McDonough <jmcd@us.ibm.com>   2002.
+ *  Copyright (C) Gerald (Jerry) Carter             2003.
  *
  *  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
@@ -44,10 +44,10 @@ extern rid_name builtin_alias_rids[];
 typedef struct _disp_info {
        BOOL user_dbloaded;
        uint32 num_user_account;
-       DISP_USER_INFO *disp_user_info;
+       SAM_ACCOUNT *disp_user_info;
        BOOL group_dbloaded;
        uint32 num_group_account;
-       DISP_GROUP_INFO *disp_group_info;
+       DOMAIN_GRP *disp_group_info;
 } DISP_INFO;
 
 struct samr_info {
@@ -151,28 +151,29 @@ static struct samr_info *get_samr_info_by_sid(DOM_SID *psid)
        return info;
 }
 
-
 /*******************************************************************
  Function to free the per handle data.
  ********************************************************************/
+
 static void free_samr_users(struct samr_info *info) 
 {
        int i;
 
        if (info->disp_info.user_dbloaded){
                for (i=0; i<info->disp_info.num_user_account; i++) {
+                       SAM_ACCOUNT *sam = &info->disp_info.disp_user_info[i];
                        /* Not really a free, actually a 'clear' */
-                       pdb_free_sam(&info->disp_info.disp_user_info[i].sam);
+                       pdb_free_sam(&sam);
                }
        }
        info->disp_info.user_dbloaded=False;
        info->disp_info.num_user_account=0;
 }
 
-
 /*******************************************************************
  Function to free the per handle data.
  ********************************************************************/
+
 static void free_samr_db(struct samr_info *info)
 {
        /* Groups are talloced */
@@ -183,7 +184,6 @@ static void free_samr_db(struct samr_info *info)
        info->disp_info.num_group_account=0;
 }
 
-
 static void free_samr_info(void *ptr)
 {
        struct samr_info *info=(struct samr_info *) ptr;
@@ -212,7 +212,7 @@ static void samr_clear_sam_passwd(SAM_ACCOUNT *sam_pass)
 static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOOL all_machines)
 {
        SAM_ACCOUNT *pwd = NULL;
-       DISP_USER_INFO *pwd_array = NULL;
+       SAM_ACCOUNT *pwd_array = NULL;
        NTSTATUS nt_status = NT_STATUS_OK;
        TALLOC_CTX *mem_ctx = info->mem_ctx;
 
@@ -255,8 +255,8 @@ static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOO
                if (info->disp_info.num_user_account % MAX_SAM_ENTRIES == 0) {
                
                        DEBUG(10,("load_sampwd_entries: allocating more memory\n"));
-                       pwd_array=(DISP_USER_INFO *)talloc_realloc(mem_ctx, info->disp_info.disp_user_info, 
-                                         (info->disp_info.num_user_account+MAX_SAM_ENTRIES)*sizeof(DISP_USER_INFO));
+                       pwd_array=(SAM_ACCOUNT *)talloc_realloc(mem_ctx, info->disp_info.disp_user_info, 
+                                         (info->disp_info.num_user_account+MAX_SAM_ENTRIES)*sizeof(SAM_ACCOUNT));
 
                        if (pwd_array==NULL)
                                return NT_STATUS_NO_MEMORY;
@@ -264,8 +264,8 @@ static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOO
                        info->disp_info.disp_user_info=pwd_array;
                }
        
-               /* link the SAM_ACCOUNT to the array */
-               info->disp_info.disp_user_info[info->disp_info.num_user_account].sam=pwd;
+               /* Copy the SAM_ACCOUNT into the array */
+               info->disp_info.disp_user_info[info->disp_info.num_user_account]=*pwd;
 
                DEBUG(10,("load_sampwd_entries: entry: %d\n", info->disp_info.num_user_account));
 
@@ -288,10 +288,11 @@ static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOO
 static NTSTATUS load_group_domain_entries(struct samr_info *info, DOM_SID *sid)
 {
        GROUP_MAP *map=NULL;
-       DISP_GROUP_INFO *grp_array = NULL;
+       DOMAIN_GRP *grp_array = NULL;
        uint32 group_entries = 0;
        uint32 i;
        TALLOC_CTX *mem_ctx = info->mem_ctx;
+       BOOL ret;
 
        DEBUG(10,("load_group_domain_entries\n"));
 
@@ -300,16 +301,21 @@ static NTSTATUS load_group_domain_entries(struct samr_info *info, DOM_SID *sid)
                DEBUG(10,("load_group_domain_entries: already in memory\n"));
                return NT_STATUS_OK;
        }
+       
 
-       if (!pdb_enum_group_mapping(SID_NAME_DOM_GRP, &map, (int *)&group_entries, ENUM_ONLY_MAPPED, MAPPING_WITHOUT_PRIV)) {
+       become_root();
+       ret = pdb_enum_group_mapping(SID_NAME_DOM_GRP, &map, (int *)&group_entries, ENUM_ONLY_MAPPED); 
+       unbecome_root();
+       
+       if ( !ret ) {
                DEBUG(1, ("load_group_domain_entries: pdb_enum_group_mapping() failed!\n"));
                return NT_STATUS_NO_MEMORY;
        }
+       
 
        info->disp_info.num_group_account=group_entries;
 
-       grp_array=(DISP_GROUP_INFO *)talloc(mem_ctx, info->disp_info.num_group_account*sizeof(DISP_GROUP_INFO));
-
+       grp_array=(DOMAIN_GRP *)talloc(mem_ctx, info->disp_info.num_group_account*sizeof(DOMAIN_GRP));
        if (group_entries!=0 && grp_array==NULL) {
                DEBUG(1, ("load_group_domain_entries: talloc() failed for grp_array!\n"));
                SAFE_FREE(map);
@@ -319,13 +325,10 @@ static NTSTATUS load_group_domain_entries(struct samr_info *info, DOM_SID *sid)
        info->disp_info.disp_group_info=grp_array;
 
        for (i=0; i<group_entries; i++) {
-       
-               grp_array[i].grp=(DOMAIN_GRP *)talloc(mem_ctx, sizeof(DOMAIN_GRP));
-       
-               fstrcpy(grp_array[i].grp->name, map[i].nt_name);
-               fstrcpy(grp_array[i].grp->comment, map[i].comment);
-               sid_split_rid(&map[i].sid, &grp_array[i].grp->rid);
-               grp_array[i].grp->attr=SID_NAME_DOM_GRP;
+               fstrcpy(grp_array[i].name, map[i].nt_name);
+               fstrcpy(grp_array[i].comment, map[i].comment);
+               sid_split_rid(&map[i].sid, &grp_array[i].rid);
+               grp_array[i].attr=SID_NAME_DOM_GRP;
        }
 
        SAFE_FREE(map);
@@ -466,7 +469,7 @@ static NTSTATUS samr_make_dom_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 3, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
-       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, NULL, NULL, NULL, psa, sd_size)) == NULL)
+       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        return NT_STATUS_OK;
@@ -509,7 +512,7 @@ static NTSTATUS samr_make_usr_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 4, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
-       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, NULL, NULL, NULL, psa, sd_size)) == NULL)
+       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        return NT_STATUS_OK;
@@ -548,7 +551,7 @@ static NTSTATUS samr_make_grp_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 3, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
-       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, NULL, NULL, NULL, psa, sd_size)) == NULL)
+       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        return NT_STATUS_OK;
@@ -587,7 +590,7 @@ static NTSTATUS samr_make_ali_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd
        if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, 3, ace)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
-       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, NULL, NULL, NULL, psa, sd_size)) == NULL)
+       if ((*psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        return NT_STATUS_OK;
@@ -686,7 +689,7 @@ makes a SAM_ENTRY / UNISTR2* structure from a user list.
 ********************************************************************/
 
 static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UNISTR2 **uni_name_pp,
-                                        uint32 num_entries, uint32 start_idx, DISP_USER_INFO *disp_user_info,
+                                        uint32 num_entries, uint32 start_idx, SAM_ACCOUNT *disp_user_info,
                                         DOM_SID *domain_sid)
 {
        uint32 i;
@@ -716,9 +719,9 @@ static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UN
        }
 
        for (i = 0; i < num_entries; i++) {
-               pwd = disp_user_info[i+start_idx].sam;
+               pwd = &disp_user_info[i+start_idx];
                temp_name = pdb_get_username(pwd);
-               init_unistr2(&uni_temp_name, temp_name, strlen(temp_name)+1);
+               init_unistr2(&uni_temp_name, temp_name, UNI_STR_TERMINATE);
                user_sid = pdb_get_user_sid(pwd);
 
                if (!sid_peek_check_rid(domain_sid, user_sid, &user_rid)) {
@@ -730,7 +733,7 @@ static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UN
                        return NT_STATUS_UNSUCCESSFUL;
                }
 
-               init_sam_entry(&sam[i], uni_temp_name.uni_str_len, user_rid);
+               init_sam_entry(&sam[i], &uni_temp_name, user_rid);
                copy_unistr2(&uni_name[i], &uni_temp_name);
        }
 
@@ -864,10 +867,8 @@ static void make_group_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UNIST
                /*
                 * JRA. I think this should include the null. TNG does not.
                 */
-               int len = strlen(grp[i].name)+1;
-
-               init_sam_entry(&sam[i], len, grp[i].rid);
-               init_unistr2(&uni_name[i], grp[i].name, len);
+               init_unistr2(&uni_name[i], grp[i].name, UNI_STR_TERMINATE);
+               init_sam_entry(&sam[i], &uni_name[i], grp[i].rid);
        }
 
        *sam_pp = sam;
@@ -876,135 +877,11 @@ static void make_group_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UNIST
 
 /*******************************************************************
  Get the group entries - similar to get_sampwd_entries().
- ********************************************************************/
+ ******************************************************************/
 
-static NTSTATUS get_group_alias_entries(TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, DOM_SID *sid, uint32 start_idx,
-                                   uint32 *p_num_entries, uint32 max_entries)
-{
-       fstring sid_str;
-       uint32 num_entries = 0;
-       int i;
-       GROUP_MAP smap;
-       GROUP_MAP *map = NULL;
-
-       sid_to_string(sid_str, sid);
-       DEBUG(5, ("get_group_alias_entries: enumerating aliases on SID: %s\n", sid_str));
-
-       *p_num_entries = 0;
-
-       /* well-known aliases */
-       if (sid_equal(sid, &global_sid_Builtin) && !lp_hide_local_users()) {
-               
-               pdb_enum_group_mapping(SID_NAME_WKN_GRP, &map, (int *)&num_entries, ENUM_ONLY_MAPPED, MAPPING_WITHOUT_PRIV);
-               
-               if (num_entries != 0) {         
-                       *d_grp=(DOMAIN_GRP *)talloc_zero(ctx, num_entries*sizeof(DOMAIN_GRP));
-                       if (*d_grp==NULL)
-                               return NT_STATUS_NO_MEMORY;
-                       
-                       for(i=0; i<num_entries && i<max_entries; i++) {
-                               fstrcpy((*d_grp)[i].name, map[i+start_idx].nt_name);
-                               sid_split_rid(&map[i+start_idx].sid, &(*d_grp)[i].rid);
-                               
-                       }
-               }
-               SAFE_FREE(map);
-               
-       } else if (sid_equal(sid, get_global_sam_sid()) && !lp_hide_local_users()) {
-               struct sys_grent *glist;
-               struct sys_grent *grp;
-               struct passwd *pw;
-               gid_t winbind_gid_low, winbind_gid_high;
-               BOOL winbind_groups_exist = lp_winbind_gid(&winbind_gid_low, &winbind_gid_high);
-
-               /* local aliases */
-               /* we return the UNIX groups here.  This seems to be the right */
-               /* thing to do, since NT member servers return their local     */
-                /* groups in the same situation.                               */
-
-               /* use getgrent_list() to retrieve the list of groups to avoid
-                * problems with getgrent possible infinite loop by internal
-                * libc grent structures overwrites by called functions */
-               grp = glist = getgrent_list();
-               if (grp == NULL)
-                       return NT_STATUS_NO_MEMORY;
-               
-               for (; (num_entries < max_entries) && (grp != NULL); grp = grp->next) {
-                       uint32 trid;
-                       
-                       if(!pdb_getgrgid(&smap, grp->gr_gid, MAPPING_WITHOUT_PRIV))
-                               continue;
-                       
-                       if (smap.sid_name_use!=SID_NAME_ALIAS) {
-                               continue;
-                       }
-
-                       sid_split_rid(&smap.sid, &trid);
-                       
-                       if (!sid_equal(sid, &smap.sid))
-                               continue;
-
-                       /* Don't return winbind groups as they are not local! */
-                       if (winbind_groups_exist && (grp->gr_gid >= winbind_gid_low)&&(grp->gr_gid <= winbind_gid_high)) {
-                               DEBUG(10,("get_group_alias_entries: not returing %s, not local.\n", smap.nt_name ));
-                               continue;
-                       }
-
-                       /* Don't return user private groups... */
-
-                       if ((pw = Get_Pwnam(smap.nt_name)) != 0) {
-                               DEBUG(10,("get_group_alias_entries: not returing %s, clashes with user.\n", smap.nt_name ));
-                               continue;                       
-                       }
-
-                       for( i = 0; i < num_entries; i++)
-                               if ( (*d_grp)[i].rid == trid )
-                                       break;
-
-                       if ( i < num_entries ) {
-                               continue; /* rid was there, dup! */
-                       }
-
-                       /* JRA - added this for large group db enumeration... */
-
-                       if (start_idx > 0) {
-                               /* skip the requested number of entries.
-                                       not very efficient, but hey...
-                               */
-                               start_idx--;
-                               continue;
-                       }
-
-                       *d_grp=talloc_realloc(ctx,*d_grp, (num_entries+1)*sizeof(DOMAIN_GRP));
-                       if (*d_grp==NULL) {
-                               grent_free(glist);
-                               return NT_STATUS_NO_MEMORY;
-                       }
-
-                       fstrcpy((*d_grp)[num_entries].name, smap.nt_name);
-                       (*d_grp)[num_entries].rid = trid;
-                       num_entries++;
-                       DEBUG(10,("get_group_alias_entries: added entry %d, rid:%d\n", num_entries, trid));
-               }
-
-               grent_free(glist);
-       }
-
-       *p_num_entries = num_entries;
-
-       DEBUG(10,("get_group_alias_entries: returning %d entries\n", *p_num_entries));
-
-       if (num_entries >= max_entries)
-               return STATUS_MORE_ENTRIES;
-       return NT_STATUS_OK;
-}
-
-/*******************************************************************
- Get the group entries - similar to get_sampwd_entries().
- ********************************************************************/
-
-static NTSTATUS get_group_domain_entries(TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, DOM_SID *sid, uint32 start_idx,
-                                    uint32 *p_num_entries, uint32 max_entries)
+static NTSTATUS get_group_entries( enum SID_NAME_USE type, TALLOC_CTX *ctx, 
+                                   DOMAIN_GRP **d_grp, DOM_SID *sid, uint32 start_idx,
+                                   uint32 *p_num_entries, uint32 max_entries )
 {
        GROUP_MAP *map=NULL;
        int i;
@@ -1013,8 +890,13 @@ static NTSTATUS get_group_domain_entries(TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, DO
 
        *p_num_entries = 0;
 
-       pdb_enum_group_mapping(SID_NAME_DOM_GRP, &map, (int *)&group_entries, ENUM_ONLY_MAPPED, MAPPING_WITHOUT_PRIV);
-
+       /* access checks for the users were performed higher up.  become/unbecome_root()
+          needed for some passdb backends to enumerate groups */
+          
+       become_root();
+       pdb_enum_group_mapping(type, &map, (int *)&group_entries, ENUM_ONLY_MAPPED);
+       unbecome_root();
+       
        num_entries=group_entries-start_idx;
 
        /* limit the number of entries */
@@ -1033,13 +915,51 @@ static NTSTATUS get_group_domain_entries(TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, DO
                fstrcpy((*d_grp)[i].name, map[i+start_idx].nt_name);
                fstrcpy((*d_grp)[i].comment, map[i+start_idx].comment);
                sid_split_rid(&map[i+start_idx].sid, &(*d_grp)[i].rid);
-               (*d_grp)[i].attr=SID_NAME_DOM_GRP;
+               (*d_grp)[i].attr=type;
        }
 
        SAFE_FREE(map);
 
        *p_num_entries = num_entries;
 
+       DEBUG(10,("get_group_entries: returning %d entries\n", *p_num_entries));
+
+       return NT_STATUS_OK;
+}
+
+/*******************************************************************
+ Wrapper for enuemrating domain groups
+ ******************************************************************/
+
+static NTSTATUS get_group_domain_entries( TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, 
+                                         DOM_SID *sid, uint32 start_idx, 
+                                         uint32 *p_num_entries, uint32 max_entries )
+{
+       return get_group_entries( SID_NAME_DOM_GRP, ctx, d_grp, sid, start_idx, 
+               p_num_entries, max_entries );
+}
+
+/*******************************************************************
+ Wrapper for enumerating local groups
+ ******************************************************************/
+
+static NTSTATUS get_group_alias_entries( TALLOC_CTX *ctx, DOMAIN_GRP **d_grp, 
+                                        DOM_SID *sid, uint32 start_idx,
+                                         uint32 *p_num_entries, uint32 max_entries)
+{
+       if ( sid_equal(sid, &global_sid_Builtin) ) {    
+               return get_group_entries( SID_NAME_WKN_GRP, ctx, d_grp, 
+                       sid, start_idx, p_num_entries, max_entries );
+       }
+       else if ( sid_equal(sid, get_global_sam_sid()) ) {
+               return get_group_entries( SID_NAME_ALIAS, ctx, d_grp, 
+                       sid, start_idx, p_num_entries, max_entries );   
+       }
+
+       /* can't do anything with this SID */
+               
+       *p_num_entries = 0;
+
        return NT_STATUS_OK;
 }
 
@@ -1123,6 +1043,7 @@ NTSTATUS _samr_enum_dom_aliases(pipes_struct *p, SAMR_Q_ENUM_DOM_ALIASES *q_u, S
 /*******************************************************************
  samr_reply_query_dispinfo
  ********************************************************************/
+
 NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u, 
                              SAMR_R_QUERY_DISPINFO *r_u)
 {
@@ -1325,6 +1246,7 @@ NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAM
        DOM_SID   sid;
        GROUP_MAP map;
        uint32    acc_granted;
+       BOOL ret;
 
        r_u->status = NT_STATUS_OK;
 
@@ -1341,7 +1263,11 @@ NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAM
            !sid_check_is_in_builtin(&sid))
                return NT_STATUS_OBJECT_TYPE_MISMATCH;
 
-       if (!pdb_getgrsid(&map, sid, MAPPING_WITHOUT_PRIV))
+       become_root();
+       ret = pdb_getgrsid(&map, sid);
+       unbecome_root();
+       
+       if ( !ret )
                return NT_STATUS_NO_SUCH_ALIAS;
 
        switch (q_u->switch_level) {
@@ -1463,18 +1389,17 @@ NTSTATUS _samr_lookup_names(pipes_struct *p, SAMR_Q_LOOKUP_NAMES *q_u, SAMR_R_LO
 
        DEBUG(5,("_samr_lookup_names: looking name on SID %s\n", sid_to_string(sid_str, &pol_sid)));
        
-       become_root(); /* local_lookup_name can require root privs */
-
        for (i = 0; i < num_rids; i++) {
                fstring name;
                DOM_SID sid;
+               int ret;
 
                r_u->status = NT_STATUS_NONE_MAPPED;
 
                rid [i] = 0xffffffff;
                type[i] = SID_NAME_UNKNOWN;
 
-               rpcstr_pull(name, q_u->uni_name[i].buffer, sizeof(name), q_u->uni_name[i].uni_str_len*2, 0);
+               ret = rpcstr_pull(name, q_u->uni_name[i].buffer, sizeof(name), q_u->uni_name[i].uni_str_len*2, 0);
 
                /*
                 * we are only looking for a name
@@ -1487,19 +1412,23 @@ NTSTATUS _samr_lookup_names(pipes_struct *p, SAMR_Q_LOOKUP_NAMES *q_u, SAMR_R_LO
                 * a cleaner code is to add the sid of the domain we're looking in
                 * to the local_lookup_name function.
                 */
-               if(local_lookup_name(name, &sid, &local_type)) {
+                
+               if ((ret > 0) && local_lookup_name(name, &sid, &local_type)) {
                        sid_split_rid(&sid, &local_rid);
                                
                        if (sid_equal(&sid, &pol_sid)) {
                                rid[i]=local_rid;
-                               type[i]=local_type;
+
+                               /* Windows does not return WKN_GRP here, even
+                                * on lookups in builtin */
+                               type[i] = (local_type == SID_NAME_WKN_GRP) ?
+                                       SID_NAME_ALIAS : local_type;
+
                                r_u->status = NT_STATUS_OK;
                        }
                }
        }
 
-       unbecome_root();
-
        init_samr_r_lookup_names(p->mem_ctx, r_u, num_rids, rid, (uint32 *)type, r_u->status);
 
        DEBUG(5,("_samr_lookup_names: %d\n", __LINE__));
@@ -1513,17 +1442,17 @@ NTSTATUS _samr_lookup_names(pipes_struct *p, SAMR_Q_LOOKUP_NAMES *q_u, SAMR_R_LO
 
 NTSTATUS _samr_chgpasswd_user(pipes_struct *p, SAMR_Q_CHGPASSWD_USER *q_u, SAMR_R_CHGPASSWD_USER *r_u)
 {
-    fstring user_name;
-    fstring wks;
+       fstring user_name;
+       fstring wks;
 
-    DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
+       DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
 
-    r_u->status = NT_STATUS_OK;
+       r_u->status = NT_STATUS_OK;
 
-    rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
-    rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
+       rpcstr_pull(user_name, q_u->uni_user_name.buffer, sizeof(user_name), q_u->uni_user_name.uni_str_len*2, 0);
+       rpcstr_pull(wks, q_u->uni_dest_host.buffer, sizeof(wks), q_u->uni_dest_host.uni_str_len*2,0);
 
-    DEBUG(5,("samr_chgpasswd_user: user: %s wks: %s\n", user_name, wks));
+       DEBUG(5,("samr_chgpasswd_user: user: %s wks: %s\n", user_name, wks));
 
        /*
         * Pass the user through the NT -> unix user mapping
@@ -1537,14 +1466,14 @@ NTSTATUS _samr_chgpasswd_user(pipes_struct *p, SAMR_Q_CHGPASSWD_USER *q_u, SAMR_
         * is case insensitive.
         */
 
-    r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
-                                 q_u->nt_newpass.pass, q_u->nt_oldhash.hash);
+       r_u->status = pass_oem_change(user_name, q_u->lm_newpass.pass, q_u->lm_oldhash.hash,
+                               q_u->nt_newpass.pass, q_u->nt_oldhash.hash);
 
-    init_samr_r_chgpasswd_user(r_u, r_u->status);
+       init_samr_r_chgpasswd_user(r_u, r_u->status);
 
-    DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
+       DEBUG(5,("_samr_chgpasswd_user: %d\n", __LINE__));
 
-    return r_u->status;
+       return r_u->status;
 }
 
 /*******************************************************************
@@ -1572,10 +1501,9 @@ static BOOL make_samr_lookup_rids(TALLOC_CTX *ctx, uint32 num_names, fstring nam
        }
 
        for (i = 0; i < num_names; i++) {
-               int len = names[i] != NULL ? strlen(names[i]) : 0;
-               DEBUG(10, ("names[%d]:%s\n", i, names[i]));
-               init_uni_hdr(&hdr_name[i], len);
-               init_unistr2(&uni_name[i], names[i], len);
+               DEBUG(10, ("names[%d]:%s\n", i, names[i] ? names[i] : ""));
+               init_unistr2(&uni_name[i], names[i], UNI_FLAGS_NONE);
+               init_uni_hdr(&hdr_name[i], &uni_name[i]);
        }
 
        *pp_uni_name = uni_name;
@@ -1656,10 +1584,10 @@ NTSTATUS _samr_lookup_rids(pipes_struct *p, SAMR_Q_LOOKUP_RIDS *q_u, SAMR_R_LOOK
 }
 
 /*******************************************************************
- _api_samr_open_user. Safe - gives out no passwd info.
+ _samr_open_user. Safe - gives out no passwd info.
  ********************************************************************/
 
-NTSTATUS _api_samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USER *r_u)
+NTSTATUS _samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USER *r_u)
 {
        SAM_ACCOUNT *sampass=NULL;
        DOM_SID sid;
@@ -2137,7 +2065,7 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
                                       num_users, num_groups, num_aliases);
                        break;
                case 0x03:
-                       account_policy_get(AP_TIME_TO_LOGOUT, (int *)&u_logout);
+                       account_policy_get(AP_TIME_TO_LOGOUT, (unsigned int *)&u_logout);
                        unix_to_nt_time_abs(&nt_logout, u_logout);
                        
                        init_unk_info3(&ctr->info.inf3, nt_logout);
@@ -2178,12 +2106,12 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
 }
 
 /*******************************************************************
- _api_samr_create_user
+ _samr_create_user
  Create an account, can be either a normal user or a machine.
  This funcion will need to be updated for bdc/domain trusts.
  ********************************************************************/
 
-NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREATE_USER *r_u)
+NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREATE_USER *r_u)
 {
        SAM_ACCOUNT *sam_pass=NULL;
        fstring account;
@@ -2200,6 +2128,8 @@ NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_
        uint32 acc_granted;
        SEC_DESC *psd;
        size_t    sd_size;
+       uint32 new_rid = 0;
+       /* check this, when giving away 'add computer to domain' privs */
        uint32    des_access = GENERIC_RIGHTS_USER_ALL_ACCESS;
 
        /* Get the domain SID stored in the domain policy */
@@ -2210,6 +2140,12 @@ NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_
                return nt_status;
        }
 
+       if (!(acb_info == ACB_NORMAL || acb_info == ACB_DOMTRUST || acb_info == ACB_WSTRUST || acb_info == ACB_SVRTRUST)) { 
+               /* Match Win2k, and return NT_STATUS_INVALID_PARAMETER if 
+                  this parameter is not an account type */
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        /* find the account: tell the caller if it exists.
          lkclXXXX i have *no* idea if this is a problem or not
          or even if you are supposed to construct a different
@@ -2217,7 +2153,7 @@ NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_
         */
 
        rpcstr_pull(account, user_account.buffer, sizeof(account), user_account.uni_str_len*2, 0);
-       strlower(account);
+       strlower_m(account);
 
        pdb_init_sam(&sam_pass);
 
@@ -2253,101 +2189,73 @@ NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_
         * now have some sainity-checking to match. 
         */
 
-       DEBUG(10,("checking account %s at pos %d for $ termination\n",account, strlen(account)-1));
-#if 0
-       if ((acb_info & ACB_WSTRUST) && (account[strlen(account)-1] == '$')) {
-               pstrcpy(add_script, lp_addmachine_script());            
-       } else if ((!(acb_info & ACB_WSTRUST)) && (account[strlen(account)-1] != '$')) {
-               pstrcpy(add_script, lp_adduser_script());
-       } else {
-               DEBUG(0, ("_api_samr_create_user: mismatch between trust flags and $ termination\n"));
-               pdb_free_sam(&sam_pass);
-               return NT_STATUS_UNSUCCESSFUL;
-       }
-#endif
-
+       DEBUG(10,("checking account %s at pos %lu for $ termination\n",account, (unsigned long)strlen(account)-1));
+       
        /* 
-        * we can't check both the ending $ and the acb_info.
-        * 
-        * UserManager creates trust accounts (ending in $,
-        * normal that hidden accounts) with the acb_info equals to ACB_NORMAL.
-        * JFM, 11/29/2001
+        * we used to have code here that made sure the acb_info flags 
+        * matched with the users named (e.g. an account flags as a machine 
+        * trust account ended in '$').  It has been ifdef'd out for a long 
+        * time, so I replaced it with this comment.     --jerry
         */
-       if (account[strlen(account)-1] == '$')
-               pstrcpy(add_script, lp_addmachine_script());            
-       else 
-               pstrcpy(add_script, lp_adduser_script());
-
-       if (*add_script) {
-               int add_ret;
-               all_string_sub(add_script, "%u", account, sizeof(account));
-               add_ret = smbrun(add_script,NULL);
-               DEBUG(3,("_api_samr_create_user: Running the command `%s' gave %d\n", add_script, add_ret));
-       }
-       
-       if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(&sam_pass))) {
-               return nt_status;
-       }
-               
-       pw = getpwnam_alloc(account);
-
-       if (pw) {
-               DOM_SID user_sid;
-               DOM_SID group_sid;
-               if (!uid_to_sid(&user_sid, pw->pw_uid)) {
-                       passwd_free(&pw); /* done with this now */
-                       pdb_free_sam(&sam_pass);
-                       DEBUG(1, ("_api_samr_create_user: uid_to_sid failed, cannot add user.\n"));
-                       return NT_STATUS_ACCESS_DENIED;
-               }
-
-               if (!pdb_set_user_sid(sam_pass, &user_sid, PDB_CHANGED)) {
-                       passwd_free(&pw); /* done with this now */
-                       pdb_free_sam(&sam_pass);
-                       return NT_STATUS_NO_MEMORY;
-               }
-
-               if (!gid_to_sid(&group_sid, pw->pw_gid)) {
-                       passwd_free(&pw); /* done with this now */
-                       pdb_free_sam(&sam_pass);
-                       DEBUG(1, ("_api_samr_create_user: gid_to_sid failed, cannot add user.\n"));
-                       return NT_STATUS_ACCESS_DENIED;
-               }
 
-               if (!pdb_set_group_sid(sam_pass, &group_sid, PDB_CHANGED)) {
-                       passwd_free(&pw); /* done with this now */
-                       pdb_free_sam(&sam_pass);
-                       return NT_STATUS_NO_MEMORY;
-               }
-
-               passwd_free(&pw); /* done with this now */
-       } else {
-               DEBUG(3,("attempting to create non-unix account %s\n", account));
-               
+       /* the passdb lookup has failed; check to see if we need to run the
+          add user/machine script */
+          
+       pw = Get_Pwnam(account);
+       
+       /*********************************************************************
+        * HEADS UP!  If we have to create a new user account, we have to get 
+        * a new RID from somewhere.  This used to be done by the passdb 
+        * backend. It has been moved into idmap now.  Since idmap is now 
+        * wrapped up behind winbind, this means you have to run winbindd if you
+        * want new accounts to get a new RID when "enable rid algorithm = no".
+        * Tough.  We now have a uniform way of allocating RIDs regardless
+        * of what ever passdb backend people may use.
+        *                                             --jerry (2003-07-10)
+        *********************************************************************/
+       
+       if ( !pw ) {
+               /* 
+                * we can't check both the ending $ and the acb_info.
+                * 
+                * UserManager creates trust accounts (ending in $,
+                * normal that hidden accounts) with the acb_info equals to ACB_NORMAL.
+                * JFM, 11/29/2001
+                */
+               if (account[strlen(account)-1] == '$')
+                       pstrcpy(add_script, lp_addmachine_script());            
+               else 
+                       pstrcpy(add_script, lp_adduser_script());
+
+               if (*add_script) {
+                       int add_ret;
+                       all_string_sub(add_script, "%u", account, sizeof(account));
+                       add_ret = smbrun(add_script,NULL);
+                       DEBUG(3,("_samr_create_user: Running the command `%s' gave %d\n", add_script, add_ret));
+               }
+               else    /* no add user script -- ask winbindd to do it */
+               {
+                       if ( !winbind_create_user( account, &new_rid ) ) {
+                               DEBUG(3,("_samr_create_user: winbind_create_user(%s) failed\n", 
+                                       account));
+                       }
                }
                
-               if (!pdb_set_username(sam_pass, account, PDB_CHANGED)) {
-                       pdb_free_sam(&sam_pass);
-                       return NT_STATUS_NO_MEMORY;
        }
+       
+       /* implicit call to getpwnam() next.  we have a valid SID coming out of this call */
 
+       if ( !NT_STATUS_IS_OK(nt_status = pdb_init_sam_new(&sam_pass, account, new_rid)) )
+               return nt_status;
+               
        pdb_set_acct_ctrl(sam_pass, acb_info, PDB_CHANGED);
+       
        if (!pdb_add_sam_account(sam_pass)) {
                pdb_free_sam(&sam_pass);
                DEBUG(0, ("could not add user/computer %s to passdb.  Check permissions?\n", 
                          account));
                return NT_STATUS_ACCESS_DENIED;         
        }
-
-       pdb_reset_sam(sam_pass);
-       
-       if (!pdb_getsampwnam(sam_pass, account)) {
-               pdb_free_sam(&sam_pass);
-               DEBUG(0, ("could not find user/computer %s just added to passdb?!?\n", 
-                         account));
-               return NT_STATUS_ACCESS_DENIED;         
-       }
        
        /* Get the user's SID */
        sid_copy(&sid, pdb_get_user_sid(sam_pass));
@@ -2392,6 +2300,7 @@ NTSTATUS _api_samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_
 NTSTATUS _samr_connect_anon(pipes_struct *p, SAMR_Q_CONNECT_ANON *q_u, SAMR_R_CONNECT_ANON *r_u)
 {
        struct samr_info *info = NULL;
+       uint32    des_access = q_u->access_mask;
 
        /* Access check */
 
@@ -2409,6 +2318,13 @@ NTSTATUS _samr_connect_anon(pipes_struct *p, SAMR_Q_CONNECT_ANON *q_u, SAMR_R_CO
        if ((info = get_samr_info_by_sid(NULL)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
+       /* don't give away the farm but this is probably ok.  The SA_RIGHT_SAM_ENUM_DOMAINS
+          was observed from a win98 client trying to enumerate users (when configured  
+          user level access control on shares)   --jerry */
+          
+       se_map_generic( &des_access, &sam_generic_mapping );
+       info->acc_granted = des_access & (SA_RIGHT_SAM_ENUM_DOMAINS|SA_RIGHT_SAM_OPEN_DOMAIN);
+       
        info->status = q_u->unknown_0;
 
        /* get a (unique) handle.  open a policy on it. */
@@ -2533,7 +2449,9 @@ NTSTATUS _samr_lookup_domain(pipes_struct *p, SAMR_Q_LOOKUP_DOMAIN *q_u, SAMR_R_
        if (!find_policy_by_hnd(p, &q_u->connect_pol, (void**)&info))
                return NT_STATUS_INVALID_HANDLE;
 
-       if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_lookup_domain"))) {
+       if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
+               SA_RIGHT_SAM_ENUM_DOMAINS, "_samr_lookup_domain"))) 
+       {
                return r_u->status;
        }
 
@@ -2578,10 +2496,8 @@ static BOOL make_enum_domains(TALLOC_CTX *ctx, SAM_ENTRY **pp_sam,
                return False;
 
        for (i = 0; i < num_sam_entries; i++) {
-               int len = doms[i] != NULL ? strlen(doms[i]) : 0;
-
-               init_sam_entry(&sam[i], len, 0);
-               init_unistr2(&uni_name[i], doms[i], len);
+               init_unistr2(&uni_name[i], doms[i], UNI_FLAGS_NONE);
+               init_sam_entry(&sam[i], &uni_name[i], 0);
        }
 
        *pp_sam = sam;
@@ -2610,17 +2526,10 @@ NTSTATUS _samr_enum_domains(pipes_struct *p, SAMR_Q_ENUM_DOMAINS *q_u, SAMR_R_EN
                return r_u->status;
        }
 
-       switch (lp_server_role()) {
-       case ROLE_DOMAIN_PDC:
-       case ROLE_DOMAIN_BDC:
-               name = lp_workgroup();
-               break;
-       default:
-               name = global_myname();
-       }
+       name = get_global_sam_name();
 
        fstrcpy(dom[0],name);
-       strupper(dom[0]);
+       strupper_m(dom[0]);
        fstrcpy(dom[1],"Builtin");
 
        if (!make_enum_domains(p->mem_ctx, &r_u->sam, &r_u->uni_dom_name, num_entries, dom))
@@ -2635,7 +2544,7 @@ NTSTATUS _samr_enum_domains(pipes_struct *p, SAMR_Q_ENUM_DOMAINS *q_u, SAMR_R_EN
  api_samr_open_alias
  ********************************************************************/
 
-NTSTATUS _api_samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_ALIAS *r_u)
+NTSTATUS _samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_ALIAS *r_u)
 {
        DOM_SID sid;
        POLICY_HND domain_pol = q_u->dom_pol;
@@ -2772,6 +2681,74 @@ static BOOL set_user_info_12(SAM_USER_INFO_12 *id12, DOM_SID *sid)
        return True;
 }
 
+/*******************************************************************
+ The GROUPSID field in the SAM_ACCOUNT changed. Try to tell unix.
+ ********************************************************************/
+static BOOL set_unix_primary_group(SAM_ACCOUNT *sampass)
+{
+       struct group *grp;
+       gid_t gid;
+
+       if (!NT_STATUS_IS_OK(sid_to_gid(pdb_get_group_sid(sampass),
+                                       &gid))) {
+               DEBUG(2,("Could not get gid for primary group of "
+                        "user %s\n", pdb_get_username(sampass)));
+               return False;
+       }
+
+       grp = getgrgid(gid);
+
+       if (grp == NULL) {
+               DEBUG(2,("Could not find primary group %lu for "
+                        "user %s\n", (unsigned long)gid, 
+                        pdb_get_username(sampass)));
+               return False;
+       }
+
+       if (smb_set_primary_group(grp->gr_name,
+                                 pdb_get_username(sampass)) != 0) {
+               DEBUG(2,("Could not set primary group for user %s to "
+                        "%s\n",
+                        pdb_get_username(sampass), grp->gr_name));
+               return False;
+       }
+
+       return True;
+}
+       
+
+/*******************************************************************
+ set_user_info_20
+ ********************************************************************/
+
+static BOOL set_user_info_20(SAM_USER_INFO_20 *id20, DOM_SID *sid)
+{
+       SAM_ACCOUNT *pwd = NULL;
+       if (id20 == NULL) {
+               DEBUG(5, ("set_user_info_20: NULL id20\n"));
+               return False;
+       }
+       pdb_init_sam(&pwd);
+       if (!pdb_getsampwsid(pwd, sid)) {
+               pdb_free_sam(&pwd);
+               return False;
+       }
+       copy_id20_to_sam_passwd(pwd, id20);
+
+       /* write the change out */
+       if(!pdb_update_sam_account(pwd)) {
+               pdb_free_sam(&pwd);
+               return False;
+       }
+
+       pdb_free_sam(&pwd);
+
+       return True;
+}
 /*******************************************************************
  set_user_info_21
  ********************************************************************/
@@ -2801,6 +2778,9 @@ static BOOL set_user_info_21(SAM_USER_INFO_21 *id21, DOM_SID *sid)
         * id21.  I don't know if they need to be set.    --jerry
         */
  
+       if (IS_SAM_CHANGED(pwd, PDB_GROUPSID))
+               set_unix_primary_group(pwd);
+
        /* write the change out */
        if(!pdb_update_sam_account(pwd)) {
                pdb_free_sam(&pwd);
@@ -2840,7 +2820,7 @@ static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, DOM_SID *sid)
 
        acct_ctrl = pdb_get_acct_ctrl(pwd);
 
-       if (!decode_pw_buffer((char*)id23->pass, plaintext_buf, 256, &len)) {
+       if (!decode_pw_buffer((char*)id23->pass, plaintext_buf, 256, &len, STR_UNICODE)) {
                pdb_free_sam(&pwd);
                return False;
        }
@@ -2853,22 +2833,30 @@ static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, DOM_SID *sid)
        copy_id23_to_sam_passwd(pwd, id23);
  
        /* if it's a trust account, don't update /etc/passwd */
-       if ( (!IS_SAM_UNIX_USER(pwd)) ||
-               ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
+       if (    ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
                ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
                ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
                DEBUG(5, ("Changing trust account or non-unix-user password, not updating /etc/passwd\n"));
        } else  {
                /* update the UNIX password */
-               if (lp_unix_password_sync() )
-                       if(!chgpasswd(pdb_get_username(pwd), "", plaintext_buf, True)) {
+               if (lp_unix_password_sync() ) {
+                       struct passwd *passwd = Get_Pwnam(pdb_get_username(pwd));
+                       if (!passwd) {
+                               DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
+                       }
+                       
+                       if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
                                pdb_free_sam(&pwd);
                                return False;
                        }
+               }
        }
  
        ZERO_STRUCT(plaintext_buf);
  
+       if (IS_SAM_CHANGED(pwd, PDB_GROUPSID))
+               set_unix_primary_group(pwd);
+
        if(!pdb_update_sam_account(pwd)) {
                pdb_free_sam(&pwd);
                return False;
@@ -2904,7 +2892,7 @@ static BOOL set_user_info_pw(char *pass, DOM_SID *sid)
 
        ZERO_STRUCT(plaintext_buf);
  
-       if (!decode_pw_buffer(pass, plaintext_buf, 256, &len)) {
+       if (!decode_pw_buffer(pass, plaintext_buf, 256, &len, STR_UNICODE)) {
                pdb_free_sam(&pwd);
                return False;
        }
@@ -2915,15 +2903,19 @@ static BOOL set_user_info_pw(char *pass, DOM_SID *sid)
        }
  
        /* if it's a trust account, don't update /etc/passwd */
-       if ( (!IS_SAM_UNIX_USER(pwd)) ||
-               ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
+       if ( ( (acct_ctrl &  ACB_DOMTRUST) == ACB_DOMTRUST ) ||
                ( (acct_ctrl &  ACB_WSTRUST) ==  ACB_WSTRUST) ||
                ( (acct_ctrl &  ACB_SVRTRUST) ==  ACB_SVRTRUST) ) {
                DEBUG(5, ("Changing trust account or non-unix-user password, not updating /etc/passwd\n"));
        } else {
                /* update the UNIX password */
                if (lp_unix_password_sync()) {
-                       if(!chgpasswd(pdb_get_username(pwd), "", plaintext_buf, True)) {
+                       struct passwd *passwd = Get_Pwnam(pdb_get_username(pwd));
+                       if (!passwd) {
+                               DEBUG(1, ("chgpasswd: Username does not exist in system !?!\n"));
+                       }
+                       
+                       if(!chgpasswd(pdb_get_username(pwd), passwd, "", plaintext_buf, True)) {
                                pdb_free_sam(&pwd);
                                return False;
                        }
@@ -2986,7 +2978,10 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
                        break;
 
                case 24:
-                       SamOEMhash(ctr->info.id24->pass, p->session_key, 516);
+                       if (!p->session_key.length) {
+                               return NT_STATUS_NO_USER_SESSION_KEY;
+                       }
+                       SamOEMhashBlob(ctr->info.id24->pass, 516, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id24->pass, 516);
 
@@ -3004,7 +2999,10 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
                         * info level and W2K SP2 drops down to level 23... JRA.
                         */
 
-                       SamOEMhash(ctr->info.id25->pass, p->session_key, 532);
+                       if (!p->session_key.length) {
+                               return NT_STATUS_NO_USER_SESSION_KEY;
+                       }
+                       SamOEMhashBlob(ctr->info.id25->pass, 532, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id25->pass, 532);
 
@@ -3015,7 +3013,10 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
                        return NT_STATUS_INVALID_INFO_CLASS;
 
                case 23:
-                       SamOEMhash(ctr->info.id23->pass, p->session_key, 516);
+                       if (!p->session_key.length) {
+                               return NT_STATUS_NO_USER_SESSION_KEY;
+                       }
+                       SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id23->pass, 516);
 
@@ -3071,6 +3072,10 @@ NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_
                        if (!set_user_info_21(ctr->info.id21, &sid))
                                return NT_STATUS_ACCESS_DENIED;
                        break;
+               case 20:
+                       if (!set_user_info_20(ctr->info.id20, &sid))
+                               return NT_STATUS_ACCESS_DENIED;
+                       break;
                case 16:
                        if (!set_user_info_10(ctr->info.id10, &sid))
                                return NT_STATUS_ACCESS_DENIED;
@@ -3187,18 +3192,15 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
        int i;
 
        GROUP_MAP map;
-       int num_uids = 0;
+       int num_sids = 0;
        DOM_SID2 *sid;
-       uid_t *uid=NULL;
+       DOM_SID *sids=NULL;
 
        DOM_SID alias_sid;
        DOM_SID als_sid;
        uint32 alias_rid;
        fstring alias_sid_str;
-       DOM_SID temp_sid;
 
-       SAM_ACCOUNT *sam_user = NULL;
-       BOOL check;
        uint32 acc_granted;
 
        /* find the policy handle.  open a policy on it. */
@@ -3218,65 +3220,40 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
 
        if (sid_equal(&alias_sid, &global_sid_Builtin)) {
                DEBUG(10, ("lookup on Builtin SID (S-1-5-32)\n"));
-               if(!get_builtin_group_from_sid(als_sid, &map, MAPPING_WITHOUT_PRIV))
+               if(!get_builtin_group_from_sid(&als_sid, &map))
                        return NT_STATUS_NO_SUCH_ALIAS;
        } else {
                if (sid_equal(&alias_sid, get_global_sam_sid())) {
                        DEBUG(10, ("lookup on Server SID\n"));
-                       if(!get_local_group_from_sid(als_sid, &map, MAPPING_WITHOUT_PRIV))
+                       if(!get_local_group_from_sid(&als_sid, &map)) {
+                               fstring alias_sid_string;
+                               DEBUG(10, ("Alias %s not found\n", sid_to_string(alias_sid_string, &als_sid))); 
                                return NT_STATUS_NO_SUCH_ALIAS;
+                       }
                }
        }
 
-       if(!get_uid_list_of_group(map.gid, &uid, &num_uids))
+       if (!get_sid_list_of_group(map.gid, &sids, &num_sids)) {
+               fstring alias_sid_string;
+               DEBUG(10, ("Alias %s found, but member list unavailable\n", sid_to_string(alias_sid_string, &als_sid))); 
                return NT_STATUS_NO_SUCH_ALIAS;
+       }
 
        DEBUG(10, ("sid is %s\n", alias_sid_str));
-       sid = (DOM_SID2 *)talloc_zero(p->mem_ctx, sizeof(DOM_SID2) * num_uids); 
-       if (num_uids!=0 && sid == NULL) 
+       sid = (DOM_SID2 *)talloc_zero(p->mem_ctx, sizeof(DOM_SID2) * num_sids); 
+       if (num_sids!=0 && sid == NULL) {
+               SAFE_FREE(sids);
                return NT_STATUS_NO_MEMORY;
+       }
 
-       for (i = 0; i < num_uids; i++) {
-               struct passwd *pass;
-               uint32 rid;
-
-               sid_copy(&temp_sid, get_global_sam_sid());
-
-               pass = getpwuid_alloc(uid[i]);
-               if (!pass) continue;
-
-               if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_user))) {
-                       passwd_free(&pass);
-                       continue;
-               }
-
-               become_root();
-               check = pdb_getsampwnam(sam_user, pass->pw_name);
-               unbecome_root();
-       
-               if (check != True) {
-                       pdb_free_sam(&sam_user);
-                       passwd_free(&pass);
-                       continue;
-               }
-       
-               rid = pdb_get_user_rid(sam_user);
-               if (rid == 0) {
-                       pdb_free_sam(&sam_user);
-                       passwd_free(&pass);
-                       continue;
-               }
-
-               pdb_free_sam(&sam_user);
-               passwd_free(&pass);
-
-               sid_append_rid(&temp_sid, rid);
-               
-               init_dom_sid2(&sid[i], &temp_sid);
+       for (i = 0; i < num_sids; i++) {
+               init_dom_sid2(&sid[i], &sids[i]);
        }
 
        DEBUG(10, ("sid is %s\n", alias_sid_str));
-       init_samr_r_query_aliasmem(r_u, num_uids, sid, NT_STATUS_OK);
+       init_samr_r_query_aliasmem(r_u, num_sids, sid, NT_STATUS_OK);
+
+       SAFE_FREE(sids);
 
        return NT_STATUS_OK;
 }
@@ -3287,20 +3264,18 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
 
 NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_R_QUERY_GROUPMEM *r_u)
 {
-       int num_uids = 0;
+       int num_sids = 0;
+       int final_num_sids = 0;
        int i;
        DOM_SID group_sid;
-       uint32 group_rid;
        fstring group_sid_str;
-       uid_t *uid=NULL;
+       DOM_SID *sids=NULL;
        
        GROUP_MAP map;
 
        uint32 *rid=NULL;
        uint32 *attr=NULL;
 
-       SAM_ACCOUNT *sam_user = NULL;
-       BOOL check;
        uint32 acc_granted;
 
        /* find the policy handle.  open a policy on it. */
@@ -3311,68 +3286,45 @@ NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_
                return r_u->status;
        }
                
-       /* todo: change to use sid_compare_front */
-
-       sid_split_rid(&group_sid, &group_rid);
        sid_to_string(group_sid_str, &group_sid);
        DEBUG(10, ("sid is %s\n", group_sid_str));
 
-       /* can we get a query for an SID outside our domain ? */
-       if (!sid_equal(&group_sid, get_global_sam_sid()))
+       if (!sid_check_is_in_our_domain(&group_sid)) {
+               DEBUG(3, ("sid %s is not in our domain\n", group_sid_str));
                return NT_STATUS_NO_SUCH_GROUP;
+       }
 
-       sid_append_rid(&group_sid, group_rid);
        DEBUG(10, ("lookup on Domain SID\n"));
 
-       if(!get_domain_group_from_sid(group_sid, &map, MAPPING_WITHOUT_PRIV))
+       if(!get_domain_group_from_sid(group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
 
-       if(!get_uid_list_of_group(map.gid, &uid, &num_uids))
+       if(!get_sid_list_of_group(map.gid, &sids, &num_sids))
                return NT_STATUS_NO_SUCH_GROUP;
 
-       rid=talloc_zero(p->mem_ctx, sizeof(uint32)*num_uids);
-       attr=talloc_zero(p->mem_ctx, sizeof(uint32)*num_uids);
+       rid=talloc_zero(p->mem_ctx, sizeof(uint32)*num_sids);
+       attr=talloc_zero(p->mem_ctx, sizeof(uint32)*num_sids);
        
-       if (num_uids!=0 && (rid==NULL || attr==NULL))
+       if (num_sids!=0 && (rid==NULL || attr==NULL))
                return NT_STATUS_NO_MEMORY;
        
-       for (i=0; i<num_uids; i++) {
-               struct passwd *pass;
+       for (i=0; i<num_sids; i++) {
                uint32 urid;
-
-               pass = getpwuid_alloc(uid[i]);
-               if (!pass) continue;
-
-               if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_user))) {
-                       passwd_free(&pass);
-                       continue;
-               }
-
-               become_root();
-               check = pdb_getsampwnam(sam_user, pass->pw_name);
-               unbecome_root();
-       
-               if (check != True) {
-                       pdb_free_sam(&sam_user);
-                       passwd_free(&pass);
-                       continue;
-               }
-       
-               urid = pdb_get_user_rid(sam_user);
-               if (urid == 0) {
-                       pdb_free_sam(&sam_user);
-                       passwd_free(&pass);
-                       continue;
+               
+               if (sid_peek_check_rid(get_global_sam_sid(), &sids[i], &urid)) {
+                       rid[final_num_sids] = urid;
+                       attr[final_num_sids] = SID_NAME_USER;
+                       final_num_sids++;
+               } else {
+                       fstring user_sid_str, domain_sid_str;
+                       DEBUG(1, ("_samr_query_groupmem: SID %s in group %s is not in our domain %s\n",
+                                 sid_to_string(user_sid_str, &sids[i]), 
+                                 sid_to_string(group_sid_str, &group_sid),
+                                 sid_to_string(domain_sid_str, get_global_sam_sid())));
                }
-
-               pdb_free_sam(&sam_user);
-               passwd_free(&pass);
-
-               rid[i] = urid;
-               attr[i] = SID_NAME_USER;                
        }
 
-       init_samr_r_query_groupmem(r_u, num_uids, rid, attr, NT_STATUS_OK);
+       init_samr_r_query_groupmem(r_u, final_num_sids, rid, attr, NT_STATUS_OK);
 
        return NT_STATUS_OK;
 }
@@ -3408,13 +3360,13 @@ NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_AD
 
        if (sid_compare(&alias_sid, get_global_sam_sid())>0) {
                DEBUG(10, ("adding member on Server SID\n"));
-               if(!get_local_group_from_sid(alias_sid, &map, MAPPING_WITHOUT_PRIV))
+               if(!get_local_group_from_sid(&alias_sid, &map))
                        return NT_STATUS_NO_SUCH_ALIAS;
        
        } else {
                if (sid_compare(&alias_sid, &global_sid_Builtin)>0) {
                        DEBUG(10, ("adding member on BUILTIN SID\n"));
-                       if( !get_local_group_from_sid(alias_sid, &map, MAPPING_WITHOUT_PRIV))
+                       if( !get_builtin_group_from_sid(&alias_sid, &map))
                                return NT_STATUS_NO_SUCH_ALIAS;
 
                } else
@@ -3431,9 +3383,9 @@ NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_AD
                pdb_free_sam(&sam_user);
                return NT_STATUS_NO_SUCH_USER;
        }
-       
-       uid = pdb_get_uid(sam_user);
-       if (uid == -1) {
+
+       /* check a real user exist before we run the script to add a user to a group */
+       if (!NT_STATUS_IS_OK(sid_to_uid(pdb_get_user_sid(sam_user), &uid))) {
                pdb_free_sam(&sam_user);
                return NT_STATUS_NO_SUCH_USER;
        }
@@ -3443,7 +3395,7 @@ NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_AD
        if ((pwd=getpwuid_alloc(uid)) == NULL) {
                return NT_STATUS_NO_SUCH_USER;
        }
-
+       
        if ((grp=getgrgid(map.gid)) == NULL) {
                passwd_free(&pwd);
                return NT_STATUS_NO_SUCH_ALIAS;
@@ -3505,7 +3457,7 @@ NTSTATUS _samr_del_aliasmem(pipes_struct *p, SAMR_Q_DEL_ALIASMEM *q_u, SAMR_R_DE
                return NT_STATUS_NO_SUCH_ALIAS;
        }
 
-       if( !get_local_group_from_sid(alias_sid, &map, MAPPING_WITHOUT_PRIV))
+       if( !get_local_group_from_sid(&alias_sid, &map))
                return NT_STATUS_NO_SUCH_ALIAS;
 
        if ((grp=getgrgid(map.gid)) == NULL)
@@ -3549,11 +3501,11 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
        DOM_SID group_sid;
        DOM_SID user_sid;
        fstring group_sid_str;
+       uid_t uid;
        struct passwd *pwd;
        struct group *grp;
        fstring grp_name;
        GROUP_MAP map;
-       uid_t uid;
        NTSTATUS ret;
        SAM_ACCOUNT *sam_user=NULL;
        BOOL check;
@@ -3575,7 +3527,7 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
 
        DEBUG(10, ("lookup on Domain SID\n"));
 
-       if(!get_domain_group_from_sid(group_sid, &map, MAPPING_WITHOUT_PRIV))
+       if(!get_domain_group_from_sid(group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
 
        sid_copy(&user_sid, get_global_sam_sid());
@@ -3591,9 +3543,9 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
                pdb_free_sam(&sam_user);
                return NT_STATUS_NO_SUCH_USER;
        }
-       
-       uid = pdb_get_uid(sam_user);
-       if (uid == -1) {
+
+       /* check a real user exist before we run the script to add a user to a group */
+       if (!NT_STATUS_IS_OK(sid_to_uid(pdb_get_user_sid(sam_user), &uid))) {
                pdb_free_sam(&sam_user);
                return NT_STATUS_NO_SUCH_USER;
        }
@@ -3670,7 +3622,7 @@ NTSTATUS _samr_del_groupmem(pipes_struct *p, SAMR_Q_DEL_GROUPMEM *q_u, SAMR_R_DE
        sid_copy(&user_sid, get_global_sam_sid());
        sid_append_rid(&user_sid, q_u->rid);
 
-       if (!get_domain_group_from_sid(group_sid, &map, MAPPING_WITHOUT_PRIV))
+       if (!get_domain_group_from_sid(group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
 
        if ((grp=getgrgid(map.gid)) == NULL)
@@ -3715,12 +3667,25 @@ static int smb_delete_user(const char *unix_user)
        pstring del_script;
        int ret;
 
+       /* try winbindd first since it is impossible to determine where 
+          a user came from via NSS.  Try the delete user script if this fails
+          meaning the user did not exist in winbindd's list of accounts */
+
+       if ( winbind_delete_user( unix_user ) ) {
+               DEBUG(3,("winbind_delete_user: removed user (%s)\n", unix_user));
+               return 0;
+       }
+
+
+       /* fall back to 'delete user script' */
+
        pstrcpy(del_script, lp_deluser_script());
        if (! *del_script)
                return -1;
        all_string_sub(del_script, "%u", unix_user, sizeof(pstring));
        ret = smbrun(del_script,NULL);
        DEBUG(3,("smb_delete_user: Running the command `%s' gave %d\n",del_script,ret));
+
        return ret;
 }
 
@@ -3750,7 +3715,8 @@ NTSTATUS _samr_delete_dom_user(pipes_struct *p, SAMR_Q_DELETE_DOM_USER *q_u, SAM
        /* check if the user exists before trying to delete */
        pdb_init_sam(&sam_pass);
        if(!pdb_getsampwsid(sam_pass, &user_sid)) {
-               DEBUG(5,("_samr_delete_dom_user:User %s doesn't exist.\n", pdb_get_username(sam_pass)));
+               DEBUG(5,("_samr_delete_dom_user:User %s doesn't exist.\n", 
+                       sid_string_static(&user_sid)));
                pdb_free_sam(&sam_pass);
                return NT_STATUS_NO_SUCH_USER;
        }
@@ -3815,7 +3781,7 @@ NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, S
 
        DEBUG(10, ("lookup on Domain SID\n"));
 
-       if(!get_domain_group_from_sid(group_sid, &map, MAPPING_WITHOUT_PRIV))
+       if(!get_domain_group_from_sid(group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
 
        gid=map.gid;
@@ -3824,6 +3790,10 @@ NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, S
        if ( (grp=getgrgid(gid)) == NULL)
                return NT_STATUS_NO_SUCH_GROUP;
 
+       /* delete mapping first */
+       if(!pdb_delete_group_mapping_entry(group_sid))
+               return NT_STATUS_ACCESS_DENIED;
+               
        /* we can delete the UNIX group */
        smb_delete_group(grp->gr_name);
 
@@ -3831,8 +3801,6 @@ NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, S
        if ( (grp=getgrgid(gid)) != NULL)
                return NT_STATUS_ACCESS_DENIED;
 
-       if(!pdb_delete_group_mapping_entry(group_sid))
-               return NT_STATUS_ACCESS_DENIED;
 
        if (!close_policy_hnd(p, &q_u->group_pol))
                return NT_STATUS_OBJECT_NAME_INVALID;
@@ -3877,7 +3845,7 @@ NTSTATUS _samr_delete_dom_alias(pipes_struct *p, SAMR_Q_DELETE_DOM_ALIAS *q_u, S
 
        DEBUG(10, ("lookup on Local SID\n"));
 
-       if(!get_local_group_from_sid(alias_sid, &map, MAPPING_WITHOUT_PRIV))
+       if(!get_local_group_from_sid(&alias_sid, &map))
                return NT_STATUS_NO_SUCH_ALIAS;
 
        gid=map.gid;
@@ -3914,12 +3882,9 @@ NTSTATUS _samr_create_dom_group(pipes_struct *p, SAMR_Q_CREATE_DOM_GROUP *q_u, S
        fstring sid_string;
        struct group *grp;
        struct samr_info *info;
-       PRIVILEGE_SET priv_set;
        uint32 acc_granted;
        gid_t gid;
 
-       init_privilege(&priv_set);
-
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->pol, &dom_sid, &acc_granted)) 
                return NT_STATUS_INVALID_HANDLE;
@@ -3954,7 +3919,7 @@ NTSTATUS _samr_create_dom_group(pipes_struct *p, SAMR_Q_CREATE_DOM_GROUP *q_u, S
        sid_append_rid(&info_sid, r_u->rid);
        sid_to_string(sid_string, &info_sid);
 
-       if(!add_initial_entry(grp->gr_gid, sid_string, SID_NAME_DOM_GRP, name, NULL, priv_set, PR_ACCESS_FROM_NETWORK))
+       if(!add_initial_entry(grp->gr_gid, sid_string, SID_NAME_DOM_GRP, name, NULL))
                return NT_STATUS_ACCESS_DENIED;
 
        if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
@@ -3979,12 +3944,9 @@ NTSTATUS _samr_create_dom_alias(pipes_struct *p, SAMR_Q_CREATE_DOM_ALIAS *q_u, S
        fstring sid_string;
        struct group *grp;
        struct samr_info *info;
-       PRIVILEGE_SET priv_set;
        uint32 acc_granted;
        gid_t gid;
 
-       init_privilege(&priv_set);
-
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->dom_pol, &dom_sid, &acc_granted)) 
                return NT_STATUS_INVALID_HANDLE;
@@ -4019,7 +3981,7 @@ NTSTATUS _samr_create_dom_alias(pipes_struct *p, SAMR_Q_CREATE_DOM_ALIAS *q_u, S
        sid_to_string(sid_string, &info_sid);
 
        /* add the group to the mapping table */
-       if(!add_initial_entry(grp->gr_gid, sid_string, SID_NAME_ALIAS, name, NULL, priv_set, PR_ACCESS_FROM_NETWORK))
+       if(!add_initial_entry(grp->gr_gid, sid_string, SID_NAME_ALIAS, name, NULL))
                return NT_STATUS_ACCESS_DENIED;
 
        if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
@@ -4043,10 +4005,11 @@ NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAM
 {
        DOM_SID group_sid;
        GROUP_MAP map;
-       uid_t *uid=NULL;
-       int num_uids=0;
+       DOM_SID *sids=NULL;
+       int num_sids=0;
        GROUP_INFO_CTR *ctr;
        uint32 acc_granted;
+       BOOL ret;
 
        if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted)) 
                return NT_STATUS_INVALID_HANDLE;
@@ -4055,7 +4018,10 @@ NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAM
                return r_u->status;
        }
                
-       if (!get_domain_group_from_sid(group_sid, &map, MAPPING_WITHOUT_PRIV))
+       become_root();
+       ret = get_domain_group_from_sid(group_sid, &map);
+       unbecome_root();
+       if (!ret)
                return NT_STATUS_INVALID_HANDLE;
 
        ctr=(GROUP_INFO_CTR *)talloc_zero(p->mem_ctx, sizeof(GROUP_INFO_CTR));
@@ -4065,10 +4031,10 @@ NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAM
        switch (q_u->switch_level) {
                case 1:
                        ctr->switch_value1 = 1;
-                       if(!get_uid_list_of_group(map.gid, &uid, &num_uids))
+                       if(!get_sid_list_of_group(map.gid, &sids, &num_sids))
                                return NT_STATUS_NO_SUCH_GROUP;
-                       init_samr_group_info1(&ctr->group.info1, map.nt_name, map.comment, num_uids);
-                       SAFE_FREE(uid);
+                       init_samr_group_info1(&ctr->group.info1, map.nt_name, map.comment, num_sids);
+                       SAFE_FREE(sids);
                        break;
                case 3:
                        ctr->switch_value1 = 3;
@@ -4107,7 +4073,7 @@ NTSTATUS _samr_set_groupinfo(pipes_struct *p, SAMR_Q_SET_GROUPINFO *q_u, SAMR_R_
                return r_u->status;
        }
                
-       if (!get_domain_group_from_sid(group_sid, &map, MAPPING_WITH_PRIV))
+       if (!get_domain_group_from_sid(group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
        
        ctr=q_u->ctr;
@@ -4120,17 +4086,13 @@ NTSTATUS _samr_set_groupinfo(pipes_struct *p, SAMR_Q_SET_GROUPINFO *q_u, SAMR_R_
                        unistr2_to_ascii(map.comment, &(ctr->group.info4.uni_acct_desc), sizeof(map.comment)-1);
                        break;
                default:
-                       free_privilege(&map.priv_set);
                        return NT_STATUS_INVALID_INFO_CLASS;
        }
 
        if(!pdb_update_group_mapping_entry(&map)) {
-               free_privilege(&map.priv_set);
                return NT_STATUS_NO_SUCH_GROUP;
        }
 
-       free_privilege(&map.priv_set);
-
        return NT_STATUS_OK;
 }
 
@@ -4154,7 +4116,8 @@ NTSTATUS _samr_set_aliasinfo(pipes_struct *p, SAMR_Q_SET_ALIASINFO *q_u, SAMR_R_
                return r_u->status;
        }
                
-       if (!get_local_group_from_sid(group_sid, &map, MAPPING_WITH_PRIV))
+       if (!get_local_group_from_sid(&group_sid, &map) &&
+           !get_builtin_group_from_sid(&group_sid, &map))
                return NT_STATUS_NO_SUCH_GROUP;
        
        ctr=&q_u->ctr;
@@ -4164,17 +4127,13 @@ NTSTATUS _samr_set_aliasinfo(pipes_struct *p, SAMR_Q_SET_ALIASINFO *q_u, SAMR_R_
                        unistr2_to_ascii(map.comment, &(ctr->alias.info3.uni_acct_desc), sizeof(map.comment)-1);
                        break;
                default:
-                       free_privilege(&map.priv_set);
                        return NT_STATUS_INVALID_INFO_CLASS;
        }
 
        if(!pdb_update_group_mapping_entry(&map)) {
-               free_privilege(&map.priv_set);
                return NT_STATUS_NO_SUCH_GROUP;
        }
 
-       free_privilege(&map.priv_set);
-
        return NT_STATUS_OK;
 }
 
@@ -4211,10 +4170,11 @@ NTSTATUS _samr_open_group(pipes_struct *p, SAMR_Q_OPEN_GROUP *q_u, SAMR_R_OPEN_G
        struct samr_info *info;
        SEC_DESC         *psd = NULL;
        uint32            acc_granted;
-       uint32            des_access;
+       uint32            des_access = q_u->access_mask;
        size_t            sd_size;
        NTSTATUS          status;
        fstring sid_string;
+       BOOL ret;
 
        if (!get_lsa_policy_samr_sid(p, &q_u->domain_pol, &sid, &acc_granted)) 
                return NT_STATUS_INVALID_HANDLE;
@@ -4249,7 +4209,10 @@ NTSTATUS _samr_open_group(pipes_struct *p, SAMR_Q_OPEN_GROUP *q_u, SAMR_R_OPEN_G
        DEBUG(10, ("_samr_open_group:Opening SID: %s\n", sid_string));
 
        /* check if that group really exists */
-       if (!get_domain_group_from_sid(info->sid, &map, MAPPING_WITHOUT_PRIV))
+       become_root();
+       ret = get_domain_group_from_sid(info->sid, &map);
+       unbecome_root();
+       if (!ret)
                return NT_STATUS_NO_SUCH_GROUP;
 
        /* get a (unique) handle.  open a policy on it. */
@@ -4260,13 +4223,114 @@ NTSTATUS _samr_open_group(pipes_struct *p, SAMR_Q_OPEN_GROUP *q_u, SAMR_R_OPEN_G
 }
 
 /*********************************************************************
- _samr_unknown_2d
+ _samr_remove_sid_foreign_domain
 *********************************************************************/
 
-NTSTATUS _samr_unknown_2d(pipes_struct *p, SAMR_Q_UNKNOWN_2D *q_u, SAMR_R_UNKNOWN_2D *r_u)
+NTSTATUS _samr_remove_sid_foreign_domain(pipes_struct *p, 
+                                          SAMR_Q_REMOVE_SID_FOREIGN_DOMAIN *q_u, 
+                                          SAMR_R_REMOVE_SID_FOREIGN_DOMAIN *r_u)
 {
-       DEBUG(0,("_samr_unknown_2d: Not yet implemented.\n"));
-       return NT_STATUS_NOT_IMPLEMENTED;
+       DOM_SID                 delete_sid, alias_sid;
+       SAM_ACCOUNT             *sam_pass=NULL;
+       uint32                  acc_granted;
+       GROUP_MAP               map;
+       BOOL                    is_user = False;
+       NTSTATUS                result;
+       enum SID_NAME_USE       type = SID_NAME_UNKNOWN;
+       
+       sid_copy( &delete_sid, &q_u->sid.sid );
+       
+       DEBUG(5,("_samr_remove_sid_foreign_domain: removing SID [%s]\n",
+               sid_string_static(&delete_sid)));
+               
+       /* Find the policy handle. Open a policy on it. */
+       
+       if (!get_lsa_policy_samr_sid(p, &q_u->dom_pol, &alias_sid, &acc_granted)) 
+               return NT_STATUS_INVALID_HANDLE;
+       
+       result = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, 
+               "_samr_remove_sid_foreign_domain");
+               
+       if (!NT_STATUS_IS_OK(result)) 
+               return result;
+                       
+       DEBUG(8, ("_samr_remove_sid_foreign_domain:sid is %s\n", 
+               sid_string_static(&alias_sid)));
+               
+       /* make sure we can handle this */
+       
+       if ( sid_check_is_domain(&alias_sid) )
+               type = SID_NAME_DOM_GRP;
+       else if ( sid_check_is_builtin(&alias_sid) )
+               type = SID_NAME_ALIAS;
+       
+       if ( type == SID_NAME_UNKNOWN ) {
+               DEBUG(10, ("_samr_remove_sid_foreign_domain: can't operate on what we don't own!\n"));
+               return NT_STATUS_OK;
+       }
+
+       /* check if the user exists before trying to delete */
+       
+       pdb_init_sam(&sam_pass);
+       
+       if ( pdb_getsampwsid(sam_pass, &delete_sid) ) {
+               is_user = True;
+       } else {
+               /* maybe it is a group */
+               if( !pdb_getgrsid(&map, delete_sid) ) {
+                       DEBUG(3,("_samr_remove_sid_foreign_domain: %s is not a user or a group!\n",
+                               sid_string_static(&delete_sid)));
+                       result = NT_STATUS_INVALID_SID;
+                       goto done;
+               }
+       }
+       
+       /* we can only delete a user from a group since we don't have 
+          nested groups anyways.  So in the latter case, just say OK */
+          
+       if ( is_user ) {
+               GROUP_MAP       *mappings = NULL;
+               int             num_groups, i;
+               struct group    *grp2;
+               
+               if ( pdb_enum_group_mapping(type, &mappings, &num_groups, False) && num_groups>0 ) {
+               
+                       /* interate over the groups */
+                       for ( i=0; i<num_groups; i++ ) {
+
+                               grp2 = getgrgid(mappings[i].gid);
+
+                               if ( !grp2 ) {
+                                       DEBUG(0,("_samr_remove_sid_foreign_domain: group mapping without UNIX group!\n"));
+                                       continue;
+                               }
+                       
+                               if ( !user_in_unix_group_list(pdb_get_username(sam_pass), grp2->gr_name) )
+                                       continue;
+                               
+                               smb_delete_user_group(grp2->gr_name, pdb_get_username(sam_pass));
+                               
+                               if ( user_in_unix_group_list(pdb_get_username(sam_pass), grp2->gr_name) ) {
+                                       /* should we fail here ? */
+                                       DEBUG(0,("_samr_remove_sid_foreign_domain: Delete user [%s] from group [%s] failed!\n",
+                                               pdb_get_username(sam_pass), grp2->gr_name ));
+                                       continue;
+                               }
+                                       
+                               DEBUG(10,("_samr_remove_sid_foreign_domain: Removed user [%s] from group [%s]!\n",
+                                       pdb_get_username(sam_pass), grp2->gr_name ));
+                       }
+                       
+                       SAFE_FREE(mappings);
+               }
+       }
+       
+       result = NT_STATUS_OK;
+done:
+
+       pdb_free_sam(&sam_pass);
+
+       return result;
 }
 
 /*******************************************************************
@@ -4438,8 +4502,8 @@ NTSTATUS _samr_set_dom_info(pipes_struct *p, SAMR_Q_SET_DOMAIN_INFO *q_u, SAMR_R
                case 0x07:
                        break;
                case 0x0c:
-                       u_lock_duration=nt_time_to_unix_abs(&q_u->ctr->info.inf12.duration);
-                       u_reset_time=nt_time_to_unix_abs(&q_u->ctr->info.inf12.reset_count);
+                       u_lock_duration=nt_time_to_unix_abs(&q_u->ctr->info.inf12.duration)/60;
+                       u_reset_time=nt_time_to_unix_abs(&q_u->ctr->info.inf12.reset_count)/60;
                        
                        account_policy_set(AP_LOCK_ACCOUNT_DURATION, (int)u_lock_duration);
                        account_policy_set(AP_RESET_COUNT_TIME, (int)u_reset_time);
@@ -4455,4 +4519,3 @@ NTSTATUS _samr_set_dom_info(pipes_struct *p, SAMR_Q_SET_DOMAIN_INFO *q_u, SAMR_R
 
        return r_u->status;
 }
-