r5264: Log with loglevel 0 when account-administration scripts fail.
[ira/wip.git] / source3 / utils / net_rpc_samsync.c
index 74607676729a2e2f253f3b7541bd1d8100a574e8..cc81719b6ab13a424cacf0f3d13238b7cc59fb99 100644 (file)
@@ -22,7 +22,7 @@
 */
 
 #include "includes.h"
-#include "../utils/net.h"
+#include "utils/net.h"
 
 extern DOM_SID global_sid_Builtin; 
 
@@ -36,6 +36,45 @@ static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
        d_printf("\n");
 }
 
+
+static const char *display_time(NTTIME *nttime)
+{
+       static fstring string;
+
+       float high;
+       float low;
+       int sec;
+       int days, hours, mins, secs;
+       int offset = 1;
+
+       if (nttime->high==0 && nttime->low==0)
+               return "Now";
+
+       if (nttime->high==0x80000000 && nttime->low==0)
+               return "Never";
+
+       high = 65536;   
+       high = high/10000;
+       high = high*65536;
+       high = high/1000;
+       high = high * (~nttime->high);
+
+       low = ~nttime->low;     
+       low = low/(1000*1000*10);
+
+       sec=high+low;
+       sec+=offset;
+
+       days=sec/(60*60*24);
+       hours=(sec - (days*60*60*24)) / (60*60);
+       mins=(sec - (days*60*60*24) - (hours*60*60) ) / 60;
+       secs=sec - (days*60*60*24) - (hours*60*60) - (mins*60);
+
+       fstr_sprintf(string, "%u days, %u hours, %u minutes, %u seconds", days, hours, mins, secs);
+       return (string);
+}
+
+
 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
 {
        d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
@@ -62,26 +101,44 @@ static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
        
        if (memcmp(a->pass.buf_lm_pwd, zero_buf, 16) != 0) {
                sam_pwd_hash(a->user_rid, a->pass.buf_lm_pwd, lm_passwd, 0);
-               smbpasswd_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
+               pdb_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
        } else {
-               smbpasswd_sethexpwd(hex_lm_passwd, NULL, 0);
+               pdb_sethexpwd(hex_lm_passwd, NULL, 0);
        }
 
        if (memcmp(a->pass.buf_nt_pwd, zero_buf, 16) != 0) {
                sam_pwd_hash(a->user_rid, a->pass.buf_nt_pwd, nt_passwd, 0);
-               smbpasswd_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
+               pdb_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
        } else {
-               smbpasswd_sethexpwd(hex_nt_passwd, NULL, 0);
+               pdb_sethexpwd(hex_nt_passwd, NULL, 0);
        }
        
        printf("%s:%d:%s:%s:%s:LCT-0\n", unistr2_static(&a->uni_acct_name),
               a->user_rid, hex_lm_passwd, hex_nt_passwd,
-              smbpasswd_encode_acb_info(a->acb_info));
+              pdb_encode_acct_ctrl(a->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN));
 }
 
 static void display_domain_info(SAM_DOMAIN_INFO *a)
 {
+       time_t u_logout;
+
+       u_logout = nt_time_to_unix_abs((NTTIME *)&a->force_logoff);
+
        d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
+
+       d_printf("Minimal Password Length: %d\n", a->min_pwd_len);
+       d_printf("Password History Length: %d\n", a->pwd_history_len);
+
+       d_printf("Force Logoff: %d\n", (int)u_logout);
+
+       d_printf("Max Password Age: %s\n", display_time((NTTIME *)&a->max_pwd_age));
+       d_printf("Min Password Age: %s\n", display_time((NTTIME *)&a->min_pwd_age));
+
+       d_printf("Lockout Time: %s\n", display_time((NTTIME *)&a->account_lockout.lockout_duration));
+       d_printf("Lockout Reset Time: %s\n", display_time((NTTIME *)&a->account_lockout.reset_count));
+
+       d_printf("Bad Attempt Lockout: %d\n", a->account_lockout.bad_attempt_lockout);
+       d_printf("User must logon to change password: %d\n", a->logon_chgpass);
 }
 
 static void display_group_info(uint32 rid, SAM_GROUP_INFO *a)
