r5203: additional changes for BUG 2291 to restrict who can join a BDC and add domain...
[tprouty/samba.git] / source / rpc_server / srv_samr_nt.c
index 1959674f0add2c1bd3eda53a4a8341302c33b21b..83da81044465ed4f52f3aa7d51625ebd02fd1ec5 100644 (file)
@@ -1,14 +1,14 @@
 /*
  *  Unix SMB/CIFS implementation.
  *  RPC Pipe client / server routines
- *  Copyright (C) Andrew Tridgell              1992-1997,
- *  Copyright (C) Luke Kenneth Casson Leighton 1996-1997,
+ *  Copyright (C) Andrew Tridgell                   1992-1997,
+ *  Copyright (C) Luke Kenneth Casson Leighton      1996-1997,
  *  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) Jim McDonough <jmcd@us.ibm.com>   2002.
- *  Copyright (C) Gerald (Jerry) Carter             2003.
+ *  Copyright (C) Jeremy Allison                    2001-2002,
+ *  Copyright (C) Jean François Micouleau          1998-2001,
+ *  Copyright (C) Jim McDonough <jmcd@us.ibm.com>   2002,
+ *  Copyright (C) Gerald (Jerry) Carter             2003-2004,
  *
  *  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
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_RPC_SRV
 
+#define SAMR_USR_RIGHTS_WRITE_PW \
+               ( READ_CONTROL_ACCESS           | \
+                 SA_RIGHT_USER_CHANGE_PASSWORD | \
+                 SA_RIGHT_USER_SET_LOC_COM )
+
 extern DOM_SID global_sid_Builtin;
 
 extern rid_name domain_group_rids[];
 extern rid_name domain_alias_rids[];
 extern rid_name builtin_alias_rids[];
 
-extern PRIVS privs[];
 
 typedef struct _disp_info {
        BOOL user_dbloaded;
@@ -57,7 +61,7 @@ struct samr_info {
        uint32 status; /* some sort of flag.  best to record it.  comes from opnum 0x39 */
        uint32 acc_granted;
        uint16 acb_mask;
-       BOOL all_machines;
+       BOOL only_machines;
        DISP_INFO disp_info;
 
        TALLOC_CTX *mem_ctx;