@@ -182,6 +239,9 @@ static void dump_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret
                result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds, db_type,
                                               sync_context,
                                               &num_deltas, &hdr_deltas, &deltas);
+               if (NT_STATUS_IS_ERR(result))
+                       break;
+
                clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), ret_creds);
                 for (i = 0; i < num_deltas; i++) {
                        display_sam_entry(&hdr_deltas[i], &deltas[i]);
@@ -193,35 +253,30 @@ static void dump_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret
 }
 
 /* dump sam database via samsync rpc calls */
-int rpc_samdump(int argc, const char **argv)
+NTSTATUS rpc_samdump_internals(const DOM_SID *domain_sid, 
+                              const char *domain_name, 
+                              struct cli_state *cli, TALLOC_CTX *mem_ctx, 
+                              int argc, const char **argv) 
 {
-        NTSTATUS result;
-       struct cli_state *cli = NULL;
+       NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
        uchar trust_password[16];
        DOM_CRED ret_creds;
-       uint32 neg_flags = 0x000001ff;
-
+       uint32 sec_channel;
 
        ZERO_STRUCT(ret_creds);
 
-       /* Connect to remote machine */
-       if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC))) {
-               return 1;
-       }
+       fstrcpy(cli->domain, domain_name);
 
-       if (!cli_nt_session_open(cli, PI_NETLOGON)) {
-               DEBUG(0,("Error connecting to NETLOGON pipe\n"));
+       if (!secrets_fetch_trust_account_password(domain_name,
+                                                 trust_password,
+                                                 NULL, &sec_channel)) {
+               DEBUG(0,("Could not fetch trust account password\n"));
                goto fail;
        }
 
-       if (!secrets_fetch_trust_account_password(lp_workgroup(), trust_password, NULL)) {
-               d_printf("Could not retrieve domain trust secret\n");
-               goto fail;
-       }
-       
-       result = cli_nt_setup_creds(cli, SEC_CHAN_BDC,  trust_password, &neg_flags, 2);
-       if (!NT_STATUS_IS_OK(result)) {
-               d_printf("Failed to setup BDC creds\n");
+       if (!NT_STATUS_IS_OK(nt_status = cli_nt_establish_netlogon(cli, sec_channel,
+                                                                  trust_password))) {
+               DEBUG(0,("Error connecting to NETLOGON pipe\n"));
                goto fail;
        }
 
@@ -229,15 +284,11 @@ int rpc_samdump(int argc, const char **argv)
        dump_database(cli, SAM_DATABASE_BUILTIN, &ret_creds);
        dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds);
 
-       cli_nt_session_close(cli);
-        
-        return 0;
+        nt_status = NT_STATUS_OK;
 
 fail:
-       if (cli) {
-               cli_nt_session_close(cli);
-       }
-       return -1;
+       cli_nt_session_close(cli);
+       return nt_status;
 }
 
 /* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
@@ -328,6 +379,17 @@ sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
                        pdb_set_profile_path(account, new_string, PDB_CHANGED);
        }
 
+       if (delta->hdr_parameters.buffer) {
+               DATA_BLOB mung;
+               old_string = pdb_get_munged_dial(account);
+               mung.length = delta->hdr_parameters.uni_str_len;
+               mung.data = (uint8 *) delta->uni_parameters.buffer;
+               new_string = (mung.length == 0) ? NULL : base64_encode_data_blob(mung);
+
+               if (STRING_CHANGED)
+                       pdb_set_munged_dial(account, new_string, PDB_CHANGED);
+       }
+
        /* User and group sid */
        if (pdb_get_user_rid(account) != delta->user_rid)
                pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