@@ -69,31 +73,121 @@ struct generic_mapping usr_generic_mapping = {GENERIC_RIGHTS_USER_READ, GENERIC_
 struct generic_mapping grp_generic_mapping = {GENERIC_RIGHTS_GROUP_READ, GENERIC_RIGHTS_GROUP_WRITE, GENERIC_RIGHTS_GROUP_EXECUTE, GENERIC_RIGHTS_GROUP_ALL_ACCESS};
 struct generic_mapping ali_generic_mapping = {GENERIC_RIGHTS_ALIAS_READ, GENERIC_RIGHTS_ALIAS_WRITE, GENERIC_RIGHTS_ALIAS_EXECUTE, GENERIC_RIGHTS_ALIAS_ALL_ACCESS};
 
-static NTSTATUS samr_make_dom_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size);
+/*******************************************************************
+*******************************************************************/
+
+static NTSTATUS make_samr_object_sd( TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size,
+                                     struct generic_mapping *map,
+                                    DOM_SID *sid, uint32 sid_access )
+{
+       extern DOM_SID global_sid_World;
+       DOM_SID adm_sid, act_sid, domadmin_sid;
+       SEC_ACE ace[5];         /* at most 5 entries */
+       SEC_ACCESS mask;
+       size_t i = 0;
+
+       SEC_ACL *psa = NULL;
+
+       /* basic access for Everyone */
+       
+       init_sec_access(&mask, map->generic_execute | map->generic_read );
+       init_sec_ace(&ace[i++], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       
+       /* add Full Access 'BUILTIN\Administrators' and 'BUILTIN\Account Operators */
+       
+       sid_copy(&adm_sid, &global_sid_Builtin);
+       sid_append_rid(&adm_sid, BUILTIN_ALIAS_RID_ADMINS);
+
+       sid_copy(&act_sid, &global_sid_Builtin);
+       sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
+       
+       init_sec_access(&mask, map->generic_all);
+       
+       init_sec_ace(&ace[i++], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       init_sec_ace(&ace[i++], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       
+       /* Add Full Access for Domain Admins if we are a DC */
+       
+       if ( IS_DC ) {
+               sid_copy( &domadmin_sid, get_global_sam_sid() );
+               sid_append_rid( &domadmin_sid, DOMAIN_GROUP_RID_ADMINS );
+               init_sec_ace(&ace[i++], &domadmin_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       }
+
+       /* if we have a sid, give it some special access */
+       
+       if ( sid ) {
+               init_sec_access( &mask, sid_access );
+               init_sec_ace(&ace[i++], sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
+       }
+       
+       /* create the security descriptor */
+       
+       if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, i, ace)) == NULL)
+               return NT_STATUS_NO_MEMORY;
+
+       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;
+}
 
 /*******************************************************************
  Checks if access to an object should be granted, and returns that
  level of access for further checks.
 ********************************************************************/
 
-NTSTATUS access_check_samr_object(SEC_DESC *psd, NT_USER_TOKEN *nt_user_token, uint32 des_access, 
-                                 uint32 *acc_granted, const char *debug) 
+static NTSTATUS access_check_samr_object( SEC_DESC *psd, NT_USER_TOKEN *token, 
+                                          SE_PRIV *rights, uint32 rights_mask,
+                                          uint32 des_access, uint32 *acc_granted, 
+                                         const char *debug )
 {
        NTSTATUS status = NT_STATUS_ACCESS_DENIED;
+       uint32 saved_mask = 0;
 
-       if (!se_access_check(psd, nt_user_token, des_access, acc_granted, &status)) {
+       /* check privileges; certain SAM access bits should be overridden 
+          by privileges (mostly having to do with creating/modifying/deleting 
+          users and groups) */
+       
+       if ( rights && user_has_any_privilege( token, rights ) ) {
+       
+               saved_mask = (des_access & rights_mask);
+               des_access &= ~saved_mask;
+               
+               DEBUG(4,("access_check_samr_object: user rights access mask [0x%x]\n",
+                       rights_mask));
+       }
+               
+       
+       /* check the security descriptor first */
+       
+       if ( se_access_check(psd, token, des_access, acc_granted, &status) )
+               goto done;
+       
+       /* give root a free pass */
+       
+       if ( geteuid() == sec_initial_uid() ) {
+       
+               DEBUG(4,("%s: ACCESS should be DENIED  (requested: %#010x)\n", debug, des_access));
+               DEBUGADD(4,("but overritten by euid == sec_initial_uid()\n"));
+               
                *acc_granted = des_access;
-               if (geteuid() == sec_initial_uid()) {
-                       DEBUG(4,("%s: ACCESS should be DENIED  (requested: %#010x)\n",
-                               debug, des_access));
-                       DEBUGADD(4,("but overritten by euid == sec_initial_uid()\n"));
-                       status = NT_STATUS_OK;
-               }
-               else {
-                       DEBUG(2,("%s: ACCESS DENIED  (requested: %#010x)\n",
-                               debug, des_access));
-               }
+               
+               status = NT_STATUS_OK;
+               goto done;
        }
+       
+       
+done:
+       /* add in any bits saved during the privilege check (only 
+          matters is status is ok) */
+       
+       *acc_granted |= rights_mask;
+
+       DEBUG(4,("%s: access %s (requested: 0x%08x, granted: 0x%08x)\n", 
+               debug, NT_STATUS_IS_OK(status) ? "GRANTED" : "DENIED", 
+               des_access, *acc_granted));
+       
        return status;
 }
 
@@ -101,22 +195,31 @@ NTSTATUS access_check_samr_object(SEC_DESC *psd, NT_USER_TOKEN *nt_user_token, u
  Checks if access to a function can be granted
 ********************************************************************/
 
-NTSTATUS access_check_samr_function(uint32 acc_granted, uint32 acc_required, const char *debug)
+static NTSTATUS access_check_samr_function(uint32 acc_granted, uint32 acc_required, const char *debug)
 {
-       DEBUG(5,("%s: access check ((granted: %#010x;  required: %#010x)\n",
-                       debug, acc_granted, acc_required));
-       if ((acc_granted & acc_required) != acc_required) {
-               if (geteuid() == sec_initial_uid()) {
-                       DEBUG(4,("%s: ACCESS should be DENIED (granted: %#010x;  required: %#010x)\n",
-                               debug, acc_granted, acc_required));
-                       DEBUGADD(4,("but overwritten by euid == 0\n"));
-                       return NT_STATUS_OK;
-               }
-               DEBUG(2,("%s: ACCESS DENIED (granted: %#010x;  required: %#010x)\n",
+       DEBUG(5,("%s: access check ((granted: %#010x;  required: %#010x)\n",  
+               debug, acc_granted, acc_required));
+
+       /* check the security descriptor first */
+       
+       if ( (acc_granted&acc_required) == acc_required )
+               return NT_STATUS_OK;
+               
+       /* give root a free pass */
+
+       if (geteuid() == sec_initial_uid()) {
+       
+               DEBUG(4,("%s: ACCESS should be DENIED (granted: %#010x;  required: %#010x)\n",
                        debug, acc_granted, acc_required));
-               return NT_STATUS_ACCESS_DENIED;
+               DEBUGADD(4,("but overwritten by euid == 0\n"));
+               
+               return NT_STATUS_OK;
        }
-       return NT_STATUS_OK;
+       
+       DEBUG(2,("%s: ACCESS DENIED (granted: %#010x;  required: %#010x)\n", 
+               debug, acc_granted, acc_required));
+               
+       return NT_STATUS_ACCESS_DENIED;
 }
 
 
@@ -138,7 +241,7 @@ static struct samr_info *get_samr_info_by_sid(DOM_SID *psid)
 
        mem_ctx = talloc_init("samr_info for domain sid %s", sid_str);
 
-       if ((info = (struct samr_info *)talloc(mem_ctx, sizeof(struct samr_info))) == NULL)
+       if ((info = TALLOC_P(mem_ctx, struct samr_info)) == NULL)
                return NULL;
 
        ZERO_STRUCTP(info);
@@ -210,34 +313,40 @@ 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)
+static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOOL only_machines)
 {
        SAM_ACCOUNT *pwd = NULL;
        SAM_ACCOUNT *pwd_array = NULL;
        NTSTATUS nt_status = NT_STATUS_OK;
        TALLOC_CTX *mem_ctx = info->mem_ctx;
+       uint16 query_acb_mask = acb_mask;
 
        DEBUG(10,("load_sampwd_entries\n"));
 
        /* if the snapshoot is already loaded, return */
        if ((info->disp_info.user_dbloaded==True) 
            && (info->acb_mask == acb_mask) 
-           && (info->all_machines == all_machines)) {
+           && (info->only_machines == only_machines)) {
                DEBUG(10,("load_sampwd_entries: already in memory\n"));
                return NT_STATUS_OK;
        }
 
        free_samr_users(info);
+       
+       if (only_machines) {
+               query_acb_mask |= ACB_WSTRUST;
+               query_acb_mask |= ACB_SVRTRUST;
+       }
 
-       if (!pdb_setsampwent(False)) {
+       if (!pdb_setsampwent(False, query_acb_mask)) {
                DEBUG(0, ("load_sampwd_entries: Unable to open passdb.\n"));
                return NT_STATUS_ACCESS_DENIED;
        }
 
        for (; (NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(mem_ctx, &pwd))) 
                     && pdb_getsampwent(pwd) == True; pwd=NULL) {
-               
-               if (all_machines) {
+       
+               if (only_machines) {
                        if (!((pdb_get_acct_ctrl(pwd) & ACB_WSTRUST) 
                              || (pdb_get_acct_ctrl(pwd) & ACB_SVRTRUST))) {
                                DEBUG(5,("load_sampwd_entries: '%s' is not a machine account - ACB: %x - skipping\n", pdb_get_username(pwd), acb_mask));
@@ -256,8 +365,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=(SAM_ACCOUNT *)talloc_realloc(mem_ctx, info->disp_info.disp_user_info, 
-                                         (info->disp_info.num_user_account+MAX_SAM_ENTRIES)*sizeof(SAM_ACCOUNT));
+                       pwd_array=TALLOC_REALLOC_ARRAY(mem_ctx, info->disp_info.disp_user_info, SAM_ACCOUNT,
+                                         info->disp_info.num_user_account+MAX_SAM_ENTRIES);
 
                        if (pwd_array==NULL)
                                return NT_STATUS_NO_MEMORY;
@@ -278,7 +387,7 @@ static NTSTATUS load_sampwd_entries(struct samr_info *info, uint16 acb_mask, BOO
        /* the snapshoot is in memory, we're ready to enumerate fast */
 
        info->acb_mask = acb_mask;
-       info->all_machines = all_machines;
+       info->only_machines = only_machines;
        info->disp_info.user_dbloaded=True;
 
        DEBUG(10,("load_sampwd_entries: done\n"));
@@ -303,6 +412,13 @@ static NTSTATUS load_group_domain_entries(struct samr_info *info, DOM_SID *sid)
                return NT_STATUS_OK;
        }
        
+       if (sid_equal(sid, &global_sid_Builtin)) {
+               /* No domain groups for now in the BUILTIN domain */
+               info->disp_info.num_group_account=0;
+               info->disp_info.disp_group_info=NULL;
+               info->disp_info.group_dbloaded=True;
+               return NT_STATUS_OK;
+       }
 
        become_root();
        ret = pdb_enum_group_mapping(SID_NAME_DOM_GRP, &map, (int *)&group_entries, ENUM_ONLY_MAPPED); 
@@ -316,7 +432,7 @@ static NTSTATUS load_group_domain_entries(struct samr_info *info, DOM_SID *sid)
 
        info->disp_info.num_group_account=group_entries;
 
-       grp_array=(DOMAIN_GRP *)talloc(mem_ctx, info->disp_info.num_group_account*sizeof(DOMAIN_GRP));
+       grp_array=TALLOC_ARRAY(mem_ctx, DOMAIN_GRP, info->disp_info.num_group_account);
        if (group_entries!=0 && grp_array==NULL) {
                DEBUG(1, ("load_group_domain_entries: talloc() failed for grp_array!\n"));
                SAFE_FREE(map);
@@ -371,28 +487,37 @@ NTSTATUS _samr_open_domain(pipes_struct *p, SAMR_Q_OPEN_DOMAIN *q_u, SAMR_R_OPEN
        SEC_DESC *psd = NULL;
        uint32    acc_granted;
        uint32    des_access = q_u->flags;
-       size_t    sd_size;
        NTSTATUS  status;
+       size_t sd_size;
+       SE_PRIV se_rights;
 
        r_u->status = NT_STATUS_OK;
 
        /* find the connection policy handle. */
-       if (!find_policy_by_hnd(p, &q_u->pol, (void**)&info))
+       
+       if ( !find_policy_by_hnd(p, &q_u->pol, (void**)&info) )
                return NT_STATUS_INVALID_HANDLE;
 
-       if (!NT_STATUS_IS_OK(status = access_check_samr_function(info->acc_granted, SA_RIGHT_SAM_OPEN_DOMAIN,"_samr_open_domain"))) {
+       status = access_check_samr_function( info->acc_granted, 
+               SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_open_domain" );
+               
+       if ( !NT_STATUS_IS_OK(status) )
                return status;
-       }
 
        /*check if access can be granted as requested by client. */
-       samr_make_dom_obj_sd(p->mem_ctx, &psd, &sd_size);
-       se_map_generic(&des_access,&dom_generic_mapping);
+       
+       make_samr_object_sd( p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0 );
+       se_map_generic( &des_access, &dom_generic_mapping );
+       
+       se_priv_copy( &se_rights, &se_machine_account );
+       se_priv_add( &se_rights, &se_add_users );
 
-       if (!NT_STATUS_IS_OK(status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_open_domain"))) {
+       status = access_check_samr_object( psd, p->pipe_user.nt_user_token, 
+               &se_rights, GENERIC_RIGHTS_DOMAIN_WRITE, des_access, 
+               &acc_granted, "_samr_open_domain" );
+               
+       if ( !NT_STATUS_IS_OK(status) )
                return status;
-       }
 
        /* associate the domain SID with the (unique) handle. */
        if ((info = get_samr_info_by_sid(&q_u->dom_sid.sid))==NULL)
@@ -437,167 +562,23 @@ NTSTATUS _samr_get_usrdom_pwinfo(pipes_struct *p, SAMR_Q_GET_USRDOM_PWINFO *q_u,
        return r_u->status;
 }
 
-/*******************************************************************
- samr_make_dom_obj_sd
- ********************************************************************/
-
-static NTSTATUS samr_make_dom_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size)
-{
-       extern DOM_SID global_sid_World;
-       DOM_SID adm_sid;
-       DOM_SID act_sid;
-
-       SEC_ACE ace[3];
-       SEC_ACCESS mask;
-
-       SEC_ACL *psa = NULL;
-
-       sid_copy(&adm_sid, &global_sid_Builtin);
-       sid_append_rid(&adm_sid, BUILTIN_ALIAS_RID_ADMINS);
-
-       sid_copy(&act_sid, &global_sid_Builtin);
-       sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
-
-       /*basic access for every one*/
-       init_sec_access(&mask, GENERIC_RIGHTS_DOMAIN_EXECUTE | GENERIC_RIGHTS_DOMAIN_READ);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       /*full access for builtin aliases Administrators and Account Operators*/
-       init_sec_access(&mask, GENERIC_RIGHTS_DOMAIN_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[2], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       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, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
-               return NT_STATUS_NO_MEMORY;
-
-       return NT_STATUS_OK;
-}
 
 /*******************************************************************
- samr_make_usr_obj_sd
+ _samr_set_sec_obj
  ********************************************************************/
 
-static NTSTATUS samr_make_usr_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size, DOM_SID *usr_sid)
+NTSTATUS _samr_set_sec_obj(pipes_struct *p, SAMR_Q_SET_SEC_OBJ *q_u, SAMR_R_SET_SEC_OBJ *r_u)
 {
-       extern DOM_SID global_sid_World;
-       DOM_SID adm_sid;
-       DOM_SID act_sid;
-
-       SEC_ACE ace[4];
-       SEC_ACCESS mask;
-
-       SEC_ACL *psa = NULL;
-
-       sid_copy(&adm_sid, &global_sid_Builtin);
-       sid_append_rid(&adm_sid, BUILTIN_ALIAS_RID_ADMINS);
-
-       sid_copy(&act_sid, &global_sid_Builtin);
-       sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
-
-       /*basic access for every one*/
-       init_sec_access(&mask, GENERIC_RIGHTS_USER_EXECUTE | GENERIC_RIGHTS_USER_READ);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       /*full access for builtin aliases Administrators and Account Operators*/
-       init_sec_access(&mask, GENERIC_RIGHTS_USER_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[2], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       /*extended access for the user*/
-       init_sec_access(&mask,READ_CONTROL_ACCESS | SA_RIGHT_USER_CHANGE_PASSWORD | SA_RIGHT_USER_SET_LOC_COM);
-       init_sec_ace(&ace[3], usr_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       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, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
-               return NT_STATUS_NO_MEMORY;
-
-       return NT_STATUS_OK;
+       DEBUG(0,("_samr_set_sec_obj: Not yet implemented!\n"));
+       return NT_STATUS_NOT_IMPLEMENTED;
 }
 
-/*******************************************************************
- samr_make_grp_obj_sd
- ********************************************************************/
-
-static NTSTATUS samr_make_grp_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size)
-{
-       extern DOM_SID global_sid_World;
-       DOM_SID adm_sid;
-       DOM_SID act_sid;
-
-       SEC_ACE ace[3];
-       SEC_ACCESS mask;
-
-       SEC_ACL *psa = NULL;
-
-       sid_copy(&adm_sid, &global_sid_Builtin);
-       sid_append_rid(&adm_sid, BUILTIN_ALIAS_RID_ADMINS);
-
-       sid_copy(&act_sid, &global_sid_Builtin);
-       sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
-
-       /*basic access for every one*/
-       init_sec_access(&mask, GENERIC_RIGHTS_GROUP_EXECUTE | GENERIC_RIGHTS_GROUP_READ);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       /*full access for builtin aliases Administrators and Account Operators*/
-       init_sec_access(&mask, GENERIC_RIGHTS_GROUP_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[2], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       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, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
-               return NT_STATUS_NO_MEMORY;
-
-       return NT_STATUS_OK;
-}
 
 /*******************************************************************
- samr_make_ali_obj_sd
- ********************************************************************/
-
-static NTSTATUS samr_make_ali_obj_sd(TALLOC_CTX *ctx, SEC_DESC **psd, size_t *sd_size)
-{
-       extern DOM_SID global_sid_World;
-       DOM_SID adm_sid;
-       DOM_SID act_sid;
-
-       SEC_ACE ace[3];
-       SEC_ACCESS mask;
-
-       SEC_ACL *psa = NULL;
-
-       sid_copy(&adm_sid, &global_sid_Builtin);
-       sid_append_rid(&adm_sid, BUILTIN_ALIAS_RID_ADMINS);
-
-       sid_copy(&act_sid, &global_sid_Builtin);
-       sid_append_rid(&act_sid, BUILTIN_ALIAS_RID_ACCOUNT_OPS);
-
-       /*basic access for every one*/
-       init_sec_access(&mask, GENERIC_RIGHTS_ALIAS_EXECUTE | GENERIC_RIGHTS_ALIAS_READ);
-       init_sec_ace(&ace[0], &global_sid_World, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       /*full access for builtin aliases Administrators and Account Operators*/
-       init_sec_access(&mask, GENERIC_RIGHTS_ALIAS_ALL_ACCESS);
-       init_sec_ace(&ace[1], &adm_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-       init_sec_ace(&ace[2], &act_sid, SEC_ACE_TYPE_ACCESS_ALLOWED, mask, 0);
-
-       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, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, sd_size)) == NULL)
-               return NT_STATUS_NO_MEMORY;
-
-       return NT_STATUS_OK;
-}
+********************************************************************/
 
-static BOOL get_lsa_policy_samr_sid(pipes_struct *p, POLICY_HND *pol, DOM_SID *sid, uint32 *acc_granted)
+static BOOL get_lsa_policy_samr_sid( pipes_struct *p, POLICY_HND *pol, 
+                                     DOM_SID *sid, uint32 *acc_granted)
 {
        struct samr_info *info = NULL;
 
@@ -613,17 +594,6 @@ static BOOL get_lsa_policy_samr_sid(pipes_struct *p, POLICY_HND *pol, DOM_SID *s
        return True;
 }
 
-/*******************************************************************
- _samr_set_sec_obj
- ********************************************************************/
-
-NTSTATUS _samr_set_sec_obj(pipes_struct *p, SAMR_Q_SET_SEC_OBJ *q_u, SAMR_R_SET_SEC_OBJ *r_u)
-{
-       DEBUG(0,("_samr_set_sec_obj: Not yet implemented!\n"));
-       return NT_STATUS_NOT_IMPLEMENTED;
-}
-
-
 /*******************************************************************
  _samr_query_sec_obj
  ********************************************************************/
@@ -633,8 +603,8 @@ NTSTATUS _samr_query_sec_obj(pipes_struct *p, SAMR_Q_QUERY_SEC_OBJ *q_u, SAMR_R_
        DOM_SID pol_sid;
        fstring str_sid;
        SEC_DESC * psd = NULL;
-       size_t sd_size;
        uint32 acc_granted;
+       size_t sd_size;
 
        r_u->status = NT_STATUS_OK;
 
@@ -652,19 +622,19 @@ NTSTATUS _samr_query_sec_obj(pipes_struct *p, SAMR_Q_QUERY_SEC_OBJ *q_u, SAMR_R_
        if (pol_sid.sid_rev_num == 0)
        {
                DEBUG(5,("_samr_query_sec_obj: querying security on SAM\n"));
-               r_u->status = samr_make_sam_obj_sd(p->mem_ctx, &psd, &sd_size);
+               r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
        }
        else if (sid_equal(&pol_sid,get_global_sam_sid()))  /* check if it is our domain SID */
 
        {
                DEBUG(5,("_samr_query_sec_obj: querying security on Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
-               r_u->status = samr_make_dom_obj_sd(p->mem_ctx, &psd, &sd_size);
+               r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
        }
        else if (sid_equal(&pol_sid,&global_sid_Builtin)) /* check if it is the Builtin  Domain */
        {
                /* TODO: Builtin probably needs a different SD with restricted write access*/
                DEBUG(5,("_samr_query_sec_obj: querying security on Builtin Domain with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
-               r_u->status = samr_make_dom_obj_sd(p->mem_ctx, &psd, &sd_size);
+               r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &dom_generic_mapping, NULL, 0);
        }
        else if (sid_check_is_in_our_domain(&pol_sid) ||
                 sid_check_is_in_builtin(&pol_sid))
@@ -672,7 +642,7 @@ NTSTATUS _samr_query_sec_obj(pipes_struct *p, SAMR_Q_QUERY_SEC_OBJ *q_u, SAMR_R_
                /* TODO: different SDs have to be generated for aliases groups and users.
                         Currently all three get a default user SD  */
                DEBUG(10,("_samr_query_sec_obj: querying security on Object with SID: %s\n", sid_to_string(str_sid, &pol_sid)));
-               r_u->status = samr_make_usr_obj_sd(p->mem_ctx, &psd,&sd_size, &pol_sid);
+               r_u->status = make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, &pol_sid, SAMR_USR_RIGHTS_WRITE_PW);
        }
        else return NT_STATUS_OBJECT_TYPE_MISMATCH;
 
@@ -710,9 +680,9 @@ static NTSTATUS make_user_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UN
        if (num_entries == 0)
                return NT_STATUS_OK;
 
-       sam = (SAM_ENTRY *)talloc_zero(ctx, sizeof(SAM_ENTRY)*num_entries);
+       sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_entries);
 
-       uni_name = (UNISTR2 *)talloc_zero(ctx, sizeof(UNISTR2)*num_entries);
+       uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_entries);
 
        if (sam == NULL || uni_name == NULL) {
                DEBUG(0, ("make_user_sam_entry_list: talloc_zero failed!\n"));
@@ -722,7 +692,17 @@ 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];
                temp_name = pdb_get_username(pwd);
-               init_unistr2(&uni_temp_name, temp_name, UNI_STR_TERMINATE);
+
+               /*
+                * usrmgr expects a non-NULL terminated string with
+                * trust relationships
+                */
+               if (pdb_get_acct_ctrl(pwd) & ACB_DOMTRUST) {
+                       init_unistr2(&uni_temp_name, temp_name, UNI_FLAGS_NONE);
+               } else {
+                       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)) {
@@ -855,9 +835,8 @@ static void make_group_sam_entry_list(TALLOC_CTX *ctx, SAM_ENTRY **sam_pp, UNIST
        if (num_sam_entries == 0)
                return;
 
-       sam = (SAM_ENTRY *)talloc_zero(ctx, sizeof(SAM_ENTRY)*num_sam_entries);
-
-       uni_name = (UNISTR2 *)talloc_zero(ctx, sizeof(UNISTR2)*num_sam_entries);
+       sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
+       uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
 
        if (sam == NULL || uni_name == NULL) {
                DEBUG(0, ("NULL pointers in SAMR_R_QUERY_DISPINFO\n"));
@@ -880,7 +859,7 @@ 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_entries( enum SID_NAME_USE type, TALLOC_CTX *ctx, 
+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 )
 {
@@ -895,7 +874,8 @@ static NTSTATUS get_group_entries( enum SID_NAME_USE type, TALLOC_CTX *ctx,
           needed for some passdb backends to enumerate groups */
           
        become_root();
-       pdb_enum_group_mapping(type, &map, (int *)&group_entries, ENUM_ONLY_MAPPED);
+       pdb_enum_group_mapping(SID_NAME_DOM_GRP, &map, (int *)&group_entries,
+                              ENUM_ONLY_MAPPED);
        unbecome_root();
        
        num_entries=group_entries-start_idx;
@@ -906,7 +886,7 @@ static NTSTATUS get_group_entries( enum SID_NAME_USE type, TALLOC_CTX *ctx,
                num_entries=max_entries;
        }
 
-       *d_grp=(DOMAIN_GRP *)talloc_zero(ctx, num_entries*sizeof(DOMAIN_GRP));
+       *d_grp=TALLOC_ZERO_ARRAY(ctx, DOMAIN_GRP, num_entries);
        if (num_entries!=0 && *d_grp==NULL){
                SAFE_FREE(map);
                return NT_STATUS_NO_MEMORY;
@@ -916,51 +896,57 @@ static NTSTATUS get_group_entries( enum SID_NAME_USE type, TALLOC_CTX *ctx,
                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=type;
+               (*d_grp)[i].attr=SID_NAME_DOM_GRP;
        }
 
        SAFE_FREE(map);
 
        *p_num_entries = num_entries;
 
-       DEBUG(10,("get_group_entries: returning %d entries\n", *p_num_entries));
+       DEBUG(10,("get_group_domain_entries: returning %d entries\n",
+                 *p_num_entries));
 
        return NT_STATUS_OK;
 }
 
 /*******************************************************************
- Wrapper for enuemrating domain groups
+ Wrapper for enumerating local 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 )
+static NTSTATUS get_alias_entries( TALLOC_CTX *ctx, DOMAIN_GRP **d_grp,
+                                  const 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 );
-}
+       struct acct_info *info;
+       int i;
+       BOOL res;
 
-/*******************************************************************
- Wrapper for enumerating local groups
- ******************************************************************/
+       become_root();
+       res = pdb_enum_aliases(sid, start_idx, max_entries,
+                              p_num_entries, &info);
+       unbecome_root();
 
-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 );   
+       if (!res)
+               return NT_STATUS_ACCESS_DENIED;
+
+       if (*p_num_entries == 0)
+               return NT_STATUS_OK;
+
+       *d_grp = TALLOC_ARRAY(ctx, DOMAIN_GRP, *p_num_entries);
+
+       if (*d_grp == NULL) {
+               SAFE_FREE(info);
+               return NT_STATUS_NO_MEMORY;
        }
 
-       /* can't do anything with this SID */
-               
-       *p_num_entries = 0;
+       for (i=0; i<*p_num_entries; i++) {
+               fstrcpy((*d_grp)[i].name, info[i].acct_name);
+               fstrcpy((*d_grp)[i].comment, info[i].acct_desc);
+               (*d_grp)[i].rid = info[i].rid;
+               (*d_grp)[i].attr = SID_NAME_ALIAS;
+       }
 
+       SAFE_FREE(info);
        return NT_STATUS_OK;
 }
 
@@ -1026,9 +1012,9 @@ NTSTATUS _samr_enum_dom_aliases(pipes_struct *p, SAMR_Q_ENUM_DOM_ALIASES *q_u, S
        sid_to_string(sid_str, &sid);
        DEBUG(5,("samr_reply_enum_dom_aliases: sid %s\n", sid_str));
 
-       status = get_group_alias_entries(p->mem_ctx, &grp, &sid, q_u->start_idx, 
-                                        &num_entries, MAX_SAM_ENTRIES);
-       if (NT_STATUS_IS_ERR(status)) return status;
+       status = get_alias_entries(p->mem_ctx, &grp, &sid, q_u->start_idx, 
+                                  &num_entries, MAX_SAM_ENTRIES);
+       if (!NT_STATUS_IS_OK(status)) return status;
 
        make_group_sam_entry_list(p->mem_ctx, &r_u->sam, &r_u->uni_grp_name, num_entries, grp);
 
@@ -1164,7 +1150,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
                DEBUG(5, ("samr_reply_query_dispinfo: buffer size limits to only %d entries\n", max_entries));
        }
 
-       if (!(ctr = (SAM_DISPINFO_CTR *)talloc_zero(p->mem_ctx,sizeof(SAM_DISPINFO_CTR))))
+       if (!(ctr = TALLOC_ZERO_P(p->mem_ctx,SAM_DISPINFO_CTR)))
                return NT_STATUS_NO_MEMORY;
 
        ZERO_STRUCTP(ctr);
@@ -1173,7 +1159,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
        switch (q_u->switch_level) {
        case 0x1:
                if (max_entries) {
-                       if (!(ctr->sam.info1 = (SAM_DISPINFO_1 *)talloc_zero(p->mem_ctx,max_entries*sizeof(SAM_DISPINFO_1))))
+                       if (!(ctr->sam.info1 = TALLOC_ZERO_ARRAY(p->mem_ctx,SAM_DISPINFO_1,max_entries)))
                                return NT_STATUS_NO_MEMORY;
                }
                disp_ret = init_sam_dispinfo_1(p->mem_ctx, ctr->sam.info1, max_entries, enum_context, 
@@ -1183,7 +1169,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
                break;
        case 0x2:
                if (max_entries) {
-                       if (!(ctr->sam.info2 = (SAM_DISPINFO_2 *)talloc_zero(p->mem_ctx,max_entries*sizeof(SAM_DISPINFO_2))))
+                       if (!(ctr->sam.info2 = TALLOC_ZERO_ARRAY(p->mem_ctx,SAM_DISPINFO_2,max_entries)))
                                return NT_STATUS_NO_MEMORY;
                }
                disp_ret = init_sam_dispinfo_2(p->mem_ctx, ctr->sam.info2, max_entries, enum_context, 
@@ -1193,7 +1179,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
                break;
        case 0x3:
                if (max_entries) {
-                       if (!(ctr->sam.info3 = (SAM_DISPINFO_3 *)talloc_zero(p->mem_ctx,max_entries*sizeof(SAM_DISPINFO_3))))
+                       if (!(ctr->sam.info3 = TALLOC_ZERO_ARRAY(p->mem_ctx,SAM_DISPINFO_3,max_entries)))
                                return NT_STATUS_NO_MEMORY;
                }
                disp_ret = init_sam_dispinfo_3(p->mem_ctx, ctr->sam.info3, max_entries, enum_context, info->disp_info.disp_group_info);
@@ -1202,7 +1188,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
                break;
        case 0x4:
                if (max_entries) {
-                       if (!(ctr->sam.info4 = (SAM_DISPINFO_4 *)talloc_zero(p->mem_ctx,max_entries*sizeof(SAM_DISPINFO_4))))
+                       if (!(ctr->sam.info4 = TALLOC_ZERO_ARRAY(p->mem_ctx,SAM_DISPINFO_4,max_entries)))
                                return NT_STATUS_NO_MEMORY;
                }
                disp_ret = init_sam_dispinfo_4(p->mem_ctx, ctr->sam.info4, max_entries, enum_context, info->disp_info.disp_user_info);
@@ -1211,7 +1197,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
                break;
        case 0x5:
                if (max_entries) {
-                       if (!(ctr->sam.info5 = (SAM_DISPINFO_5 *)talloc_zero(p->mem_ctx,max_entries*sizeof(SAM_DISPINFO_5))))
+                       if (!(ctr->sam.info5 = TALLOC_ZERO_ARRAY(p->mem_ctx,SAM_DISPINFO_5,max_entries)))
                                return NT_STATUS_NO_MEMORY;
                }
                disp_ret = init_sam_dispinfo_5(p->mem_ctx, ctr->sam.info5, max_entries, enum_context, info->disp_info.disp_group_info);
@@ -1245,7 +1231,7 @@ NTSTATUS _samr_query_dispinfo(pipes_struct *p, SAMR_Q_QUERY_DISPINFO *q_u,
 NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAMR_R_QUERY_ALIASINFO *r_u)
 {
        DOM_SID   sid;
-       GROUP_MAP map;
+       struct acct_info info;
        uint32    acc_granted;
        BOOL ret;
 
@@ -1260,12 +1246,8 @@ NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAM
                return r_u->status;
        }
 
-       if (!sid_check_is_in_our_domain(&sid) &&
-           !sid_check_is_in_builtin(&sid))
-               return NT_STATUS_OBJECT_TYPE_MISMATCH;
-
        become_root();
-       ret = pdb_getgrsid(&map, sid);
+       ret = pdb_get_aliasinfo(&sid, &info);
        unbecome_root();
        
        if ( !ret )
@@ -1275,12 +1257,13 @@ NTSTATUS _samr_query_aliasinfo(pipes_struct *p, SAMR_Q_QUERY_ALIASINFO *q_u, SAM
        case 1:
                r_u->ptr = 1;
                r_u->ctr.switch_value1 = 1;
-               init_samr_alias_info1(&r_u->ctr.alias.info1, map.nt_name, 1, map.comment);
+               init_samr_alias_info1(&r_u->ctr.alias.info1,
+                                     info.acct_name, 1, info.acct_desc);
                break;
        case 3:
                r_u->ptr = 1;
                r_u->ctr.switch_value1 = 3;
-               init_samr_alias_info3(&r_u->ctr.alias.info3, map.comment);
+               init_samr_alias_info3(&r_u->ctr.alias.info3, info.acct_desc);
                break;
        default:
                return NT_STATUS_INVALID_INFO_CLASS;
@@ -1492,11 +1475,11 @@ static BOOL make_samr_lookup_rids(TALLOC_CTX *ctx, uint32 num_names, fstring nam
        *pp_hdr_name = NULL;
 
        if (num_names != 0) {
-               hdr_name = (UNIHDR *)talloc_zero(ctx, sizeof(UNIHDR)*num_names);
+               hdr_name = TALLOC_ZERO_ARRAY(ctx, UNIHDR, num_names);
                if (hdr_name == NULL)
                        return False;
 
-               uni_name = (UNISTR2 *)talloc_zero(ctx,sizeof(UNISTR2)*num_names);
+               uni_name = TALLOC_ZERO_ARRAY(ctx,UNISTR2, num_names);
                if (uni_name == NULL)
                        return False;
        }
@@ -1542,7 +1525,7 @@ NTSTATUS _samr_lookup_rids(pipes_struct *p, SAMR_Q_LOOKUP_RIDS *q_u, SAMR_R_LOOK
        }
 
        if (num_rids) {
-               if ((group_attrs = (uint32 *)talloc_zero(p->mem_ctx, num_rids * sizeof(uint32))) == NULL)
+               if ((group_attrs = TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num_rids )) == NULL)
                        return NT_STATUS_NO_MEMORY;
        }
  
@@ -1601,34 +1584,45 @@ NTSTATUS _samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USE
        size_t    sd_size;
        BOOL ret;
        NTSTATUS nt_status;
+       SE_PRIV se_rights;
 
        r_u->status = NT_STATUS_OK;
 
        /* find the domain policy handle and get domain SID / access bits in the domain policy. */
-       if (!get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted))
+       
+       if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted) )
                return NT_STATUS_INVALID_HANDLE;
        
-       if (!NT_STATUS_IS_OK(nt_status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_user"))) {
+       nt_status = access_check_samr_function( acc_granted, 
+               SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_user" );
+               
+       if ( !NT_STATUS_IS_OK(nt_status) )
                return nt_status;
-       }
 
        nt_status = pdb_init_sam_talloc(p->mem_ctx, &sampass);
-       if (!NT_STATUS_IS_OK(nt_status)) {
+       
+       if (!NT_STATUS_IS_OK(nt_status))
                return nt_status;
-       }
 
        /* append the user's RID to it */
+       
        if (!sid_append_rid(&sid, q_u->user_rid))
                return NT_STATUS_NO_SUCH_USER;
        
        /* check if access can be granted as requested by client. */
-       samr_make_usr_obj_sd(p->mem_ctx, &psd, &sd_size, &sid);
+       
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, &sid, SAMR_USR_RIGHTS_WRITE_PW);
        se_map_generic(&des_access, &usr_generic_mapping);
-       if (!NT_STATUS_IS_OK(nt_status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_open_user"))) {
+       
+       se_priv_copy( &se_rights, &se_machine_account );
+       se_priv_add( &se_rights, &se_add_users );
+       
+       nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
+               &acc_granted, "_samr_open_user");
+               
+       if ( !NT_STATUS_IS_OK(nt_status) )
                return nt_status;
-       }
 
        become_root();
        ret=pdb_getsampwsid(sampass, &sid);
@@ -1654,10 +1648,10 @@ NTSTATUS _samr_open_user(pipes_struct *p, SAMR_Q_OPEN_USER *q_u, SAMR_R_OPEN_USE
 }
 
 /*************************************************************************
- get_user_info_10. Safe. Only gives out acb bits.
+ get_user_info_7. Safe. Only gives out account_name.
  *************************************************************************/
 
-static NTSTATUS get_user_info_10(TALLOC_CTX *mem_ctx, SAM_USER_INFO_10 *id10, DOM_SID *user_sid)
+static NTSTATUS get_user_info_7(TALLOC_CTX *mem_ctx, SAM_USER_INFO_7 *id7, DOM_SID *user_sid)
 {
        SAM_ACCOUNT *smbpass=NULL;
        BOOL ret;
@@ -1680,30 +1674,64 @@ static NTSTATUS get_user_info_10(TALLOC_CTX *mem_ctx, SAM_USER_INFO_10 *id10, DO
 
        DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
 
-       ZERO_STRUCTP(id10);
-       init_sam_user_info10(id10, pdb_get_acct_ctrl(smbpass) );
+       ZERO_STRUCTP(id7);
+       init_sam_user_info7(id7, pdb_get_username(smbpass) );
 
        pdb_free_sam(&smbpass);
 
        return NT_STATUS_OK;
 }
-
 /*************************************************************************
- get_user_info_12. OK - this is the killer as it gives out password info.
- Ensure that this is only allowed on an encrypted connection with a root
- user. JRA. 
+ get_user_info_10. Safe. Only gives out acb bits.
  *************************************************************************/
 
-static NTSTATUS get_user_info_12(pipes_struct *p, TALLOC_CTX *mem_ctx, SAM_USER_INFO_12 * id12, DOM_SID *user_sid)
+static NTSTATUS get_user_info_10(TALLOC_CTX *mem_ctx, SAM_USER_INFO_10 *id10, DOM_SID *user_sid)
 {
        SAM_ACCOUNT *smbpass=NULL;
        BOOL ret;
        NTSTATUS nt_status;
 
-       if (!p->ntlmssp_auth_validated)
-               return NT_STATUS_ACCESS_DENIED;
-
-       if (!(p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SIGN) || !(p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SEAL))
+       nt_status = pdb_init_sam_talloc(mem_ctx, &smbpass);
+       
+       if (!NT_STATUS_IS_OK(nt_status)) {
+               return nt_status;
+       }
+
+       become_root();
+       ret = pdb_getsampwsid(smbpass, user_sid);
+       unbecome_root();
+
+       if (ret==False) {
+               DEBUG(4,("User %s not found\n", sid_string_static(user_sid)));
+               return NT_STATUS_NO_SUCH_USER;
+       }
+
+       DEBUG(3,("User:[%s]\n", pdb_get_username(smbpass) ));
+
+       ZERO_STRUCTP(id10);
+       init_sam_user_info10(id10, pdb_get_acct_ctrl(smbpass) );
+
+       pdb_free_sam(&smbpass);
+
+       return NT_STATUS_OK;
+}
+
+/*************************************************************************
+ get_user_info_12. OK - this is the killer as it gives out password info.
+ Ensure that this is only allowed on an encrypted connection with a root
+ user. JRA. 
+ *************************************************************************/
+
+static NTSTATUS get_user_info_12(pipes_struct *p, TALLOC_CTX *mem_ctx, SAM_USER_INFO_12 * id12, DOM_SID *user_sid)
+{
+       SAM_ACCOUNT *smbpass=NULL;
+       BOOL ret;
+       NTSTATUS nt_status;
+
+       if (!p->ntlmssp_auth_validated)
+               return NT_STATUS_ACCESS_DENIED;
+
+       if (!(p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SIGN) || !(p->ntlmssp_chal_flags & NTLMSSP_NEGOTIATE_SEAL))
                return NT_STATUS_ACCESS_DENIED;
 
        /*
@@ -1834,7 +1862,7 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
 
        DEBUG(5,("_samr_query_userinfo: sid:%s\n", sid_string_static(&info->sid)));
 
-       ctr = (SAM_USERINFO_CTR *)talloc_zero(p->mem_ctx, sizeof(SAM_USERINFO_CTR));
+       ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_USERINFO_CTR);
        if (!ctr)
                return NT_STATUS_NO_MEMORY;
 
@@ -1844,8 +1872,16 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
        ctr->switch_value = q_u->switch_value;
 
        switch (q_u->switch_value) {
+       case 0x07:
+               ctr->info.id7 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_7);
+               if (ctr->info.id7 == NULL)
+                       return NT_STATUS_NO_MEMORY;
+
+               if (!NT_STATUS_IS_OK(r_u->status = get_user_info_7(p->mem_ctx, ctr->info.id7, &info->sid)))
+                       return r_u->status;
+               break;
        case 0x10:
-               ctr->info.id10 = (SAM_USER_INFO_10 *)talloc_zero(p->mem_ctx, sizeof(SAM_USER_INFO_10));
+               ctr->info.id10 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_10);
                if (ctr->info.id10 == NULL)
                        return NT_STATUS_NO_MEMORY;
 
@@ -1863,11 +1899,7 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
             expire.low = 0xffffffff;
             expire.high = 0x7fffffff;
 
-            ctr->info.id = (SAM_USER_INFO_11 *)talloc_zero(p->mem_ctx,
-                                    sizeof
-                                    (*ctr->
-                                     info.
-                                     id11));
+            ctr->info.id = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_11));
            ZERO_STRUCTP(ctr->info.id11);
             init_sam_user_info11(ctr->info.id11, &expire,
                          "BROOKFIELDS$",    /* name */
@@ -1880,7 +1912,7 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
 #endif
 
        case 0x12:
-               ctr->info.id12 = (SAM_USER_INFO_12 *)talloc_zero(p->mem_ctx, sizeof(SAM_USER_INFO_12));
+               ctr->info.id12 = TALLOC_ZERO_P(p->mem_ctx, SAM_USER_INFO_12);
                if (ctr->info.id12 == NULL)
                        return NT_STATUS_NO_MEMORY;
 
@@ -1889,7 +1921,7 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
                break;
                
        case 20:
-               ctr->info.id20 = (SAM_USER_INFO_20 *)talloc_zero(p->mem_ctx,sizeof(SAM_USER_INFO_20));
+               ctr->info.id20 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_20);
                if (ctr->info.id20 == NULL)
                        return NT_STATUS_NO_MEMORY;
                if (!NT_STATUS_IS_OK(r_u->status = get_user_info_20(p->mem_ctx, ctr->info.id20, &info->sid)))
@@ -1897,7 +1929,7 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
                break;
 
        case 21:
-               ctr->info.id21 = (SAM_USER_INFO_21 *)talloc_zero(p->mem_ctx,sizeof(SAM_USER_INFO_21));
+               ctr->info.id21 = TALLOC_ZERO_P(p->mem_ctx,SAM_USER_INFO_21);
                if (ctr->info.id21 == NULL)
                        return NT_STATUS_NO_MEMORY;
                if (!NT_STATUS_IS_OK(r_u->status = get_user_info_21(p->mem_ctx, ctr->info.id21, 
@@ -1923,11 +1955,16 @@ NTSTATUS _samr_query_userinfo(pipes_struct *p, SAMR_Q_QUERY_USERINFO *q_u, SAMR_
 NTSTATUS _samr_query_usergroups(pipes_struct *p, SAMR_Q_QUERY_USERGROUPS *q_u, SAMR_R_QUERY_USERGROUPS *r_u)
 {
        SAM_ACCOUNT *sam_pass=NULL;
+       struct passwd *passwd;
        DOM_SID  sid;
+       DOM_SID *sids;
        DOM_GID *gids = NULL;
        int num_groups = 0;
+       gid_t *unix_gids;
+       int i, num_gids, num_sids;
        uint32 acc_granted;
        BOOL ret;
+       NTSTATUS result;
 
        /*
         * from the SID in the request:
@@ -1966,19 +2003,52 @@ NTSTATUS _samr_query_usergroups(pipes_struct *p, SAMR_Q_QUERY_USERGROUPS *q_u, S
                pdb_free_sam(&sam_pass);
                return NT_STATUS_NO_SUCH_USER;
        }
-       
-       if(!get_domain_user_groups(p->mem_ctx, &num_groups, &gids, sam_pass)) {
+
+       passwd = getpwnam_alloc(pdb_get_username(sam_pass));
+       if (passwd == NULL) {
                pdb_free_sam(&sam_pass);
-               return NT_STATUS_NO_SUCH_GROUP;
+               return NT_STATUS_NO_SUCH_USER;
+       }
+
+       sids = NULL;
+       num_sids = 0;
+
+       become_root();
+       result = pdb_enum_group_memberships(pdb_get_username(sam_pass),
+                                           passwd->pw_gid,
+                                           &sids, &unix_gids, &num_groups);
+       unbecome_root();
+
+       pdb_free_sam(&sam_pass);
+       passwd_free(&passwd);
+
+       if (!NT_STATUS_IS_OK(result))
+               return result;
+
+       SAFE_FREE(unix_gids);
+
+       gids = NULL;
+       num_gids = 0;
+
+       for (i=0; i<num_groups; i++) {
+               uint32 rid;
+
+               if (!sid_peek_check_rid(get_global_sam_sid(),
+                                       &(sids[i]), &rid))
+                       continue;
+
+               gids = TALLOC_REALLOC_ARRAY(p->mem_ctx, gids, DOM_GID, num_gids+1);
+               gids[num_gids].attr=7;
+               gids[num_gids].g_rid = rid;
+               num_gids += 1;
        }
+       SAFE_FREE(sids);
        
        /* construct the response.  lkclXXXX: gids are not copied! */
        init_samr_r_query_usergroups(r_u, num_groups, gids, r_u->status);
        
        DEBUG(5,("_samr_query_usergroups: %d\n", __LINE__));
        
-       pdb_free_sam(&sam_pass);
-       
        return r_u->status;
 }
 
@@ -2005,7 +2075,7 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
 
        uint32 num_users=0, num_groups=0, num_aliases=0;
 
-       if ((ctr = (SAM_UNK_CTR *)talloc_zero(p->mem_ctx, sizeof(SAM_UNK_CTR))) == NULL)
+       if ((ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_CTR)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        ZERO_STRUCTP(ctr);
@@ -2021,19 +2091,19 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
        switch (q_u->switch_value) {
                case 0x01:
                        
-                       account_policy_get(AP_MIN_PASSWORD_LEN, &account_policy_temp);
+                       pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
                        min_pass_len = account_policy_temp;
 
-                       account_policy_get(AP_PASSWORD_HISTORY, &account_policy_temp);
+                       pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
                        pass_hist = account_policy_temp;
 
-                       account_policy_get(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
+                       pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
                        flag = account_policy_temp;
 
-                       account_policy_get(AP_MAX_PASSWORD_AGE, &account_policy_temp);
+                       pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
                        u_expire = account_policy_temp;
 
-                       account_policy_get(AP_MIN_PASSWORD_AGE, &account_policy_temp);
+                       pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
                        u_min_age = account_policy_temp;
                        
                        unix_to_nt_time_abs(&nt_expire, u_expire);
@@ -2060,13 +2130,18 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
                        }
                        num_groups=info->disp_info.num_group_account;
                        free_samr_db(info);
-                       
+
+                       pdb_get_account_policy(AP_TIME_TO_LOGOUT, &account_policy_temp);
+                       u_logout = account_policy_temp;
+
+                       unix_to_nt_time_abs(&nt_logout, u_logout);
+
                        /* The time call below is to get a sequence number for the sam. FIXME !!! JRA. */
-                       init_unk_info2(&ctr->info.inf2, lp_workgroup(), global_myname(), (uint32) time(NULL), 
-                                      num_users, num_groups, num_aliases);
+                       init_unk_info2(&ctr->info.inf2, "", lp_workgroup(), global_myname(), (uint32) time(NULL), 
+                                      num_users, num_groups, num_aliases, nt_logout);
                        break;
                case 0x03:
-                       account_policy_get(AP_TIME_TO_LOGOUT, (unsigned int *)&u_logout);
+                       pdb_get_account_policy(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);
@@ -2080,14 +2155,19 @@ NTSTATUS _samr_query_dom_info(pipes_struct *p, SAMR_Q_QUERY_DOMAIN_INFO *q_u, SA
                case 0x07:
                        init_unk_info7(&ctr->info.inf7);
                        break;
+               case 0x08:
+                       init_unk_info8(&ctr->info.inf8, (uint32) time(NULL));
+                       break;
                case 0x0c:
-                       account_policy_get(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
-                       u_lock_duration = account_policy_temp * 60;
+                       pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
+                       u_lock_duration = account_policy_temp;
+                       if (u_lock_duration != -1)
+                               u_lock_duration *= 60;
 
-                       account_policy_get(AP_RESET_COUNT_TIME, &account_policy_temp);
+                       pdb_get_account_policy(AP_RESET_COUNT_TIME, &account_policy_temp);
                        u_reset_time = account_policy_temp * 60;
 
-                       account_policy_get(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
+                       pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
                        lockout = account_policy_temp;
 
                        unix_to_nt_time_abs(&nt_lock_duration, u_lock_duration);
@@ -2132,21 +2212,15 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
        uint32 new_rid = 0;
        /* check this, when giving away 'add computer to domain' privs */
        uint32    des_access = GENERIC_RIGHTS_USER_ALL_ACCESS;
+       BOOL can_add_account;
+       SE_PRIV se_rights;
 
        /* Get the domain SID stored in the domain policy */
        if (!get_lsa_policy_samr_sid(p, &dom_pol, &sid, &acc_granted))
                return NT_STATUS_INVALID_HANDLE;
 
        if (!NT_STATUS_IS_OK(nt_status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_CREATE_USER, "_samr_create_user"))) {
-               if (NT_STATUS_IS_OK(user_has_privilege(&(p->pipe_user), SE_MACHINE_ACCOUNT))) {
-                       DEBUG(3, ("_samr_create_user: User should be denied access but was overridden by %s\n", privs[SE_MACHINE_ACCOUNT].priv));
-               } else {
-                       if (NT_STATUS_IS_OK(user_has_privilege(&(p->pipe_user), SE_ADD_USERS))) {
-                               DEBUG(3, ("_samr_create_user: User should be denied access but was overridden by %s\n", privs[SE_ADD_USERS].priv));
-                       } else {
-                               return nt_status;
-                       }
-               }
+               return nt_status;
        }
 
        if (!(acb_info == ACB_NORMAL || acb_info == ACB_DOMTRUST || acb_info == ACB_WSTRUST || acb_info == ACB_SVRTRUST)) { 
@@ -2155,15 +2229,9 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
                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
-         reply if the account already exists...
-        */
-
        rpcstr_pull(account, user_account.buffer, sizeof(account), user_account.uni_str_len*2, 0);
        strlower_m(account);
-
+               
        pdb_init_sam(&sam_pass);
 
        become_root();
@@ -2176,68 +2244,6 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
        }
 
        pdb_free_sam(&sam_pass);
-
-       /*
-        * NB. VERY IMPORTANT ! This call must be done as the current pipe user,
-        * *NOT* surrounded by a become_root()/unbecome_root() call. This ensures
-        * that only people with write access to the smbpasswd file will be able
-        * to create a user. JRA.
-        */
-
-       /*
-        * add the user in the /etc/passwd file or the unix authority system.
-        * We don't check if the smb_create_user() function succed or not for 2 reasons:
-        * a) local_password_change() checks for us if the /etc/passwd account really exists
-        * b) smb_create_user() would return an error if the account already exists
-        * and as it could return an error also if it can't create the account, it would be tricky.
-        *
-        * So we go the easy way, only check after if the account exists.
-        * JFM (2/3/2001), to clear any possible bad understanding (-:
-        *
-        * We now have seperate script paramaters for adding users/machines so we
-        * now have some sainity-checking to match. 
-        */
-
-       DEBUG(10,("checking account %s at pos %lu for $ termination\n",account, (unsigned long)strlen(account)-1));
-       
-       /* 
-        * 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
-        */
-
-       /* the passdb lookup has failed; check to see if we need to run the
-          add user/machine script */
-               
-       /* 
-        * 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] == '$') {
-               if (NT_STATUS_IS_OK(user_has_privilege(&(p->pipe_user), SE_MACHINE_ACCOUNT)) || geteuid() == 0) {
-                       DEBUG(3, ("user [%s] has been granted Add Machines privilege!\n", p->user_name));
-                       become_root();
-                       pstrcpy(add_script, lp_addmachine_script());
-               } else {
-                       DEBUG(3, ("user [%s] doesn't have Add Machines privilege!\n", p->user_name));
-                       return NT_STATUS_ACCESS_DENIED;
-               }
-       } else {
-               if (NT_STATUS_IS_OK(user_has_privilege(&(p->pipe_user), SE_ADD_USERS)) || geteuid() == 0) {
-                       DEBUG(3, ("user [%s] has been granted Add Users privilege!\n", p->user_name));
-                       become_root();
-                       pstrcpy(add_script, lp_adduser_script());
-               } else {
-                       DEBUG(3, ("user [%s] doesn't have Add Users privilege!\n", p->user_name));
-                       return NT_STATUS_ACCESS_DENIED;
-               }
-       }
-          
-       pw = Get_Pwnam(account);
        
        /*********************************************************************
         * HEADS UP!  If we have to create a new user account, we have to get 
@@ -2250,17 +2256,49 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
         *                                             --jerry (2003-07-10)
         *********************************************************************/
        
-       if ( !pw ) {
+       pw = Get_Pwnam(account);
 
+       /* determine which user right we need to check based on the acb_info */
+       
+       if ( (acb_info & ACB_WSTRUST) == ACB_WSTRUST ) 
+       {
+               pstrcpy(add_script, lp_addmachine_script());
+               se_priv_copy( &se_rights, &se_machine_account );
+               can_add_account = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+       } 
+       else if ( (acb_info & ACB_WSTRUST) == ACB_NORMAL ) 
+       {
+               pstrcpy(add_script, lp_adduser_script());
+               se_priv_copy( &se_rights, &se_add_users );
+               can_add_account = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+       } 
+       else if ( ((acb_info & ACB_SVRTRUST) == ACB_SVRTRUST) ||  ((acb_info & ACB_DOMTRUST) == ACB_DOMTRUST) ) 
+       {
+               pstrcpy(add_script, lp_addmachine_script());
+               /* only Domain Admins can add a BDC or domain trust */
+               se_priv_copy( &se_rights, &se_priv_none );
+               can_add_account = nt_token_check_domain_rid( p->pipe_user.nt_user_token, DOMAIN_GROUP_RID_ADMINS );
+       }
+       
+       DEBUG(5, ("_samr_create_user: %s can add this account : %s\n",
+               p->pipe_user_name, can_add_account ? "True":"False" ));
+               
+       /********** BEGIN Admin BLOCK **********/
+       
+       if ( can_add_account )
+               become_root();
+                               
+       if ( !pw ) {
                if (*add_script) {
                        int add_ret;
-                       all_string_sub(add_script, "%u", account, sizeof(account));
+                       
+                       all_string_sub(add_script, "%u", account, sizeof(add_script));
                        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)) {
+                       if ( !winbind_create_user( account, &new_rid ) ) {
                                DEBUG(3,("_samr_create_user: winbind_create_user(%s) failed\n", 
                                        account));
                        }
@@ -2270,35 +2308,51 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
        
        /* 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)) )
-               goto done;
+       nt_status = pdb_init_sam_new(&sam_pass, account, new_rid);
+
+       /* this code is order such that we have no unnecessary retuns 
+          out of the admin block of code */    
+          
+       if ( NT_STATUS_IS_OK(nt_status) ) {
+               pdb_set_acct_ctrl(sam_pass, acb_info, PDB_CHANGED);
+       
+               if ( !(ret = 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));
+                       nt_status = NT_STATUS_ACCESS_DENIED;
+               }
+       }
                
-       pdb_set_acct_ctrl(sam_pass, acb_info, PDB_CHANGED);
+       if ( can_add_account )
+               unbecome_root();
+
+       /********** END Admin BLOCK **********/
        
-       if (!pdb_add_sam_account(sam_pass)) {
-               pdb_free_sam(&sam_pass);
-               DEBUG(0, ("could not add user/computer %s to passdb !?\n", 
-                         account));
-               nt_status = NT_STATUS_ACCESS_DENIED;
-               goto done;
-       }
-       
+       /* now check for failure */
+       
+       if ( !NT_STATUS_IS_OK(nt_status) )
+               return nt_status;
+                       
        /* Get the user's SID */
+       
        sid_copy(&sid, pdb_get_user_sid(sam_pass));
        
-       samr_make_usr_obj_sd(p->mem_ctx, &psd, &sd_size, &sid);
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &usr_generic_mapping, &sid, SAMR_USR_RIGHTS_WRITE_PW);
        se_map_generic(&des_access, &usr_generic_mapping);
-       if (!NT_STATUS_IS_OK(nt_status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_create_user"))) {
-               goto done;
+       
+       nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               &se_rights, GENERIC_RIGHTS_USER_WRITE, des_access, 
+               &acc_granted, "_samr_create_user");
+               
+       if ( !NT_STATUS_IS_OK(nt_status) ) {
+               return nt_status;
        }
 
        /* associate the user's SID with the new handle. */
        if ((info = get_samr_info_by_sid(&sid)) == NULL) {
                pdb_free_sam(&sam_pass);
-               nt_status = NT_STATUS_NO_MEMORY;
-               goto done;
+               return NT_STATUS_NO_MEMORY;
        }
 
        ZERO_STRUCTP(info);
@@ -2308,8 +2362,7 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
        /* get a (unique) handle.  open a policy on it. */
        if (!create_policy_hnd(p, user_pol, free_samr_info, (void *)info)) {
                pdb_free_sam(&sam_pass);
-               nt_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
-               goto done;
+               return NT_STATUS_OBJECT_NAME_NOT_FOUND;
        }
 
        r_u->user_rid=pdb_get_user_rid(sam_pass);
@@ -2318,11 +2371,7 @@ NTSTATUS _samr_create_user(pipes_struct *p, SAMR_Q_CREATE_USER *q_u, SAMR_R_CREA
 
        pdb_free_sam(&sam_pass);
 
-       nt_status = NT_STATUS_OK;
-
-done:
-       unbecome_root();
-       return nt_status;
+       return NT_STATUS_OK;
 }
 
 /*******************************************************************
@@ -2376,8 +2425,8 @@ NTSTATUS _samr_connect(pipes_struct *p, SAMR_Q_CONNECT *q_u, SAMR_R_CONNECT *r_u
        SEC_DESC *psd = NULL;
        uint32    acc_granted;
        uint32    des_access = q_u->access_mask;
-       size_t    sd_size;
        NTSTATUS  nt_status;
+       size_t sd_size;
 
 
        DEBUG(5,("_samr_connect: %d\n", __LINE__));
@@ -2390,13 +2439,14 @@ NTSTATUS _samr_connect(pipes_struct *p, SAMR_Q_CONNECT *q_u, SAMR_R_CONNECT *r_u
                return r_u->status;
        }
 
-       samr_make_sam_obj_sd(p->mem_ctx, &psd, &sd_size);
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
        se_map_generic(&des_access, &sam_generic_mapping);
-       if (!NT_STATUS_IS_OK(nt_status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_connect"))) {
+       
+       nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               NULL, 0, des_access, &acc_granted, "_samr_connect");
+       
+       if ( !NT_STATUS_IS_OK(nt_status) ) 
                return nt_status;
-       }
 
        r_u->status = NT_STATUS_OK;
 
@@ -2426,8 +2476,8 @@ NTSTATUS _samr_connect4(pipes_struct *p, SAMR_Q_CONNECT4 *q_u, SAMR_R_CONNECT4 *
        SEC_DESC *psd = NULL;
        uint32    acc_granted;
        uint32    des_access = q_u->access_mask;
-       size_t    sd_size;
        NTSTATUS  nt_status;
+       size_t sd_size;
 
 
        DEBUG(5,("_samr_connect4: %d\n", __LINE__));
@@ -2440,13 +2490,14 @@ NTSTATUS _samr_connect4(pipes_struct *p, SAMR_Q_CONNECT4 *q_u, SAMR_R_CONNECT4 *
                return r_u->status;
        }
 
-       samr_make_sam_obj_sd(p->mem_ctx, &psd, &sd_size);
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &sam_generic_mapping, NULL, 0);
        se_map_generic(&des_access, &sam_generic_mapping);
-       if (!NT_STATUS_IS_OK(nt_status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_connect"))) {
+       
+       nt_status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               NULL, 0, des_access, &acc_granted, "_samr_connect4");
+       
+       if ( !NT_STATUS_IS_OK(nt_status) ) 
                return nt_status;
-       }
 
        r_u->status = NT_STATUS_OK;
 
@@ -2481,8 +2532,11 @@ 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;
 
+       /* win9x user manager likes to use SA_RIGHT_SAM_ENUM_DOMAINS here.  
+          Reverted that change so we will work with RAS servers again */
+
        if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(info->acc_granted, 
-               SA_RIGHT_SAM_ENUM_DOMAINS, "_samr_lookup_domain"))) 
+               SA_RIGHT_SAM_OPEN_DOMAIN, "_samr_lookup_domain"))) 
        {
                return r_u->status;
        }
@@ -2521,8 +2575,8 @@ static BOOL make_enum_domains(TALLOC_CTX *ctx, SAM_ENTRY **pp_sam,
        if (num_sam_entries == 0)
                return True;
 
-       sam = (SAM_ENTRY *)talloc_zero(ctx, sizeof(SAM_ENTRY)*num_sam_entries);
-       uni_name = (UNISTR2 *)talloc_zero(ctx, sizeof(UNISTR2)*num_sam_entries);
+       sam = TALLOC_ZERO_ARRAY(ctx, SAM_ENTRY, num_sam_entries);
+       uni_name = TALLOC_ZERO_ARRAY(ctx, UNISTR2, num_sam_entries);
 
        if (sam == NULL || uni_name == NULL)
                return False;
@@ -2588,29 +2642,40 @@ NTSTATUS _samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_A
        uint32    des_access = q_u->access_mask;
        size_t    sd_size;
        NTSTATUS  status;
+       SE_PRIV se_rights;
 
        r_u->status = NT_STATUS_OK;
 
        /* find the domain policy and get the SID / access bits stored in the domain policy */
-       if (!get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted))
+       
+       if ( !get_lsa_policy_samr_sid(p, &domain_pol, &sid, &acc_granted) )
                return NT_STATUS_INVALID_HANDLE;
+       
+       status = access_check_samr_function(acc_granted, 
+               SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_alias");
                
-       if (!NT_STATUS_IS_OK(status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_alias"))) {
+       if ( !NT_STATUS_IS_OK(status) ) 
                return status;
-       }
 
        /* append the alias' RID to it */
+       
        if (!sid_append_rid(&sid, alias_rid))
                return NT_STATUS_NO_SUCH_USER;
                
        /*check if access can be granted as requested by client. */
-       samr_make_ali_obj_sd(p->mem_ctx, &psd, &sd_size);
+       
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &ali_generic_mapping, NULL, 0);
        se_map_generic(&des_access,&ali_generic_mapping);
-       if (!NT_STATUS_IS_OK(status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_open_alias"))) {
+       
+       se_priv_add( &se_rights, &se_add_users );
+       
+       
+       status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               &se_rights, GENERIC_RIGHTS_ALIAS_WRITE, des_access, 
+               &acc_granted, "_samr_open_alias");
+               
+       if ( !NT_STATUS_IS_OK(status) )
                return status;
-       }
 
        /*
         * we should check if the rid really exist !!!
@@ -2634,20 +2699,8 @@ NTSTATUS _samr_open_alias(pipes_struct *p, SAMR_Q_OPEN_ALIAS *q_u, SAMR_R_OPEN_A
  set_user_info_10
  ********************************************************************/
 
-static BOOL set_user_info_10(const SAM_USER_INFO_10 *id10, DOM_SID *sid)
+static BOOL set_user_info_10(const SAM_USER_INFO_10 *id10, SAM_ACCOUNT *pwd)
 {
-       SAM_ACCOUNT *pwd =NULL;
-       BOOL ret;
-       
-       pdb_init_sam(&pwd);
-       
-       ret = pdb_getsampwsid(pwd, sid);
-       
-       if(ret==False) {
-               pdb_free_sam(&pwd);
-               return False;
-       }
-
        if (id10 == NULL) {
                DEBUG(5, ("set_user_info_10: NULL id10\n"));
                pdb_free_sam(&pwd);
@@ -2674,16 +2727,8 @@ static BOOL set_user_info_10(const SAM_USER_INFO_10 *id10, DOM_SID *sid)
  set_user_info_12
  ********************************************************************/
 
-static BOOL set_user_info_12(SAM_USER_INFO_12 *id12, DOM_SID *sid)
+static BOOL set_user_info_12(SAM_USER_INFO_12 *id12, SAM_ACCOUNT *pwd)
 {
-       SAM_ACCOUNT *pwd = NULL;
-
-       pdb_init_sam(&pwd);
-
-       if(!pdb_getsampwsid(pwd, sid)) {
-               pdb_free_sam(&pwd);
-               return False;
-       }
 
        if (id12 == NULL) {
                DEBUG(2, ("set_user_info_12: id12 is NULL\n"));
@@ -2753,22 +2798,13 @@ static BOOL set_unix_primary_group(SAM_ACCOUNT *sampass)
  set_user_info_20
  ********************************************************************/
 
-static BOOL set_user_info_20(SAM_USER_INFO_20 *id20, DOM_SID *sid)
+static BOOL set_user_info_20(SAM_USER_INFO_20 *id20, SAM_ACCOUNT *pwd)
 {
-       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 */
@@ -2785,22 +2821,14 @@ static BOOL set_user_info_20(SAM_USER_INFO_20 *id20, DOM_SID *sid)
  set_user_info_21
  ********************************************************************/
 
-static BOOL set_user_info_21(SAM_USER_INFO_21 *id21, DOM_SID *sid)
+static BOOL set_user_info_21(SAM_USER_INFO_21 *id21, SAM_ACCOUNT *pwd)
 {
-       SAM_ACCOUNT *pwd = NULL;
  
        if (id21 == NULL) {
                DEBUG(5, ("set_user_info_21: NULL id21\n"));
                return False;
        }
  
-       pdb_init_sam(&pwd);
-       if (!pdb_getsampwsid(pwd, sid)) {
-               pdb_free_sam(&pwd);
-               return False;
-       }
        copy_id21_to_sam_passwd(pwd, id21);
  
        /*
@@ -2828,9 +2856,8 @@ static BOOL set_user_info_21(SAM_USER_INFO_21 *id21, DOM_SID *sid)
  set_user_info_23
  ********************************************************************/
 
-static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, DOM_SID *sid)
+static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, SAM_ACCOUNT *pwd)
 {
-       SAM_ACCOUNT *pwd = NULL;
        pstring plaintext_buf;
        uint32 len;
        uint16 acct_ctrl;
@@ -2840,13 +2867,6 @@ static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, DOM_SID *sid)
                return False;
        }
  
-       pdb_init_sam(&pwd);
-       if (!pdb_getsampwsid(pwd, sid)) {
-               pdb_free_sam(&pwd);
-               return False;
-       }
-
        DEBUG(5, ("Attempting administrator password change (level 23) for user %s\n",
                  pdb_get_username(pwd)));
 
@@ -2903,20 +2923,12 @@ static BOOL set_user_info_23(SAM_USER_INFO_23 *id23, DOM_SID *sid)
  set_user_info_pw
  ********************************************************************/
 
-static BOOL set_user_info_pw(char *pass, DOM_SID *sid)
+static BOOL set_user_info_pw(char *pass, SAM_ACCOUNT *pwd)
 {
-       SAM_ACCOUNT *pwd = NULL;
        uint32 len;
        pstring plaintext_buf;
        uint16 acct_ctrl;
  
-       pdb_init_sam(&pwd);
-       if (!pdb_getsampwsid(pwd, sid)) {
-               pdb_free_sam(&pwd);
-               return False;
-       }
-       
        DEBUG(5, ("Attempting administrator password change for user %s\n",
                  pdb_get_username(pwd)));
 
@@ -2975,12 +2987,16 @@ static BOOL set_user_info_pw(char *pass, DOM_SID *sid)
 
 NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SET_USERINFO *r_u)
 {
+       SAM_ACCOUNT *pwd = NULL;
        DOM_SID sid;
        POLICY_HND *pol = &q_u->pol;
        uint16 switch_value = q_u->switch_value;
        SAM_USERINFO_CTR *ctr = q_u->ctr;
        uint32 acc_granted;
        uint32 acc_required;
+       BOOL ret;
+       BOOL has_enough_rights;
+       SE_PRIV se_rights;
 
        DEBUG(5, ("_samr_set_userinfo: %d\n", __LINE__));
 
@@ -2989,8 +3005,11 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
        /* find the policy handle.  open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted))
                return NT_STATUS_INVALID_HANDLE;
+
+       /* observed when joining an XP client to a Samba domain */
        
-       acc_required = SA_RIGHT_USER_SET_LOC_COM | SA_RIGHT_USER_SET_ATTRIBUTES; /* This is probably wrong */   
+       acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;     
+
        if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo"))) {
                return r_u->status;
        }
@@ -3001,24 +3020,55 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
                DEBUG(5, ("_samr_set_userinfo: NULL info level\n"));
                return NT_STATUS_INVALID_INFO_CLASS;
        }
+       
+       pdb_init_sam(&pwd);     
+       
+       become_root();
+       ret = pdb_getsampwsid(pwd, &sid);
+       unbecome_root();
+       
+       if ( !ret ) {
+               pdb_free_sam(&pwd);
+               return NT_STATUS_NO_SUCH_USER;
+       }
+       
+       /* deal with machine password changes differently from userinfo changes */
+       
+       if ( pdb_get_acct_ctrl(pwd) & ACB_WSTRUST )
+               se_priv_copy( &se_rights, &se_machine_account );
+       else
+               se_priv_copy( &se_rights, &se_add_users );
+
+       /* check to see if we have the sufficient rights */
+       
+       has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+       
+       DEBUG(5, ("_samr_set_userinfo: %s does%s possess sufficient rights\n",
+               p->pipe_user_name, has_enough_rights ? "" : " not"));
 
+       /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
+       
+       if ( has_enough_rights )                                
+               become_root(); 
+       
        /* ok!  user info levels (lots: see MSDEV help), off we go... */
+
        switch (switch_value) {
-               case 0x12:
-                       if (!set_user_info_12(ctr->info.id12, &sid))
-                               return NT_STATUS_ACCESS_DENIED;
+               case 18:
+                       if (!set_user_info_12(ctr->info.id12, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
                        break;
 
                case 24:
                        if (!p->session_key.length) {
-                               return NT_STATUS_NO_USER_SESSION_KEY;
+                               r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
                        }
                        SamOEMhashBlob(ctr->info.id24->pass, 516, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id24->pass, 516);
 
-                       if (!set_user_info_pw((char *)ctr->info.id24->pass, &sid))
-                               return NT_STATUS_ACCESS_DENIED;
+                       if (!set_user_info_pw((char *)ctr->info.id24->pass, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
                        break;
 
                case 25:
@@ -3032,34 +3082,41 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
                         */
 
                        if (!p->session_key.length) {
-                               return NT_STATUS_NO_USER_SESSION_KEY;
+                               r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
                        }
                        SamOEMhashBlob(ctr->info.id25->pass, 532, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id25->pass, 532);
 
                        if (!set_user_info_pw(ctr->info.id25->pass, &sid))
-                               return NT_STATUS_ACCESS_DENIED;
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
                        break;
 #endif
-                       return NT_STATUS_INVALID_INFO_CLASS;
+                       r_u->status = NT_STATUS_INVALID_INFO_CLASS;
+                       break;
 
                case 23:
                        if (!p->session_key.length) {
-                               return NT_STATUS_NO_USER_SESSION_KEY;
+                               r_u->status = NT_STATUS_NO_USER_SESSION_KEY;
                        }
                        SamOEMhashBlob(ctr->info.id23->pass, 516, &p->session_key);
 
                        dump_data(100, (char *)ctr->info.id23->pass, 516);
 
-                       if (!set_user_info_23(ctr->info.id23, &sid))
-                               return NT_STATUS_ACCESS_DENIED;
+                       if (!set_user_info_23(ctr->info.id23, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
                        break;
 
                default:
-                       return NT_STATUS_INVALID_INFO_CLASS;
+                       r_u->status = NT_STATUS_INVALID_INFO_CLASS;
        }
 
+       
+       if ( has_enough_rights )                                
+               unbecome_root();
+               
+       /* ================ END SeMachineAccountPrivilege BLOCK ================ */
+
        return r_u->status;
 }
 
@@ -3069,12 +3126,16 @@ NTSTATUS _samr_set_userinfo(pipes_struct *p, SAMR_Q_SET_USERINFO *q_u, SAMR_R_SE
 
 NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_SET_USERINFO2 *r_u)
 {
+       SAM_ACCOUNT *pwd = NULL;
        DOM_SID sid;
        SAM_USERINFO_CTR *ctr = q_u->ctr;
        POLICY_HND *pol = &q_u->pol;
        uint16 switch_value = q_u->switch_value;
        uint32 acc_granted;
        uint32 acc_required;
+       BOOL ret;
+       BOOL has_enough_rights;
+       SE_PRIV se_rights;
 
        DEBUG(5, ("samr_reply_set_userinfo2: %d\n", __LINE__));
 
@@ -3083,8 +3144,11 @@ NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_
        /* find the policy handle.  open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, pol, &sid, &acc_granted))
                return NT_STATUS_INVALID_HANDLE;
+
+       /* observed when joining XP client to Samba domain */
+               
+       acc_required = SA_RIGHT_USER_SET_PASSWORD | SA_RIGHT_USER_SET_ATTRIBUTES | SA_RIGHT_USER_ACCT_FLAGS_EXPIRY;
        
-       acc_required = SA_RIGHT_USER_SET_LOC_COM | SA_RIGHT_USER_SET_ATTRIBUTES; /* This is probably wrong */   
        if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, acc_required, "_samr_set_userinfo2"))) {
                return r_u->status;
        }
@@ -3098,29 +3162,65 @@ NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_
 
        switch_value=ctr->switch_value;
 
-       /* ok!  user info levels (lots: see MSDEV help), off we go... */
-       switch (switch_value) {
-               case 21:
-                       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;
-                       break;
-               case 18:
+       pdb_init_sam(&pwd);     
+       
+       become_root();
+       ret = pdb_getsampwsid(pwd, &sid);
+       unbecome_root();
+       
+       if ( !ret ) {
+               pdb_free_sam(&pwd);
+               return NT_STATUS_NO_SUCH_USER;
+       }
+       
+       /* deal with machine password changes differently from userinfo changes */
+       
+       if ( pdb_get_acct_ctrl(pwd) & ACB_WSTRUST )
+               se_priv_copy( &se_rights, &se_machine_account );
+       else
+               se_priv_copy( &se_rights, &se_add_users );
+
+       /* check to see if we have the sufficient rights */
+       
+       has_enough_rights = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+       
+       DEBUG(5, ("_samr_set_userinfo: %s does%s possess sufficient rights\n",
+               p->pipe_user_name, has_enough_rights ? "" : " not"));
+
+       /* ================ BEGIN SeMachineAccountPrivilege BLOCK ================ */
+       
+       if ( has_enough_rights )                                
+               become_root(); 
+       
+       /* ok!  user info levels (lots: see MSDEV help), off we go... */
+       
+       switch (switch_value) {
+               case 16:
+                       if (!set_user_info_10(ctr->info.id10, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
+                       break;
+               case 18:
                        /* Used by AS/U JRA. */
-                       if (!set_user_info_12(ctr->info.id12, &sid))
+                       if (!set_user_info_12(ctr->info.id12, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
+                       break;
+               case 20:
+                       if (!set_user_info_20(ctr->info.id20, pwd))
+                               r_u->status = NT_STATUS_ACCESS_DENIED;
+                       break;
+               case 21:
+                       if (!set_user_info_21(ctr->info.id21, pwd))
                                return NT_STATUS_ACCESS_DENIED;
                        break;
                default:
-                       return NT_STATUS_INVALID_INFO_CLASS;
+                       r_u->status = NT_STATUS_INVALID_INFO_CLASS;
        }
 
+       if ( has_enough_rights )                                
+               unbecome_root();
+               
+       /* ================ END SeMachineAccountPrivilege BLOCK ================ */
+
        return r_u->status;
 }
 
@@ -3130,31 +3230,19 @@ NTSTATUS _samr_set_userinfo2(pipes_struct *p, SAMR_Q_SET_USERINFO2 *q_u, SAMR_R_
 
 NTSTATUS _samr_query_useraliases(pipes_struct *p, SAMR_Q_QUERY_USERALIASES *q_u, SAMR_R_QUERY_USERALIASES *r_u)
 {
-       int num_groups = 0, tmp_num_groups=0;
-       uint32 *rids=NULL, *new_rids=NULL, *tmp_rids=NULL;
+       int num_groups = 0;
+       uint32 *rids=NULL;
        struct samr_info *info = NULL;
-       int i,j;
+       int i;
                
        NTSTATUS ntstatus1;
        NTSTATUS ntstatus2;
 
-       /* until i see a real useraliases query, we fack one up */
+       DOM_SID *members;
+       DOM_SID *aliases;
+       int num_aliases;
+       BOOL res;
 
-       /* I have seen one, JFM 2/12/2001 */
-       /*
-        * Explanation of what this call does:
-        * for all the SID given in the request:
-        * return a list of alias (local groups)
-        * that have those SID as members.
-        *
-        * and that's the alias in the domain specified
-        * in the policy_handle
-        *
-        * if the policy handle is on an incorrect sid
-        * for example a user's sid
-        * we should reply NT_STATUS_OBJECT_TYPE_MISMATCH
-        */
-       
        r_u->status = NT_STATUS_OK;
 
        DEBUG(5,("_samr_query_useraliases: %d\n", __LINE__));
@@ -3177,40 +3265,42 @@ NTSTATUS _samr_query_useraliases(pipes_struct *p, SAMR_Q_QUERY_USERALIASES *q_u,
            !sid_check_is_builtin(&info->sid))
                return NT_STATUS_OBJECT_TYPE_MISMATCH;
 
+       members = TALLOC_ARRAY(p->mem_ctx, DOM_SID, q_u->num_sids1);
 
-       for (i=0; i<q_u->num_sids1; i++) {
+       if (members == NULL)
+               return NT_STATUS_NO_MEMORY;
 
-               r_u->status=get_alias_user_groups(p->mem_ctx, &info->sid, &tmp_num_groups, &tmp_rids, &(q_u->sid[i].sid));
+       for (i=0; i<q_u->num_sids1; i++)
+               sid_copy(&members[i], &q_u->sid[i].sid);
 
-               /*
-                * if there is an error, we just continue as
-                * it can be an unfound user or group
-                */
-               if (!NT_STATUS_IS_OK(r_u->status)) {
-                       DEBUG(10,("_samr_query_useraliases: an error occured while getting groups\n"));
-                       continue;
-               }
+       become_root();
+       res = pdb_enum_alias_memberships(members,
+                                        q_u->num_sids1, &aliases,
+                                        &num_aliases);
+       unbecome_root();
+
+       if (!res)
+               return NT_STATUS_UNSUCCESSFUL;
+
+       rids = NULL;
+       num_groups = 0;
 
-               if (tmp_num_groups==0) {
-                       DEBUG(10,("_samr_query_useraliases: no groups found\n"));
+       for (i=0; i<num_aliases; i++) {
+               uint32 rid;
+
+               if (!sid_peek_check_rid(&info->sid, &aliases[i], &rid))
                        continue;
-               }
 
-               new_rids=(uint32 *)talloc_realloc(p->mem_ctx, rids, (num_groups+tmp_num_groups)*sizeof(uint32));
-               if (new_rids==NULL) {
-                       DEBUG(0,("_samr_query_useraliases: could not realloc memory\n"));
+               rids = TALLOC_REALLOC_ARRAY(p->mem_ctx, rids, uint32, num_groups+1);
+
+               if (rids == NULL)
                        return NT_STATUS_NO_MEMORY;
-               }
-               rids=new_rids;
 
-               for (j=0; j<tmp_num_groups; j++)
-                       rids[j+num_groups]=tmp_rids[j];
-               
-               safe_free(tmp_rids);
-               
-               num_groups+=tmp_num_groups;
+               rids[num_groups] = rid;
+               num_groups += 1;
        }
-       
+       SAFE_FREE(aliases);
+
        init_samr_r_query_useraliases(r_u, num_groups, rids, NT_STATUS_OK);
        return NT_STATUS_OK;
 }
@@ -3223,15 +3313,11 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
 {
        int i;
 
-       GROUP_MAP map;
        int num_sids = 0;
        DOM_SID2 *sid;
        DOM_SID *sids=NULL;
 
        DOM_SID alias_sid;
-       DOM_SID als_sid;
-       uint32 alias_rid;
-       fstring alias_sid_str;
 
        uint32 acc_granted;
 
@@ -3243,36 +3329,13 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
                access_check_samr_function(acc_granted, SA_RIGHT_ALIAS_GET_MEMBERS, "_samr_query_aliasmem"))) {
                return r_u->status;
        }
-               
-       sid_copy(&als_sid, &alias_sid);
-       sid_to_string(alias_sid_str, &alias_sid);
-       sid_split_rid(&alias_sid, &alias_rid);
-
-       DEBUG(10, ("sid is %s\n", alias_sid_str));
 
-       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))
-                       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)) {
-                               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;
-                       }
-               }
-       }
+       DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
 
-       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))); 
+       if (!pdb_enum_aliasmem(&alias_sid, &sids, &num_sids))
                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_sids); 
+       sid = TALLOC_ZERO_ARRAY(p->mem_ctx, DOM_SID2, num_sids);        
        if (num_sids!=0 && sid == NULL) {
                SAFE_FREE(sids);
                return NT_STATUS_NO_MEMORY;
@@ -3282,7 +3345,6 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
                init_dom_sid2(&sid[i], &sids[i]);
        }
 
-       DEBUG(10, ("sid is %s\n", alias_sid_str));
        init_samr_r_query_aliasmem(r_u, num_sids, sid, NT_STATUS_OK);
 
        SAFE_FREE(sids);
@@ -3290,20 +3352,82 @@ NTSTATUS _samr_query_aliasmem(pipes_struct *p, SAMR_Q_QUERY_ALIASMEM *q_u, SAMR_
        return NT_STATUS_OK;
 }
 
+static void add_uid_to_array_unique(uid_t uid, uid_t **uids, int *num)
+{
+       int i;
+
+       for (i=0; i<*num; i++) {
+               if ((*uids)[i] == uid)
+                       return;
+       }
+       
+       *uids = SMB_REALLOC_ARRAY(*uids, uid_t, *num+1);
+
+       if (*uids == NULL)
+               return;
+
+       (*uids)[*num] = uid;
+       *num += 1;
+}
+
+
+static BOOL get_memberuids(gid_t gid, uid_t **uids, int *num)
+{
+       struct group *grp;
+       char **gr;
+       struct sys_pwent *userlist, *user;
+       *uids = NULL;
+       *num = 0;
+
+       /* We only look at our own sam, so don't care about imported stuff */
+
+       winbind_off();
+
+       if ((grp = getgrgid(gid)) == NULL) {
+               winbind_on();
+               return False;
+       }
+
+       /* Primary group members */
+
+       userlist = getpwent_list();
+
+       for (user = userlist; user != NULL; user = user->next) {
+               if (user->pw_gid != gid)
+                       continue;
+               add_uid_to_array_unique(user->pw_uid, uids, num);
+       }
+
+       pwent_free(userlist);
+
+       /* Secondary group members */
+
+       for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
+               struct passwd *pw = getpwnam(*gr);
+
+               if (pw == NULL)
+                       continue;
+               add_uid_to_array_unique(pw->pw_uid, uids, num);
+       }
+
+       winbind_on();
+
+       return True;
+}      
+
 /*********************************************************************
  _samr_query_groupmem
 *********************************************************************/
 
 NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_R_QUERY_GROUPMEM *r_u)
 {
-       int num_sids = 0;
-       int final_num_sids = 0;
-       int i;
+       int final_num_rids, i;
        DOM_SID group_sid;
        fstring group_sid_str;
-       DOM_SID *sids=NULL;
-       
-       GROUP_MAP map;
+       uid_t *uids;
+       int num;
+       gid_t gid;
 
        uint32 *rid=NULL;
        uint32 *attr=NULL;
@@ -3328,35 +3452,46 @@ NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_
 
        DEBUG(10, ("lookup on Domain SID\n"));
 
-       if(!get_domain_group_from_sid(group_sid, &map))
+       if (!NT_STATUS_IS_OK(sid_to_gid(&group_sid, &gid)))
                return NT_STATUS_NO_SUCH_GROUP;
 
-       if(!get_sid_list_of_group(map.gid, &sids, &num_sids))
+       if(!get_memberuids(gid, &uids, &num))
                return NT_STATUS_NO_SUCH_GROUP;
 
-       rid=talloc_zero(p->mem_ctx, sizeof(uint32)*num_sids);
-       attr=talloc_zero(p->mem_ctx, sizeof(uint32)*num_sids);
+       rid=TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num);
+       attr=TALLOC_ZERO_ARRAY(p->mem_ctx, uint32, num);
        
-       if (num_sids!=0 && (rid==NULL || attr==NULL))
+       if (num!=0 && (rid==NULL || attr==NULL))
                return NT_STATUS_NO_MEMORY;
        
-       for (i=0; i<num_sids; i++) {
-               uint32 urid;
+       final_num_rids = 0;
                
-               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())));
+       for (i=0; i<num; i++) {
+               DOM_SID sid;
+
+               if (!NT_STATUS_IS_OK(uid_to_sid(&sid, uids[i]))) {
+                       DEBUG(1, ("Could not map member uid to SID\n"));
+                       continue;
+               }
+
+               if (!sid_check_is_in_our_domain(&sid)) {
+                       DEBUG(1, ("Inconsistent SAM -- group member uid not "
+                                 "in our domain\n"));
+                       continue;
                }
+
+               sid_peek_rid(&sid, &rid[final_num_rids]);
+
+               /* Hmm. In a trace I got the constant 7 here from NT. */
+               attr[final_num_rids] = SID_NAME_USER;
+
+               final_num_rids += 1;
        }
 
-       init_samr_r_query_groupmem(r_u, final_num_sids, rid, attr, NT_STATUS_OK);
+       SAFE_FREE(uids);
+
+       init_samr_r_query_groupmem(r_u, final_num_rids, rid, attr,
+                                  NT_STATUS_OK);
 
        return NT_STATUS_OK;
 }
@@ -3368,16 +3503,11 @@ NTSTATUS _samr_query_groupmem(pipes_struct *p, SAMR_Q_QUERY_GROUPMEM *q_u, SAMR_
 NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_ADD_ALIASMEM *r_u)
 {
        DOM_SID alias_sid;
-       fstring alias_sid_str;
-       uid_t uid;
-       struct passwd *pwd;
-       struct group *grp;
-       fstring grp_name;
-       GROUP_MAP map;
-       NTSTATUS ret;
-       SAM_ACCOUNT *sam_user = NULL;
-       BOOL check;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       BOOL ret;
+
 
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted)) 
@@ -3387,76 +3517,24 @@ NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_AD
                return r_u->status;
        }
                
-       sid_to_string(alias_sid_str, &alias_sid);
-       DEBUG(10, ("sid is %s\n", alias_sid_str));
-
-       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))
-                       return NT_STATUS_NO_SUCH_ALIAS;
+       DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
        
-       } else {
-               if (sid_compare(&alias_sid, &global_sid_Builtin)>0) {
-                       DEBUG(10, ("adding member on BUILTIN SID\n"));
-                       if( !get_builtin_group_from_sid(&alias_sid, &map))
-                               return NT_STATUS_NO_SUCH_ALIAS;
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-               } else
-                       return NT_STATUS_NO_SUCH_ALIAS;
-       }
-
-       ret = pdb_init_sam(&sam_user);
-       if (!NT_STATUS_IS_OK(ret))
-               return ret;
+       /******** BEGIN SeAddUsers BLOCK *********/
        
-       check = pdb_getsampwsid(sam_user, &q_u->sid.sid);
+       if ( can_add_accounts )
+               become_root();
        
-       if (check != True) {
-               pdb_free_sam(&sam_user);
-               return pdb_add_aliasmem(&alias_sid, &q_u->sid.sid) ?
-                       NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
-       }
-
-       /* 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;
-       }
-
-       pdb_free_sam(&sam_user);
-
-       if ((pwd=getpwuid_alloc(uid)) == NULL) {
-               return NT_STATUS_NO_SUCH_USER;
-       }
+       ret = pdb_add_aliasmem(&alias_sid, &q_u->sid.sid);
        
-       if ((grp=getgrgid(map.gid)) == NULL) {
-               passwd_free(&pwd);
-               return NT_STATUS_NO_SUCH_ALIAS;
-       }
-
-       /* we need to copy the name otherwise it's overloaded in user_in_group_list */
-       fstrcpy(grp_name, grp->gr_name);
-
-       /* if the user is already in the group */
-       if(user_in_unix_group_list(pwd->pw_name, grp_name)) {
-               passwd_free(&pwd);
-               return NT_STATUS_MEMBER_IN_ALIAS;
-       }
-
-       /* 
-        * ok, the group exist, the user exist, the user is not in the group,
-        * we can (finally) add it to the group !
-        */
-       smb_add_user_group(grp_name, pwd->pw_name);
-
-       /* check if the user has been added then ... */
-       if(!user_in_unix_group_list(pwd->pw_name, grp_name)) {
-               passwd_free(&pwd);
-               return NT_STATUS_MEMBER_NOT_IN_ALIAS;   /* don't know what to reply else */
-       }
-
-       passwd_free(&pwd);
-       return NT_STATUS_OK;
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
+       return ret ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
 }
 
 /*********************************************************************
@@ -3466,12 +3544,10 @@ NTSTATUS _samr_add_aliasmem(pipes_struct *p, SAMR_Q_ADD_ALIASMEM *q_u, SAMR_R_AD
 NTSTATUS _samr_del_aliasmem(pipes_struct *p, SAMR_Q_DEL_ALIASMEM *q_u, SAMR_R_DEL_ALIASMEM *r_u)
 {
        DOM_SID alias_sid;
-       fstring alias_sid_str;
-       struct group *grp;
-       fstring grp_name;
-       GROUP_MAP map;
-       SAM_ACCOUNT *sam_pass=NULL;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       BOOL ret;
 
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->alias_pol, &alias_sid, &acc_granted)) 
@@ -3481,50 +3557,25 @@ NTSTATUS _samr_del_aliasmem(pipes_struct *p, SAMR_Q_DEL_ALIASMEM *q_u, SAMR_R_DE
                return r_u->status;
        }
        
-       sid_to_string(alias_sid_str, &alias_sid);
-       DEBUG(10, ("_samr_del_aliasmem:sid is %s\n", alias_sid_str));
-
-       if (!sid_check_is_in_our_domain(&alias_sid) &&
-           !sid_check_is_in_builtin(&alias_sid)) {
-               DEBUG(10, ("_samr_del_aliasmem:invalid alias group\n"));
-               return NT_STATUS_NO_SUCH_ALIAS;
-       }
-
-       if( !get_local_group_from_sid(&alias_sid, &map) &&
-           !get_builtin_group_from_sid(&alias_sid, &map) )
-               return NT_STATUS_NO_SUCH_ALIAS;
-
-       if ((grp=getgrgid(map.gid)) == NULL)
-               return NT_STATUS_NO_SUCH_ALIAS;
-
-       /* we need to copy the name otherwise it's overloaded in user_in_unix_group_list */
-       fstrcpy(grp_name, grp->gr_name);
-
-       /* check if the user exists before trying to remove it from the group */
-       pdb_init_sam(&sam_pass);
-       if(!pdb_getsampwsid(sam_pass, &q_u->sid.sid)) {
-               DEBUG(5,("_samr_del_aliasmem:User %s doesn't exist.\n", pdb_get_username(sam_pass)));
-               pdb_free_sam(&sam_pass);
-               return pdb_del_aliasmem(&alias_sid, &q_u->sid.sid) ?
-                       NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
-       }
+       DEBUG(10, ("_samr_del_aliasmem:sid is %s\n",
+                  sid_string_static(&alias_sid)));
 
-       /* if the user is not in the group */
-       if(!user_in_unix_group_list(pdb_get_username(sam_pass), grp_name)) {
-               pdb_free_sam(&sam_pass);
-               return NT_STATUS_MEMBER_NOT_IN_ALIAS;
-       }
-
-       smb_delete_user_group(grp_name, pdb_get_username(sam_pass));
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-       /* check if the user has been removed then ... */
-       if(user_in_unix_group_list(pdb_get_username(sam_pass), grp_name)) {
-               pdb_free_sam(&sam_pass);
-               return NT_STATUS_MEMBER_NOT_IN_ALIAS;   /* don't know what to reply else */
-       }
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
 
-       pdb_free_sam(&sam_pass);
-       return NT_STATUS_OK;
+       ret = pdb_del_aliasmem(&alias_sid, &q_u->sid.sid);
+       
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
+       return ret ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
 }
 
 /*********************************************************************
@@ -3545,6 +3596,8 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
        SAM_ACCOUNT *sam_user=NULL;
        BOOL check;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
 
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->pol, &group_sid, &acc_granted)) 
@@ -3605,6 +3658,14 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
                return NT_STATUS_MEMBER_IN_GROUP;
        }
 
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
+               
        /* 
         * ok, the group exist, the user exist, the user is not in the group,
         *
@@ -3613,6 +3674,11 @@ NTSTATUS _samr_add_groupmem(pipes_struct *p, SAMR_Q_ADD_GROUPMEM *q_u, SAMR_R_AD
 
        smb_add_user_group(grp_name, pwd->pw_name);
 
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
        /* check if the user has been added then ... */
        if(!user_in_unix_group_list(pwd->pw_name, grp_name)) {
                passwd_free(&pwd);
@@ -3636,6 +3702,8 @@ NTSTATUS _samr_del_groupmem(pipes_struct *p, SAMR_Q_DEL_GROUPMEM *q_u, SAMR_R_DE
        fstring grp_name;
        struct group *grp;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
 
        /*
         * delete the group member named q_u->rid
@@ -3679,9 +3747,23 @@ NTSTATUS _samr_del_groupmem(pipes_struct *p, SAMR_Q_DEL_GROUPMEM *q_u, SAMR_R_DE
                pdb_free_sam(&sam_pass);
                return NT_STATUS_MEMBER_NOT_IN_GROUP;
        }
+       
+
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
+               
        smb_delete_user_group(grp_name, pdb_get_username(sam_pass));
 
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
        /* check if the user has been removed then ... */
        if (user_in_unix_group_list(pdb_get_username(sam_pass), grp_name)) {
                pdb_free_sam(&sam_pass);
@@ -3717,7 +3799,7 @@ static int smb_delete_user(const char *unix_user)
        pstrcpy(del_script, lp_deluser_script());
        if (! *del_script)
                return -1;
-       all_string_sub(del_script, "%u", unix_user, sizeof(pstring));
+       all_string_sub(del_script, "%u", unix_user, sizeof(del_script));
        ret = smbrun(del_script,NULL);
        DEBUG(3,("smb_delete_user: Running the command `%s' gave %d\n",del_script,ret));
 
@@ -3733,6 +3815,9 @@ NTSTATUS _samr_delete_dom_user(pipes_struct *p, SAMR_Q_DELETE_DOM_USER *q_u, SAM
        DOM_SID user_sid;
        SAM_ACCOUNT *sam_pass=NULL;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       BOOL ret;
 
        DEBUG(5, ("_samr_delete_dom_user: %d\n", __LINE__));
 
@@ -3755,22 +3840,41 @@ NTSTATUS _samr_delete_dom_user(pipes_struct *p, SAMR_Q_DELETE_DOM_USER *q_u, SAM
                pdb_free_sam(&sam_pass);
                return NT_STATUS_NO_SUCH_USER;
        }
+       
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-       /* delete the unix side */
-       /*
-        * note: we don't check if the delete really happened
-        * as the script is not necessary present
-        * and maybe the sysadmin doesn't want to delete the unix side
-        */
-       smb_delete_user(pdb_get_username(sam_pass));
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
 
-       /* and delete the samba side */
-       if (!pdb_delete_sam_account(sam_pass)) {
+       /* First delete the samba side....
+          code is order to prevent unnecessary returns out of the admin 
+          block of code */
+          
+       if ( (ret = pdb_delete_sam_account(sam_pass)) == True ) {
+               /*
+                * Now delete the unix side ....
+                * note: we don't check if the delete really happened
+                * as the script is not necessary present
+                * and maybe the sysadmin doesn't want to delete the unix side
+                */
+               smb_delete_user( pdb_get_username(sam_pass) );
+       }
+       
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+               
+       if ( !ret ) {
                DEBUG(5,("_samr_delete_dom_user:Failed to delete entry for user %s.\n", pdb_get_username(sam_pass)));
                pdb_free_sam(&sam_pass);
                return NT_STATUS_CANNOT_DELETE;
        }
-       
+
+
        pdb_free_sam(&sam_pass);
 
        if (!close_policy_hnd(p, &q_u->user_pol))
@@ -3793,6 +3897,9 @@ NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, S
        struct group *grp;
        GROUP_MAP map;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       BOOL ret;
 
        DEBUG(5, ("samr_delete_dom_group: %d\n", __LINE__));
 
@@ -3825,17 +3932,33 @@ 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;
 
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
+
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
+
        /* 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);
+       
+       if ( (ret = pdb_delete_group_mapping_entry(group_sid)) == True ) {
+               smb_delete_group( grp->gr_name );
+       }
 
-       /* check if the group has been successfully deleted */
-       if ( (grp=getgrgid(gid)) != NULL)
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
+       if ( !ret ) {
+               DEBUG(5,("_samr_delete_dom_group: Failed to delete mapping entry for group %s.\n", 
+                       group_sid_str));
                return NT_STATUS_ACCESS_DENIED;
-
+       }
+       
+       /* don't check that the unix group has been deleted.  Work like 
+          _samr_delet_dom_user() */
 
        if (!close_policy_hnd(p, &q_u->group_pol))
                return NT_STATUS_OBJECT_NAME_INVALID;
@@ -3850,13 +3973,10 @@ NTSTATUS _samr_delete_dom_group(pipes_struct *p, SAMR_Q_DELETE_DOM_GROUP *q_u, S
 NTSTATUS _samr_delete_dom_alias(pipes_struct *p, SAMR_Q_DELETE_DOM_ALIAS *q_u, SAMR_R_DELETE_DOM_ALIAS *r_u)
 {
        DOM_SID alias_sid;
-       DOM_SID dom_sid;
-       uint32 alias_rid;
-       fstring alias_sid_str;
-       gid_t gid;
-       struct group *grp;
-       GROUP_MAP map;
        uint32 acc_granted;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       BOOL ret;
 
        DEBUG(5, ("_samr_delete_dom_alias: %d\n", __LINE__));
 
@@ -3867,38 +3987,33 @@ NTSTATUS _samr_delete_dom_alias(pipes_struct *p, SAMR_Q_DELETE_DOM_ALIAS *q_u, S
        if (!NT_STATUS_IS_OK(r_u->status = access_check_samr_function(acc_granted, STD_RIGHT_DELETE_ACCESS, "_samr_delete_dom_alias"))) {
                return r_u->status;
        }
-               
-       sid_copy(&dom_sid, &alias_sid);
-       sid_to_string(alias_sid_str, &dom_sid);
-       sid_split_rid(&dom_sid, &alias_rid);
 
-       DEBUG(10, ("sid is %s\n", alias_sid_str));
+       DEBUG(10, ("sid is %s\n", sid_string_static(&alias_sid)));
 
-       /* we check if it's our SID before deleting */
-       if (!sid_equal(&dom_sid, get_global_sam_sid()))
+       if (!sid_check_is_in_our_domain(&alias_sid))
                return NT_STATUS_NO_SUCH_ALIAS;
-
+               
        DEBUG(10, ("lookup on Local SID\n"));
 
-       if(!get_local_group_from_sid(&alias_sid, &map))
-               return NT_STATUS_NO_SUCH_ALIAS;
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-       gid=map.gid;
-
-       /* check if group really exists */
-       if ( (grp=getgrgid(gid)) == NULL)
-               return NT_STATUS_NO_SUCH_ALIAS;
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
 
-       /* we can delete the UNIX group */
-       smb_delete_group(grp->gr_name);
+       /* Have passdb delete the alias */
+       ret = pdb_delete_alias(&alias_sid);
+       
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
 
-       /* check if the group has been successfully deleted */
-       if ( (grp=getgrgid(gid)) != NULL)
+       if ( !ret )
                return NT_STATUS_ACCESS_DENIED;
 
-       /* don't check if we removed it as it could be an un-mapped group */
-       pdb_delete_group_mapping_entry(alias_sid);
-
        if (!close_policy_hnd(p, &q_u->alias_pol))
                return NT_STATUS_OBJECT_NAME_INVALID;
 
@@ -3919,6 +4034,9 @@ NTSTATUS _samr_create_dom_group(pipes_struct *p, SAMR_Q_CREATE_DOM_GROUP *q_u, S
        struct samr_info *info;
        uint32 acc_granted;
        gid_t gid;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
+       NTSTATUS result;
 
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->pol, &dom_sid, &acc_granted)) 
@@ -3931,32 +4049,53 @@ NTSTATUS _samr_create_dom_group(pipes_struct *p, SAMR_Q_CREATE_DOM_GROUP *q_u, S
        if (!sid_equal(&dom_sid, get_global_sam_sid()))
                return NT_STATUS_ACCESS_DENIED;
 
-       /* TODO: check if allowed to create group and add a become_root/unbecome_root pair.*/
-
        unistr2_to_ascii(name, &q_u->uni_acct_desc, sizeof(name)-1);
 
        /* check if group already exist */
        if ((grp=getgrnam(name)) != NULL)
                return NT_STATUS_GROUP_EXISTS;
 
-       /* we can create the UNIX group */
-       if (smb_create_group(name, &gid) != 0)
-               return NT_STATUS_ACCESS_DENIED;
-
-       /* check if the group has been successfully created */
-       if ((grp=getgrgid(gid)) == NULL)
-               return NT_STATUS_ACCESS_DENIED;
-
-       r_u->rid=pdb_gid_to_group_rid(grp->gr_gid);
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-       /* add the group to the mapping table */
-       sid_copy(&info_sid, get_global_sam_sid());
-       sid_append_rid(&info_sid, r_u->rid);
-       sid_to_string(sid_string, &info_sid);
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
+       
+       /* check that we successfully create the UNIX group */
+       
+       result = NT_STATUS_ACCESS_DENIED;
+       if ( (smb_create_group(name, &gid) == 0) && ((grp=getgrgid(gid)) != NULL) ) {
+       
+               /* so far, so good */
+               
+               result = NT_STATUS_OK;
+               
+               r_u->rid = pdb_gid_to_group_rid( grp->gr_gid );
 
-       if(!add_initial_entry(grp->gr_gid, sid_string, SID_NAME_DOM_GRP, name, NULL))
-               return NT_STATUS_ACCESS_DENIED;
+               /* add the group to the mapping table */
+               
+               sid_copy( &info_sid, get_global_sam_sid() );
+               sid_append_rid( &info_sid, r_u->rid );
+               sid_to_string( sid_string, &info_sid );
+               
+               /* reset the error code if we fail to add the mapping entry */
+               
+               if ( !add_initial_entry(grp->gr_gid, sid_string, SID_NAME_DOM_GRP, name, NULL) )
+                       result = NT_STATUS_ACCESS_DENIED;
+       }
 
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+       
+       /* check if we should bail out here */
+       
+       if ( !NT_STATUS_IS_OK(result) )
+               return result;
+       
        if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
@@ -3976,11 +4115,13 @@ NTSTATUS _samr_create_dom_alias(pipes_struct *p, SAMR_Q_CREATE_DOM_ALIAS *q_u, S
        DOM_SID dom_sid;
        DOM_SID info_sid;
        fstring name;
-       fstring sid_string;
        struct group *grp;
        struct samr_info *info;
        uint32 acc_granted;
        gid_t gid;
+       NTSTATUS result;
+       SE_PRIV se_rights;
+       BOOL can_add_accounts;
 
        /* Find the policy handle. Open a policy on it. */
        if (!get_lsa_policy_samr_sid(p, &q_u->dom_pol, &dom_sid, &acc_granted)) 
@@ -3993,30 +4134,35 @@ NTSTATUS _samr_create_dom_alias(pipes_struct *p, SAMR_Q_CREATE_DOM_ALIAS *q_u, S
        if (!sid_equal(&dom_sid, get_global_sam_sid()))
                return NT_STATUS_ACCESS_DENIED;
 
-       /* TODO: check if allowed to create group  and add a become_root/unbecome_root pair.*/
-
        unistr2_to_ascii(name, &q_u->uni_acct_desc, sizeof(name)-1);
 
-       /* check if group already exists */
-       if ( (grp=getgrnam(name)) != NULL)
-               return NT_STATUS_GROUP_EXISTS;
+       se_priv_copy( &se_rights, &se_add_users );
+       can_add_accounts = user_has_privileges( p->pipe_user.nt_user_token, &se_rights );
 
-       /* we can create the UNIX group */
-       if (smb_create_group(name, &gid) != 0)
-               return NT_STATUS_ACCESS_DENIED;
+       /******** BEGIN SeAddUsers BLOCK *********/
+       
+       if ( can_add_accounts )
+               become_root();
 
-       /* check if the group has been successfully created */
-       if ((grp=getgrgid(gid)) == NULL)
-               return NT_STATUS_ACCESS_DENIED;
+       /* Have passdb create the alias */
+       result = pdb_create_alias(name, &r_u->rid);
 
-       r_u->rid=pdb_gid_to_group_rid(grp->gr_gid);
+       if ( can_add_accounts )
+               unbecome_root();
+               
+       /******** END SeAddUsers BLOCK *********/
+
+       if (!NT_STATUS_IS_OK(result))
+               return result;
 
        sid_copy(&info_sid, get_global_sam_sid());
        sid_append_rid(&info_sid, r_u->rid);
-       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))
+       if (!NT_STATUS_IS_OK(sid_to_gid(&info_sid, &gid)))
+               return NT_STATUS_ACCESS_DENIED;
+
+       /* check if the group has been successfully created */
+       if ((grp=getgrgid(gid)) == NULL)
                return NT_STATUS_ACCESS_DENIED;
 
        if ((info = get_samr_info_by_sid(&info_sid)) == NULL)
@@ -4041,7 +4187,8 @@ NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAM
        DOM_SID group_sid;
        GROUP_MAP map;
        DOM_SID *sids=NULL;
-       int num_sids=0;
+       uid_t *uids;
+       int num=0;
        GROUP_INFO_CTR *ctr;
        uint32 acc_granted;
        BOOL ret;
@@ -4059,16 +4206,17 @@ NTSTATUS _samr_query_groupinfo(pipes_struct *p, SAMR_Q_QUERY_GROUPINFO *q_u, SAM
        if (!ret)
                return NT_STATUS_INVALID_HANDLE;
 
-       ctr=(GROUP_INFO_CTR *)talloc_zero(p->mem_ctx, sizeof(GROUP_INFO_CTR));
+       ctr=TALLOC_ZERO_P(p->mem_ctx, GROUP_INFO_CTR);
        if (ctr==NULL)
                return NT_STATUS_NO_MEMORY;
 
        switch (q_u->switch_level) {
                case 1:
                        ctr->switch_value1 = 1;
-                       if(!get_sid_list_of_group(map.gid, &sids, &num_sids))
+                       if(!get_memberuids(map.gid, &uids, &num))
                                return NT_STATUS_NO_SUCH_GROUP;
-                       init_samr_group_info1(&ctr->group.info1, map.nt_name, map.comment, num_sids);
+                       SAFE_FREE(uids);
+                       init_samr_group_info1(&ctr->group.info1, map.nt_name, map.comment, num);
                        SAFE_FREE(sids);
                        break;
                case 3:
@@ -4140,7 +4288,7 @@ NTSTATUS _samr_set_groupinfo(pipes_struct *p, SAMR_Q_SET_GROUPINFO *q_u, SAMR_R_
 NTSTATUS _samr_set_aliasinfo(pipes_struct *p, SAMR_Q_SET_ALIASINFO *q_u, SAMR_R_SET_ALIASINFO *r_u)
 {
        DOM_SID group_sid;
-       GROUP_MAP map;
+       struct acct_info info;
        ALIAS_INFO_CTR *ctr;
        uint32 acc_granted;
 
@@ -4151,22 +4299,20 @@ 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) &&
-           !get_builtin_group_from_sid(&group_sid, &map))
-               return NT_STATUS_NO_SUCH_GROUP;
-       
        ctr=&q_u->ctr;
 
        switch (ctr->switch_value1) {
                case 3:
-                       unistr2_to_ascii(map.comment, &(ctr->alias.info3.uni_acct_desc), sizeof(map.comment)-1);
+                       unistr2_to_ascii(info.acct_desc,
+                                        &(ctr->alias.info3.uni_acct_desc),
+                                        sizeof(info.acct_desc)-1);
                        break;
                default:
                        return NT_STATUS_INVALID_INFO_CLASS;
        }
 
-       if(!pdb_update_group_mapping_entry(&map)) {
-               return NT_STATUS_NO_SUCH_GROUP;
+       if(!pdb_set_aliasinfo(&group_sid, &info)) {
+               return NT_STATUS_ACCESS_DENIED;
        }
 
        return NT_STATUS_OK;
@@ -4210,25 +4356,32 @@ NTSTATUS _samr_open_group(pipes_struct *p, SAMR_Q_OPEN_GROUP *q_u, SAMR_R_OPEN_G
        NTSTATUS          status;
        fstring sid_string;
        BOOL ret;
+       SE_PRIV se_rights;
 
        if (!get_lsa_policy_samr_sid(p, &q_u->domain_pol, &sid, &acc_granted)) 
                return NT_STATUS_INVALID_HANDLE;
        
-       if (!NT_STATUS_IS_OK(status = access_check_samr_function(acc_granted, SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_group"))) {
+       status = access_check_samr_function(acc_granted, 
+               SA_RIGHT_DOMAIN_OPEN_ACCOUNT, "_samr_open_group");
+               
+       if ( !NT_STATUS_IS_OK(status) )
                return status;
-       }
                
        /*check if access can be granted as requested by client. */
-       samr_make_grp_obj_sd(p->mem_ctx, &psd, &sd_size);
+       make_samr_object_sd(p->mem_ctx, &psd, &sd_size, &grp_generic_mapping, NULL, 0);
        se_map_generic(&des_access,&grp_generic_mapping);
-       if (!NT_STATUS_IS_OK(status = 
-                            access_check_samr_object(psd, p->pipe_user.nt_user_token, 
-                                                     des_access, &acc_granted, "_samr_open_group"))) {
-               return status;
-       }
 
+       se_priv_copy( &se_rights, &se_add_users );
+
+       status = access_check_samr_object(psd, p->pipe_user.nt_user_token, 
+               &se_rights, GENERIC_RIGHTS_GROUP_WRITE, des_access, 
+               &acc_granted, "_samr_open_group");
+               
+       if ( !NT_STATUS_IS_OK(status) ) 
+               return status;
 
        /* this should not be hard-coded like this */
+       
        if (!sid_equal(&sid, get_global_sam_sid()))
                return NT_STATUS_ACCESS_DENIED;
 
@@ -4391,7 +4544,7 @@ NTSTATUS _samr_unknown_2e(pipes_struct *p, SAMR_Q_UNKNOWN_2E *q_u, SAMR_R_UNKNOW
 
        uint32 account_policy_temp;
 
-       if ((ctr = (SAM_UNK_CTR *)talloc_zero(p->mem_ctx, sizeof(SAM_UNK_CTR))) == NULL)
+       if ((ctr = TALLOC_ZERO_P(p->mem_ctx, SAM_UNK_CTR)) == NULL)
                return NT_STATUS_NO_MEMORY;
 
        ZERO_STRUCTP(ctr);
@@ -4406,19 +4559,19 @@ NTSTATUS _samr_unknown_2e(pipes_struct *p, SAMR_Q_UNKNOWN_2E *q_u, SAMR_R_UNKNOW
 
        switch (q_u->switch_value) {
                case 0x01:
-                       account_policy_get(AP_MIN_PASSWORD_LEN, &account_policy_temp);
+                       pdb_get_account_policy(AP_MIN_PASSWORD_LEN, &account_policy_temp);
                        min_pass_len = account_policy_temp;
 
-                       account_policy_get(AP_PASSWORD_HISTORY, &account_policy_temp);
+                       pdb_get_account_policy(AP_PASSWORD_HISTORY, &account_policy_temp);
                        pass_hist = account_policy_temp;
 
-                       account_policy_get(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
+                       pdb_get_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, &account_policy_temp);
                        flag = account_policy_temp;
 
-                       account_policy_get(AP_MAX_PASSWORD_AGE, &account_policy_temp);
+                       pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &account_policy_temp);
                        u_expire = account_policy_temp;
 
-                       account_policy_get(AP_MIN_PASSWORD_AGE, &account_policy_temp);
+                       pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &account_policy_temp);
                        u_min_age = account_policy_temp;
 
                        unix_to_nt_time_abs(&nt_expire, u_expire);
@@ -4446,12 +4599,17 @@ NTSTATUS _samr_unknown_2e(pipes_struct *p, SAMR_Q_UNKNOWN_2E *q_u, SAMR_R_UNKNOW
                        num_groups=info->disp_info.num_group_account;
                        free_samr_db(info);
 
+                       pdb_get_account_policy(AP_TIME_TO_LOGOUT, &account_policy_temp);
+                       u_logout = account_policy_temp;
+
+                       unix_to_nt_time_abs(&nt_logout, u_logout);
+
                        /* The time call below is to get a sequence number for the sam. FIXME !!! JRA. */
-                       init_unk_info2(&ctr->info.inf2, lp_workgroup(), global_myname(), (uint32) time(NULL), 
-                                      num_users, num_groups, num_aliases);
+                       init_unk_info2(&ctr->info.inf2, "", lp_workgroup(), global_myname(), (uint32) time(NULL), 
+                                      num_users, num_groups, num_aliases, nt_logout);
                        break;
                case 0x03:
-                       account_policy_get(AP_TIME_TO_LOGOUT, &account_policy_temp);
+                       pdb_get_account_policy(AP_TIME_TO_LOGOUT, &account_policy_temp);
                        u_logout = account_policy_temp;
 
                        unix_to_nt_time_abs(&nt_logout, u_logout);
@@ -4467,14 +4625,19 @@ NTSTATUS _samr_unknown_2e(pipes_struct *p, SAMR_Q_UNKNOWN_2E *q_u, SAMR_R_UNKNOW
                case 0x07:
                        init_unk_info7(&ctr->info.inf7);
                        break;
+               case 0x08:
+                       init_unk_info8(&ctr->info.inf8, (uint32) time(NULL));
+                       break;
                case 0x0c:
-                       account_policy_get(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
+                       pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &account_policy_temp);
                        u_lock_duration = account_policy_temp;
+                       if (u_lock_duration != -1)
+                               u_lock_duration *= 60;
 
-                       account_policy_get(AP_RESET_COUNT_TIME, &account_policy_temp);
-                       u_reset_time = account_policy_temp;
+                       pdb_get_account_policy(AP_RESET_COUNT_TIME, &account_policy_temp);
+                       u_reset_time = account_policy_temp * 60;
 
-                       account_policy_get(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
+                       pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_temp);
                        lockout = account_policy_temp;
        
                        unix_to_nt_time_abs(&nt_lock_duration, u_lock_duration);
@@ -4518,17 +4681,17 @@ NTSTATUS _samr_set_dom_info(pipes_struct *p, SAMR_Q_SET_DOMAIN_INFO *q_u, SAMR_R
                        u_expire=nt_time_to_unix_abs(&q_u->ctr->info.inf1.expire);
                        u_min_age=nt_time_to_unix_abs(&q_u->ctr->info.inf1.min_passwordage);
                        
-                       account_policy_set(AP_MIN_PASSWORD_LEN, (uint32)q_u->ctr->info.inf1.min_length_password);
-                       account_policy_set(AP_PASSWORD_HISTORY, (uint32)q_u->ctr->info.inf1.password_history);
-                       account_policy_set(AP_USER_MUST_LOGON_TO_CHG_PASS, (uint32)q_u->ctr->info.inf1.flag);
-                       account_policy_set(AP_MAX_PASSWORD_AGE, (int)u_expire);
-                       account_policy_set(AP_MIN_PASSWORD_AGE, (int)u_min_age);
+                       pdb_set_account_policy(AP_MIN_PASSWORD_LEN, (uint32)q_u->ctr->info.inf1.min_length_password);
+                       pdb_set_account_policy(AP_PASSWORD_HISTORY, (uint32)q_u->ctr->info.inf1.password_history);
+                       pdb_set_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, (uint32)q_u->ctr->info.inf1.flag);
+                       pdb_set_account_policy(AP_MAX_PASSWORD_AGE, (int)u_expire);
+                       pdb_set_account_policy(AP_MIN_PASSWORD_AGE, (int)u_min_age);
                        break;
                case 0x02:
                        break;
                case 0x03:
                        u_logout=nt_time_to_unix_abs(&q_u->ctr->info.inf3.logout);
-                       account_policy_set(AP_TIME_TO_LOGOUT, (int)u_logout);
+                       pdb_set_account_policy(AP_TIME_TO_LOGOUT, (int)u_logout);
                        break;
                case 0x05:
                        break;
@@ -4537,12 +4700,15 @@ 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)/60;
+                       u_lock_duration=nt_time_to_unix_abs(&q_u->ctr->info.inf12.duration);
+                       if (u_lock_duration != -1)
+                               u_lock_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);
-                       account_policy_set(AP_BAD_ATTEMPT_LOCKOUT, (uint32)q_u->ctr->info.inf12.bad_attempt_lockout);
+                       pdb_set_account_policy(AP_LOCK_ACCOUNT_DURATION, (int)u_lock_duration);
+                       pdb_set_account_policy(AP_RESET_COUNT_TIME, (int)u_reset_time);
+                       pdb_set_account_policy(AP_BAD_ATTEMPT_LOCKOUT, (uint32)q_u->ctr->info.inf12.bad_attempt_lockout);
                        break;
                default:
                        return NT_STATUS_INVALID_INFO_CLASS;