@@ -349,18 +411,43 @@ sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
                        pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
        }
 
+       /* Logon Divs */
        if (pdb_get_logon_divs(account) != delta->logon_divs)
                pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
 
-       /* TODO: logon hours */
-       /* TODO: bad password count */
-       /* TODO: logon count */
+       /* Max Logon Hours */
+       if (delta->unknown1 != pdb_get_unknown_6(account)) {
+               pdb_set_unknown_6(account, delta->unknown1, PDB_CHANGED);
+       }
+
+       /* Logon Hours Len */
+       if (delta->buf_logon_hrs.buf_len != pdb_get_hours_len(account)) {
+               pdb_set_hours_len(account, delta->buf_logon_hrs.buf_len, PDB_CHANGED);
+       }
+
+       /* Logon Hours */
+       if (delta->buf_logon_hrs.buffer) {
+               pstring old, new;
+               pdb_sethexhours(old, pdb_get_hours(account));
+               pdb_sethexhours(new, (const char *)delta->buf_logon_hrs.buffer);
+               if (!strequal(old, new))
+                       pdb_set_hours(account, (const char *)delta->buf_logon_hrs.buffer, PDB_CHANGED);
+       }
+
+       if (pdb_get_bad_password_count(account) != delta->bad_pwd_count)
+               pdb_set_bad_password_count(account, delta->bad_pwd_count, PDB_CHANGED);
+
+       if (pdb_get_logon_count(account) != delta->logon_count)
+               pdb_set_logon_count(account, delta->logon_count, PDB_CHANGED);
 
        if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
                unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
                stored_time = pdb_get_pass_last_set_time(account);
                if (stored_time != unix_time)
                        pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
+       } else {
+               /* no last set time, make it now */
+               pdb_set_pass_last_set_time(account, time(NULL), PDB_CHANGED);
        }
 
 #if 0
@@ -393,11 +480,12 @@ sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
        if (pdb_get_acct_ctrl(account) != delta->acb_info)
                pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
 
+       pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
+
        return NT_STATUS_OK;
 }
 
-static NTSTATUS
-fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
+static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
 {
        NTSTATUS nt_ret;
        fstring account;
@@ -405,8 +493,10 @@ fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
        SAM_ACCOUNT *sam_account=NULL;
        GROUP_MAP map;
        struct group *grp;
-       DOM_SID sid;
-       BOOL try_add = False;
+       DOM_SID user_sid;
+       DOM_SID group_sid;
+       struct passwd *passwd;
+       fstring sid_string;
 
        fstrcpy(account, unistr2_static(&delta->uni_acct_name));
        d_printf("Creating account: %s\n", account);
@@ -414,7 +504,7 @@ fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
        if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
                return nt_ret;
 
-       if (!pdb_getsampwnam(sam_account, account)) {
+       if (!(passwd = Get_Pwnam(account))) {
                /* Create appropriate user */
                if (delta->acb_info & ACB_NORMAL) {
                        pstrcpy(add_script, lp_adduser_script());
@@ -424,56 +514,82 @@ fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
                        pstrcpy(add_script, lp_addmachine_script());
                } else {
                        DEBUG(1, ("Unknown user type: %s\n",
-                                 smbpasswd_encode_acb_info(delta->acb_info)));
-                       pdb_free_sam(&sam_account);
-                       return NT_STATUS_NO_SUCH_USER;
+                                 pdb_encode_acct_ctrl(delta->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
+                       nt_ret = NT_STATUS_UNSUCCESSFUL;
+                       goto done;
                }
                if (*add_script) {
                        int add_ret;
                        all_string_sub(add_script, "%u", account,
                                       sizeof(account));
                        add_ret = smbrun(add_script,NULL);
-                       DEBUG(1,("fetch_account: Running the command `%s' "
+                       DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
                                 "gave %d\n", add_script, add_ret));
+               } else {
+                       DEBUG(8,("fetch_account_info: no add user/machine script.  Asking winbindd\n"));
+                       
+                       /* don't need a RID allocated since the user already has a SID */
+                       if ( !winbind_create_user( account, NULL ) )
+                               DEBUG(4,("fetch_account_info: winbind_create_user() failed\n"));
+               }
+               
+               /* try and find the possible unix account again */
+               if ( !(passwd = Get_Pwnam(account)) ) {
+                       d_printf("Could not create posix account info for '%s'\n", account);
+                       nt_ret = NT_STATUS_NO_SUCH_USER;
+                       goto done;
                }
-
-               try_add = True;
        }
-
-       sam_account_from_delta(sam_account, delta);
-
-       if (try_add) { 
+       
+       sid_copy(&user_sid, get_global_sam_sid());
+       sid_append_rid(&user_sid, delta->user_rid);
+
+       DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n", sid_to_string(sid_string, &user_sid), account));
+       if (!pdb_getsampwsid(sam_account, &user_sid)) {
+               sam_account_from_delta(sam_account, delta);
+               DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
+                         sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
                if (!pdb_add_sam_account(sam_account)) {
                        DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
                                  account));
+                       return NT_STATUS_ACCESS_DENIED; 
                }
        } else {
+               sam_account_from_delta(sam_account, delta);
+               DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
+                         sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
                if (!pdb_update_sam_account(sam_account)) {
                        DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
                                  account));
+                       pdb_free_sam(&sam_account);
+                       return NT_STATUS_ACCESS_DENIED; 
                }
        }
 
-       sid = *pdb_get_group_sid(sam_account);
+       group_sid = *pdb_get_group_sid(sam_account);
 
-       if (!pdb_getgrsid(&map, sid, False)) {
+       if (!pdb_getgrsid(&map, group_sid)) {
                DEBUG(0, ("Primary group of %s has no mapping!\n",
                          pdb_get_username(sam_account)));
-               pdb_free_sam(&sam_account);
-               return NT_STATUS_NO_SUCH_GROUP;
-       }
+       } else {
+               if (map.gid != passwd->pw_gid) {
+                       if (!(grp = getgrgid(map.gid))) {
+                               DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
+                                         (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_static(&group_sid)));
+                       } else {
+                               smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
+                       }
+               }
+       }       
 
-       if (!(grp = getgrgid(map.gid))) {
-               DEBUG(0, ("Could not find unix group %d for user %s (group SID=%s)\n", 
-                         map.gid, pdb_get_username(sam_account), sid_string_static(&sid)));
-               pdb_free_sam(&sam_account);
-               return NT_STATUS_NO_SUCH_GROUP;
+       if ( !passwd ) {
+               DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
+                       pdb_get_username(sam_account)));
        }
 
-       smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
-
+ done:
        pdb_free_sam(&sam_account);
-       return NT_STATUS_OK;
+       return nt_ret;
 }
 
 static NTSTATUS
@@ -495,22 +611,26 @@ fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
        sid_append_rid(&group_sid, rid);
        sid_to_string(sid_string, &group_sid);
 
-       if (pdb_getgrsid(&map, group_sid, False)) {
-               grp = getgrgid(map.gid);
+       if (pdb_getgrsid(&map, group_sid)) {
+               if ( map.gid != -1 )
+                       grp = getgrgid(map.gid);
                insert = False;
        }
 
-       if (grp == NULL)
-       {
+       if (grp == NULL) {
                gid_t gid;
 
                /* No group found from mapping, find it from its name. */
                if ((grp = getgrnam(name)) == NULL) {
+               
                        /* No appropriate group found, create one */
+                       
                        d_printf("Creating unix group: '%s'\n", name);
+                       
                        if (smb_create_group(name, &gid) != 0)
                                return NT_STATUS_ACCESS_DENIED;
-                       if ((grp = getgrgid(gid)) == NULL)
+                               
+                       if ((grp = getgrnam(name)) == NULL)
                                return NT_STATUS_ACCESS_DENIED;
                }
        }
@@ -519,10 +639,11 @@ fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
        map.sid = group_sid;
        map.sid_name_use = SID_NAME_DOM_GRP;
        fstrcpy(map.nt_name, name);
-       fstrcpy(map.comment, comment);
-
-       map.priv_set.count = 0;
-       map.priv_set.set = NULL;
+       if (delta->hdr_grp_desc.buffer) {
+               fstrcpy(map.comment, comment);
+       } else {
+               fstrcpy(map.comment, "");
+       }
 
        if (insert)
                pdb_add_group_mapping_entry(&map);
@@ -550,13 +671,13 @@ fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
        sid_copy(&group_sid, get_global_sam_sid());
        sid_append_rid(&group_sid, rid);
 
-       if (!get_domain_group_from_sid(group_sid, &map, False)) {
+       if (!get_domain_group_from_sid(group_sid, &map)) {
                DEBUG(0, ("Could not find global group %d\n", rid));
                return NT_STATUS_NO_SUCH_GROUP;
        }
 
        if (!(grp = getgrgid(map.gid))) {
-               DEBUG(0, ("Could not find unix group %d\n", map.gid));
+               DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
                return NT_STATUS_NO_SUCH_GROUP;
        }
 
@@ -567,7 +688,7 @@ fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
                return NT_STATUS_NO_MEMORY;
        }
 
-       nt_members = talloc_zero(t, sizeof(char *) * delta->num_members);
+       nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
 
        for (i=0; i<delta->num_members; i++) {
                NTSTATUS nt_status;
@@ -675,7 +796,7 @@ static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
        sid_append_rid(&alias_sid, rid);
        sid_to_string(sid_string, &alias_sid);
 
-       if (pdb_getgrsid(&map, alias_sid, False)) {
+       if (pdb_getgrsid(&map, alias_sid)) {
                grp = getgrgid(map.gid);
                insert = False;
        }
@@ -705,9 +826,6 @@ static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
        fstrcpy(map.nt_name, name);
        fstrcpy(map.comment, comment);
 
-       map.priv_set.count = 0;
-       map.priv_set.set = NULL;
-
        if (insert)
                pdb_add_group_mapping_entry(&map);
        else
@@ -719,10 +837,203 @@ static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
 static NTSTATUS
 fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
 {
+#if 0  /* 
+        * commented out right now after talking to Volker.  Can't
+        * do much with the membership but seemed a shame to waste
+        * somewhat working code.  Needs testing because the membership
+        * that shows up surprises me.  Also can't do much with groups
+        * in groups (e.g. Domain Admins being a member of Adminsitrators).
+        * --jerry
+        */
+       
+       int i;
+       TALLOC_CTX *t = NULL;
+       char **nt_members = NULL;
+       char **unix_members;
+       DOM_SID group_sid;
+       GROUP_MAP map;
+       struct group *grp;
+       enum SID_NAME_USE sid_type;
+
+       if (delta->num_members == 0) {
+               return NT_STATUS_OK;
+       }
+
+       sid_copy(&group_sid, &dom_sid);
+       sid_append_rid(&group_sid, rid);
+
+       if (sid_equal(&dom_sid, &global_sid_Builtin)) {
+               sid_type = SID_NAME_WKN_GRP;
+               if (!get_builtin_group_from_sid(&group_sid, &map, False)) {
+                       DEBUG(0, ("Could not find builtin group %s\n", sid_string_static(&group_sid)));
+                       return NT_STATUS_NO_SUCH_GROUP;
+               }
+       } else {
+               sid_type = SID_NAME_ALIAS;
+               if (!get_local_group_from_sid(&group_sid, &map, False)) {
+                       DEBUG(0, ("Could not find local group %s\n", sid_string_static(&group_sid)));
+                       return NT_STATUS_NO_SUCH_GROUP;
+               }
+       }       
+
+       if (!(grp = getgrgid(map.gid))) {
+               DEBUG(0, ("Could not find unix group %d\n", map.gid));
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       d_printf("Group members of %s: ", grp->gr_name);
+
+       if (!(t = talloc_init("fetch_group_mem_info"))) {
+               DEBUG(0, ("could not talloc_init\n"));
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
+
+       for (i=0; i<delta->num_members; i++) {
+               NTSTATUS nt_status;
+               SAM_ACCOUNT *member = NULL;
+               DOM_SID member_sid;
+
+               if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
+                       talloc_destroy(t);
+                       return nt_status;
+               }
+
+               sid_copy(&member_sid, &delta->sids[i].sid);
+
+               if (!pdb_getsampwsid(member, &member_sid)) {
+                       DEBUG(1, ("Found bogus group member: (member_sid=%s group=%s)\n",
+                                 sid_string_static(&member_sid), grp->gr_name));
+                       pdb_free_sam(&member);
+                       continue;
+               }
+
+               if (pdb_get_group_rid(member) == rid) {
+                       d_printf("%s(primary),", pdb_get_username(member));
+                       pdb_free_sam(&member);
+                       continue;
+               }
+               
+               d_printf("%s,", pdb_get_username(member));
+               nt_members[i] = talloc_strdup(t, pdb_get_username(member));
+               pdb_free_sam(&member);
+       }
+
+       d_printf("\n");
+
+       unix_members = grp->gr_mem;
+
+       while (*unix_members) {
+               BOOL is_nt_member = False;
+               for (i=0; i<delta->num_members; i++) {
+                       if (nt_members[i] == NULL) {
+                               /* This was a primary group */
+                               continue;
+                       }
+
+                       if (strcmp(*unix_members, nt_members[i]) == 0) {
+                               is_nt_member = True;
+                               break;
+                       }
+               }
+               if (!is_nt_member) {
+                       /* We look at a unix group member that is not
+                          an nt group member. So, remove it. NT is
+                          boss here. */
+                       smb_delete_user_group(grp->gr_name, *unix_members);
+               }
+               unix_members += 1;
+       }
+
+       for (i=0; i<delta->num_members; i++) {
+               BOOL is_unix_member = False;
+
+               if (nt_members[i] == NULL) {
+                       /* This was the primary group */
+                       continue;
+               }
+
+               unix_members = grp->gr_mem;
+
+               while (*unix_members) {
+                       if (strcmp(*unix_members, nt_members[i]) == 0) {
+                               is_unix_member = True;
+                               break;
+                       }
+                       unix_members += 1;
+               }
+
+               if (!is_unix_member) {
+                       /* We look at a nt group member that is not a
+                           unix group member currently. So, add the nt
+                           group member. */
+                       smb_add_user_group(grp->gr_name, nt_members[i]);
+               }
+       }
        
+       talloc_destroy(t);
+
+#endif /* end of fetch_alias_mem() */
+
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
+{
+       time_t u_max_age, u_min_age, u_logout, u_lockoutreset, u_lockouttime;
+       NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
+       pstring domname;
+
+       u_max_age = nt_time_to_unix_abs((NTTIME *)&delta->max_pwd_age);
+       u_min_age = nt_time_to_unix_abs((NTTIME *)&delta->min_pwd_age);
+       u_logout = nt_time_to_unix_abs((NTTIME *)&delta->force_logoff);
+       u_lockoutreset = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.reset_count);
+       u_lockouttime = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.lockout_duration);
+
+       unistr2_to_ascii(domname, &delta->uni_dom_name, sizeof(domname) - 1);
+
+       /* we don't handle BUILTIN account policies */  
+       if (!strequal(domname, get_global_sam_name())) {
+               printf("skipping SAM_DOMAIN_INFO delta for '%s' (is not my domain)\n", domname);
+               return NT_STATUS_OK;
+       }
+
+
+       if (!pdb_set_account_policy(AP_PASSWORD_HISTORY, delta->pwd_history_len))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_MIN_PASSWORD_LEN, delta->min_pwd_len))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_MAX_PASSWORD_AGE, (uint32)u_max_age))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_MIN_PASSWORD_AGE, (uint32)u_min_age))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_TIME_TO_LOGOUT, (uint32)u_logout))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_BAD_ATTEMPT_LOCKOUT, delta->account_lockout.bad_attempt_lockout))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_RESET_COUNT_TIME, (uint32)u_lockoutreset/60))
+               return nt_status;
+
+       if (u_lockouttime != -1)
+               u_lockouttime /= 60;
+
+       if (!pdb_set_account_policy(AP_LOCK_ACCOUNT_DURATION, (uint32)u_lockouttime))
+               return nt_status;
+
+       if (!pdb_set_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, delta->logon_chgpass))
+               return nt_status;
+
        return NT_STATUS_OK;
 }
 
+
 static void
 fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
                DOM_SID dom_sid)
@@ -748,13 +1059,48 @@ fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
                fetch_alias_mem(hdr_delta->target_rid,
                                &delta->als_mem_info, dom_sid);
                break;
+       case SAM_DELTA_DOMAIN_INFO:
+               fetch_domain_info(hdr_delta->target_rid,
+                               &delta->domain_info);
+               break;
+       /* The following types are recognised but not handled */
+       case SAM_DELTA_RENAME_GROUP:
+               d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
+               break;
+       case SAM_DELTA_RENAME_USER:
+               d_printf("SAM_DELTA_RENAME_USER not handled\n");
+               break;
+       case SAM_DELTA_RENAME_ALIAS:
+               d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
+               break;
+       case SAM_DELTA_POLICY_INFO:
+               d_printf("SAM_DELTA_POLICY_INFO not handled\n");
+               break;
+       case SAM_DELTA_TRUST_DOMS:
+               d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
+               break;
+       case SAM_DELTA_PRIVS_INFO:
+               d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
+               break;
+       case SAM_DELTA_SECRET_INFO:
+               d_printf("SAM_DELTA_SECRET_INFO not handled\n");
+               break;
+       case SAM_DELTA_DELETE_GROUP:
+               d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
+               break;
+       case SAM_DELTA_DELETE_USER:
+               d_printf("SAM_DELTA_DELETE_USER not handled\n");
+               break;
+       case SAM_DELTA_MODIFIED_COUNT:
+               d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
+               break;
        default:
                d_printf("Unknown delta record type %d\n", hdr_delta->type);
                break;
        }
 }
 
-static void
+static NTSTATUS
 fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
               DOM_SID dom_sid)
 {
@@ -766,80 +1112,118 @@ fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
         SAM_DELTA_CTR *deltas;
         uint32 num_deltas;
 
-       if (!(mem_ctx = talloc_init("fetch_database"))) {
-               return;
-       }
+       if (!(mem_ctx = talloc_init("fetch_database")))
+               return NT_STATUS_NO_MEMORY;
 
-       d_printf("Fetching database %u\n", db_type);
+       switch( db_type ) {
+       case SAM_DATABASE_DOMAIN:
+               d_printf("Fetching DOMAIN database\n");
+               break;
+       case SAM_DATABASE_BUILTIN:
+               d_printf("Fetching BUILTIN database\n");
+               break;
+       case SAM_DATABASE_PRIVS:
+               d_printf("Fetching PRIVS databases\n");
+               break;
+       default:
+               d_printf("Fetching unknown database type %u\n", db_type );
+               break;
+       }
 
        do {
                result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
                                               db_type, sync_context,
                                               &num_deltas,
                                               &hdr_deltas, &deltas);
-               clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
-                                    ret_creds);
-                for (i = 0; i < num_deltas; i++) {
-                       fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
-                }
+
+               if (NT_STATUS_IS_OK(result) ||
+                   NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
+
+                       clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
+                                            ret_creds);
+
+                       for (i = 0; i < num_deltas; i++) {
+                               fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
+                       }
+               } else
+                       return result;
+
                sync_context += 1;
        } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
 
        talloc_destroy(mem_ctx);
+
+       return result;
 }
 
 /* dump sam database via samsync rpc calls */
-int rpc_vampire(int argc, const char **argv)
+NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
+                              const char *domain_name, 
+                              struct cli_state *cli, TALLOC_CTX *mem_ctx, 
+                              int argc, const char **argv) 
 {
         NTSTATUS result;
-       struct cli_state *cli = NULL;
        uchar trust_password[16];
        DOM_CRED ret_creds;
-       uint32 neg_flags = 0x000001ff;
-       DOM_SID dom_sid;
+       fstring my_dom_sid_str;
+       fstring rem_dom_sid_str;
+       uint32 sec_channel;
 
        ZERO_STRUCT(ret_creds);
 
-       /* Connect to remote machine */
-       if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS |
-                                           NET_FLAGS_PDC))) {
-               return 1;
+       if (!sid_equal(domain_sid, get_global_sam_sid())) {
+               d_printf("Cannot import users from %s at this time, "
+                        "as the current domain:\n\t%s: %s\nconflicts "
+                        "with the remote domain\n\t%s: %s\n"
+                        "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
+                        domain_name,
+                        get_global_sam_name(), sid_to_string(my_dom_sid_str, 
+                                                             get_global_sam_sid()),
+                        domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
+                        domain_name);
+               return NT_STATUS_UNSUCCESSFUL;
        }
 
-       if (!cli_nt_session_open(cli, PI_NETLOGON)) {
-               DEBUG(0,("Error connecting to NETLOGON pipe\n"));
-               goto fail;
-       }
+       fstrcpy(cli->domain, domain_name);
 
-       if (!secrets_fetch_trust_account_password(lp_workgroup(),
-                                                 trust_password, NULL)) {
+       if (!secrets_fetch_trust_account_password(domain_name,
+                                                 trust_password, NULL,
+                                                 &sec_channel)) {
+               result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
                d_printf("Could not retrieve domain trust secret\n");
                goto fail;
        }
        
-       result = cli_nt_setup_creds(cli, SEC_CHAN_BDC,  trust_password,
-                                   &neg_flags, 2);
+       result = cli_nt_establish_netlogon(cli, sec_channel, trust_password);
+
        if (!NT_STATUS_IS_OK(result)) {
                d_printf("Failed to setup BDC creds\n");
                goto fail;
        }
 
-       dom_sid = *get_global_sam_sid();
-       fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds, dom_sid);
+       result = fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds, *domain_sid);
 
-       sid_copy(&dom_sid, &global_sid_Builtin);
-       fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, dom_sid);
+       if (!NT_STATUS_IS_OK(result)) {
+               d_printf("Failed to fetch domain database: %s\n",
+                        nt_errstr(result));
+               if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
+                       d_printf("Perhaps %s is a Windows 2000 native mode "
+                                "domain?\n", domain_name);
+               goto fail;
+       }
+
+       result = fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, 
+                               global_sid_Builtin);
+
+       if (!NT_STATUS_IS_OK(result)) {
+               d_printf("Failed to fetch builtin database: %s\n",
+                        nt_errstr(result));
+               goto fail;
+       }
 
        /* Currently we crash on PRIVS somewhere in unmarshalling */
        /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
 
-       cli_nt_session_close(cli);
-        
-        return 0;
-
 fail:
-       if (cli) {
-               cli_nt_session_close(cli);
-       }
-       return -1;
+       return result;
 }