This is the netlogon schannel client code. Try a
[sfrench/samba-autobuild/.git] / source3 / utils / net_rpc_samsync.c
1 /* 
2    Unix SMB/CIFS implementation.
3    dump the remote SAM using rpc samsync operations
4
5    Copyright (C) Andrew Tridgell 2002
6    Copyright (C) Tim Potter 2001,2002
7    Modified by Volker Lendecke 2002
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "../utils/net.h"
26
27 extern DOM_SID global_sid_Builtin; 
28
29 static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
30 {
31         int i;
32         d_printf("Group mem %u: ", rid);
33         for (i=0;i<g->num_members;i++) {
34                 d_printf("%u ", g->rids[i]);
35         }
36         d_printf("\n");
37 }
38
39 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
40 {
41         d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
42         d_printf("desc='%s' rid=%u\n", unistr2_static(&a->uni_als_desc), a->als_rid);
43 }
44
45 static void display_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *a)
46 {
47         int i;
48         d_printf("Alias rid %u: ", rid);
49         for (i=0;i<a->num_members;i++) {
50                 d_printf("%s ", sid_string_static(&a->sids[i].sid));
51         }
52         d_printf("\n");
53 }
54
55 static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
56 {
57         fstring hex_nt_passwd, hex_lm_passwd;
58         uchar lm_passwd[16], nt_passwd[16];
59         static uchar zero_buf[16];
60
61         /* Decode hashes from password hash (if they are not NULL) */
62         
63         if (memcmp(a->pass.buf_lm_pwd, zero_buf, 16) != 0) {
64                 sam_pwd_hash(a->user_rid, a->pass.buf_lm_pwd, lm_passwd, 0);
65                 smbpasswd_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
66         } else {
67                 smbpasswd_sethexpwd(hex_lm_passwd, NULL, 0);
68         }
69
70         if (memcmp(a->pass.buf_nt_pwd, zero_buf, 16) != 0) {
71                 sam_pwd_hash(a->user_rid, a->pass.buf_nt_pwd, nt_passwd, 0);
72                 smbpasswd_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
73         } else {
74                 smbpasswd_sethexpwd(hex_nt_passwd, NULL, 0);
75         }
76         
77         printf("%s:%d:%s:%s:%s:LCT-0\n", unistr2_static(&a->uni_acct_name),
78                a->user_rid, hex_lm_passwd, hex_nt_passwd,
79                smbpasswd_encode_acb_info(a->acb_info));
80 }
81
82 static void display_domain_info(SAM_DOMAIN_INFO *a)
83 {
84         d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
85 }
86
87 static void display_group_info(uint32 rid, SAM_GROUP_INFO *a)
88 {
89         d_printf("Group '%s' ", unistr2_static(&a->uni_grp_name));
90         d_printf("desc='%s', rid=%u\n", unistr2_static(&a->uni_grp_desc), rid);
91 }
92
93 static void display_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta)
94 {
95         switch (hdr_delta->type) {
96         case SAM_DELTA_ACCOUNT_INFO:
97                 display_account_info(hdr_delta->target_rid, &delta->account_info);
98                 break;
99         case SAM_DELTA_GROUP_MEM:
100                 display_group_mem_info(hdr_delta->target_rid, &delta->grp_mem_info);
101                 break;
102         case SAM_DELTA_ALIAS_INFO:
103                 display_alias_info(hdr_delta->target_rid, &delta->alias_info);
104                 break;
105         case SAM_DELTA_ALIAS_MEM:
106                 display_alias_mem(hdr_delta->target_rid, &delta->als_mem_info);
107                 break;
108         case SAM_DELTA_DOMAIN_INFO:
109                 display_domain_info(&delta->domain_info);
110                 break;
111         case SAM_DELTA_GROUP_INFO:
112                 display_group_info(hdr_delta->target_rid, &delta->group_info);
113                 break;
114                 /* The following types are recognised but not handled */
115         case SAM_DELTA_RENAME_GROUP:
116                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
117                 break;
118         case SAM_DELTA_RENAME_USER:
119                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
120                 break;
121         case SAM_DELTA_RENAME_ALIAS:
122                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
123                 break;
124         case SAM_DELTA_POLICY_INFO:
125                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
126                 break;
127         case SAM_DELTA_TRUST_DOMS:
128                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
129                 break;
130         case SAM_DELTA_PRIVS_INFO:
131                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
132                 break;
133         case SAM_DELTA_SECRET_INFO:
134                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
135                 break;
136         case SAM_DELTA_DELETE_GROUP:
137                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
138                 break;
139         case SAM_DELTA_DELETE_USER:
140                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
141                 break;
142         case SAM_DELTA_MODIFIED_COUNT:
143                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
144                 break;
145         default:
146                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
147                 break;
148         }
149 }
150
151
152 static void dump_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds)
153 {
154         unsigned sync_context = 0;
155         NTSTATUS result;
156         int i;
157         TALLOC_CTX *mem_ctx;
158         SAM_DELTA_HDR *hdr_deltas;
159         SAM_DELTA_CTR *deltas;
160         uint32 num_deltas;
161
162         if (!(mem_ctx = talloc_init("dump_database"))) {
163                 return;
164         }
165
166         switch( db_type ) {
167         case SAM_DATABASE_DOMAIN:
168                 d_printf("Dumping DOMAIN database\n");
169                 break;
170         case SAM_DATABASE_BUILTIN:
171                 d_printf("Dumping BUILTIN database\n");
172                 break;
173         case SAM_DATABASE_PRIVS:
174                 d_printf("Dumping PRIVS databases\n");
175                 break;
176         default:
177                 d_printf("Dumping unknown database type %u\n", db_type );
178                 break;
179         }
180
181         do {
182                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds, db_type,
183                                                sync_context,
184                                                &num_deltas, &hdr_deltas, &deltas);
185                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), ret_creds);
186                 for (i = 0; i < num_deltas; i++) {
187                         display_sam_entry(&hdr_deltas[i], &deltas[i]);
188                 }
189                 sync_context += 1;
190         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
191
192         talloc_destroy(mem_ctx);
193 }
194
195 /* dump sam database via samsync rpc calls */
196 int rpc_samdump(int argc, const char **argv)
197 {
198         NTSTATUS result;
199         struct cli_state *cli = NULL;
200         uchar trust_password[16];
201         DOM_CRED ret_creds;
202         uint32 neg_flags = 0x000001ff;
203
204
205         ZERO_STRUCT(ret_creds);
206
207         /* Connect to remote machine */
208         if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC))) {
209                 return 1;
210         }
211
212         fstrcpy(cli->domain, lp_workgroup());
213
214         if (!secrets_fetch_trust_account_password(lp_workgroup(),
215                                                   trust_password,
216                                                   NULL)) {
217                 DEBUG(0,("Could not fetch trust account password\n"));
218                 goto fail;
219         }
220
221         if (!cli_nt_open_netlogon(cli, trust_password, SEC_CHAN_BDC)) {
222                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
223                 goto fail;
224         }
225
226         dump_database(cli, SAM_DATABASE_DOMAIN, &ret_creds);
227         dump_database(cli, SAM_DATABASE_BUILTIN, &ret_creds);
228         dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds);
229
230         cli_nt_session_close(cli);
231         
232         return 0;
233
234 fail:
235         if (cli) {
236                 cli_nt_session_close(cli);
237         }
238         return -1;
239 }
240
241 /* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
242 #define STRING_CHANGED (old_string && !new_string) ||\
243                     (!old_string && new_string) ||\
244                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
245
246 static NTSTATUS
247 sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
248 {
249         const char *old_string, *new_string;
250         time_t unix_time, stored_time;
251         uchar lm_passwd[16], nt_passwd[16];
252         static uchar zero_buf[16];
253
254         /* Username, fullname, home dir, dir drive, logon script, acct
255            desc, workstations, profile. */
256
257         if (delta->hdr_acct_name.buffer) {
258                 old_string = pdb_get_nt_username(account);
259                 new_string = unistr2_static(&delta->uni_acct_name);
260
261                 if (STRING_CHANGED) {
262                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
263               
264                 }
265          
266                 /* Unix username is the same - for sanity */
267                 old_string = pdb_get_username( account );
268                 if (STRING_CHANGED) {
269                         pdb_set_username(account, new_string, PDB_CHANGED);
270                 }
271         }
272
273         if (delta->hdr_full_name.buffer) {
274                 old_string = pdb_get_fullname(account);
275                 new_string = unistr2_static(&delta->uni_full_name);
276
277                 if (STRING_CHANGED)
278                         pdb_set_fullname(account, new_string, PDB_CHANGED);
279         }
280
281         if (delta->hdr_home_dir.buffer) {
282                 old_string = pdb_get_homedir(account);
283                 new_string = unistr2_static(&delta->uni_home_dir);
284
285                 if (STRING_CHANGED)
286                         pdb_set_homedir(account, new_string, PDB_CHANGED);
287         }
288
289         if (delta->hdr_dir_drive.buffer) {
290                 old_string = pdb_get_dir_drive(account);
291                 new_string = unistr2_static(&delta->uni_dir_drive);
292
293                 if (STRING_CHANGED)
294                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
295         }
296
297         if (delta->hdr_logon_script.buffer) {
298                 old_string = pdb_get_logon_script(account);
299                 new_string = unistr2_static(&delta->uni_logon_script);
300
301                 if (STRING_CHANGED)
302                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
303         }
304
305         if (delta->hdr_acct_desc.buffer) {
306                 old_string = pdb_get_acct_desc(account);
307                 new_string = unistr2_static(&delta->uni_acct_desc);
308
309                 if (STRING_CHANGED)
310                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
311         }
312
313         if (delta->hdr_workstations.buffer) {
314                 old_string = pdb_get_workstations(account);
315                 new_string = unistr2_static(&delta->uni_workstations);
316
317                 if (STRING_CHANGED)
318                         pdb_set_workstations(account, new_string, PDB_CHANGED);
319         }
320
321         if (delta->hdr_profile.buffer) {
322                 old_string = pdb_get_profile_path(account);
323                 new_string = unistr2_static(&delta->uni_profile);
324
325                 if (STRING_CHANGED)
326                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
327         }
328
329         /* User and group sid */
330         if (pdb_get_user_rid(account) != delta->user_rid)
331                 pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
332         if (pdb_get_group_rid(account) != delta->group_rid)
333                 pdb_set_group_sid_from_rid(account, delta->group_rid, PDB_CHANGED);
334
335         /* Logon and password information */
336         if (!nt_time_is_zero(&delta->logon_time)) {
337                 unix_time = nt_time_to_unix(&delta->logon_time);
338                 stored_time = pdb_get_logon_time(account);
339                 if (stored_time != unix_time)
340                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
341         }
342
343         if (!nt_time_is_zero(&delta->logoff_time)) {
344                 unix_time = nt_time_to_unix(&delta->logoff_time);
345                 stored_time = pdb_get_logoff_time(account);
346                 if (stored_time != unix_time)
347                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
348         }
349
350         if (pdb_get_logon_divs(account) != delta->logon_divs)
351                 pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
352
353         /* TODO: logon hours */
354         /* TODO: bad password count */
355         /* TODO: logon count */
356
357         if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
358                 unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
359                 stored_time = pdb_get_pass_last_set_time(account);
360                 if (stored_time != unix_time)
361                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
362         }
363
364 #if 0
365 /*      No kickoff time in the delta? */
366         if (!nt_time_is_zero(&delta->kickoff_time)) {
367                 unix_time = nt_time_to_unix(&delta->kickoff_time);
368                 stored_time = pdb_get_kickoff_time(account);
369                 if (stored_time != unix_time)
370                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
371         }
372 #endif
373
374         /* Decode hashes from password hash 
375            Note that win2000 may send us all zeros for the hashes if it doesn't 
376            think this channel is secure enough - don't set the passwords at all
377            in that case
378         */
379         if (memcmp(delta->pass.buf_lm_pwd, zero_buf, 16) != 0) {
380                 sam_pwd_hash(delta->user_rid, delta->pass.buf_lm_pwd, lm_passwd, 0);
381                 pdb_set_lanman_passwd(account, lm_passwd, PDB_CHANGED);
382         }
383
384         if (memcmp(delta->pass.buf_nt_pwd, zero_buf, 16) != 0) {
385                 sam_pwd_hash(delta->user_rid, delta->pass.buf_nt_pwd, nt_passwd, 0);
386                 pdb_set_nt_passwd(account, nt_passwd, PDB_CHANGED);
387         }
388
389         /* TODO: account expiry time */
390
391         if (pdb_get_acct_ctrl(account) != delta->acb_info)
392                 pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
393
394         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
395
396         return NT_STATUS_OK;
397 }
398
399 static NTSTATUS
400 fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
401 {
402         NTSTATUS nt_ret;
403         fstring account;
404         pstring add_script;
405         SAM_ACCOUNT *sam_account=NULL;
406         GROUP_MAP map;
407         struct group *grp;
408         DOM_SID sid;
409         BOOL try_add = False;
410
411         fstrcpy(account, unistr2_static(&delta->uni_acct_name));
412         d_printf("Creating account: %s\n", account);
413
414         if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
415                 return nt_ret;
416
417         if (!pdb_getsampwnam(sam_account, account)) {
418                 /* Create appropriate user */
419                 if (delta->acb_info & ACB_NORMAL) {
420                         pstrcpy(add_script, lp_adduser_script());
421                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
422                             (delta->acb_info & ACB_SVRTRUST) ||
423                             (delta->acb_info & ACB_DOMTRUST) ) {
424                         pstrcpy(add_script, lp_addmachine_script());
425                 } else {
426                         DEBUG(1, ("Unknown user type: %s\n",
427                                   smbpasswd_encode_acb_info(delta->acb_info)));
428                         pdb_free_sam(&sam_account);
429                         return NT_STATUS_NO_SUCH_USER;
430                 }
431                 if (*add_script) {
432                         int add_ret;
433                         all_string_sub(add_script, "%u", account,
434                                        sizeof(account));
435                         add_ret = smbrun(add_script,NULL);
436                         DEBUG(1,("fetch_account: Running the command `%s' "
437                                  "gave %d\n", add_script, add_ret));
438                 }
439
440                 try_add = True;
441         }
442
443         sam_account_from_delta(sam_account, delta);
444
445         if (try_add) { 
446                 if (!pdb_add_sam_account(sam_account)) {
447                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
448                                   account));
449                 }
450         } else {
451                 if (!pdb_update_sam_account(sam_account)) {
452                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
453                                   account));
454                 }
455         }
456
457         sid = *pdb_get_group_sid(sam_account);
458
459         if (!pdb_getgrsid(&map, sid, False)) {
460                 DEBUG(0, ("Primary group of %s has no mapping!\n",
461                           pdb_get_username(sam_account)));
462                 pdb_free_sam(&sam_account);
463                 return NT_STATUS_NO_SUCH_GROUP;
464         }
465
466         if (!(grp = getgrgid(map.gid))) {
467                 DEBUG(0, ("Could not find unix group %d for user %s (group SID=%s)\n", 
468                           map.gid, pdb_get_username(sam_account), sid_string_static(&sid)));
469                 pdb_free_sam(&sam_account);
470                 return NT_STATUS_NO_SUCH_GROUP;
471         }
472
473         smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
474
475         pdb_free_sam(&sam_account);
476         return NT_STATUS_OK;
477 }
478
479 static NTSTATUS
480 fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
481 {
482         fstring name;
483         fstring comment;
484         struct group *grp = NULL;
485         DOM_SID group_sid;
486         fstring sid_string;
487         GROUP_MAP map;
488         BOOL insert = True;
489
490         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name)-1);
491         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment)-1);
492
493         /* add the group to the mapping table */
494         sid_copy(&group_sid, get_global_sam_sid());
495         sid_append_rid(&group_sid, rid);
496         sid_to_string(sid_string, &group_sid);
497
498         if (pdb_getgrsid(&map, group_sid, False)) {
499                 grp = getgrgid(map.gid);
500                 insert = False;
501         }
502
503         if (grp == NULL)
504         {
505                 gid_t gid;
506
507                 /* No group found from mapping, find it from its name. */
508                 if ((grp = getgrnam(name)) == NULL) {
509                         /* No appropriate group found, create one */
510                         d_printf("Creating unix group: '%s'\n", name);
511                         if (smb_create_group(name, &gid) != 0)
512                                 return NT_STATUS_ACCESS_DENIED;
513                         if ((grp = getgrgid(gid)) == NULL)
514                                 return NT_STATUS_ACCESS_DENIED;
515                 }
516         }
517
518         map.gid = grp->gr_gid;
519         map.sid = group_sid;
520         map.sid_name_use = SID_NAME_DOM_GRP;
521         fstrcpy(map.nt_name, name);
522         fstrcpy(map.comment, comment);
523
524         map.priv_set.count = 0;
525         map.priv_set.set = NULL;
526
527         if (insert)
528                 pdb_add_group_mapping_entry(&map);
529         else
530                 pdb_update_group_mapping_entry(&map);
531
532         return NT_STATUS_OK;
533 }
534
535 static NTSTATUS
536 fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
537 {
538         int i;
539         TALLOC_CTX *t = NULL;
540         char **nt_members = NULL;
541         char **unix_members;
542         DOM_SID group_sid;
543         GROUP_MAP map;
544         struct group *grp;
545
546         if (delta->num_members == 0) {
547                 return NT_STATUS_OK;
548         }
549
550         sid_copy(&group_sid, get_global_sam_sid());
551         sid_append_rid(&group_sid, rid);
552
553         if (!get_domain_group_from_sid(group_sid, &map, False)) {
554                 DEBUG(0, ("Could not find global group %d\n", rid));
555                 return NT_STATUS_NO_SUCH_GROUP;
556         }
557
558         if (!(grp = getgrgid(map.gid))) {
559                 DEBUG(0, ("Could not find unix group %d\n", map.gid));
560                 return NT_STATUS_NO_SUCH_GROUP;
561         }
562
563         d_printf("Group members of %s: ", grp->gr_name);
564
565         if (!(t = talloc_init("fetch_group_mem_info"))) {
566                 DEBUG(0, ("could not talloc_init\n"));
567                 return NT_STATUS_NO_MEMORY;
568         }
569
570         nt_members = talloc_zero(t, sizeof(char *) * delta->num_members);
571
572         for (i=0; i<delta->num_members; i++) {
573                 NTSTATUS nt_status;
574                 SAM_ACCOUNT *member = NULL;
575                 DOM_SID member_sid;
576
577                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
578                         talloc_destroy(t);
579                         return nt_status;
580                 }
581
582                 sid_copy(&member_sid, get_global_sam_sid());
583                 sid_append_rid(&member_sid, delta->rids[i]);
584
585                 if (!pdb_getsampwsid(member, &member_sid)) {
586                         DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
587                                   delta->rids[i], sid_string_static(&member_sid), grp->gr_name));
588                         pdb_free_sam(&member);
589                         continue;
590                 }
591
592                 if (pdb_get_group_rid(member) == rid) {
593                         d_printf("%s(primary),", pdb_get_username(member));
594                         pdb_free_sam(&member);
595                         continue;
596                 }
597                 
598                 d_printf("%s,", pdb_get_username(member));
599                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
600                 pdb_free_sam(&member);
601         }
602
603         d_printf("\n");
604
605         unix_members = grp->gr_mem;
606
607         while (*unix_members) {
608                 BOOL is_nt_member = False;
609                 for (i=0; i<delta->num_members; i++) {
610                         if (nt_members[i] == NULL) {
611                                 /* This was a primary group */
612                                 continue;
613                         }
614
615                         if (strcmp(*unix_members, nt_members[i]) == 0) {
616                                 is_nt_member = True;
617                                 break;
618                         }
619                 }
620                 if (!is_nt_member) {
621                         /* We look at a unix group member that is not
622                            an nt group member. So, remove it. NT is
623                            boss here. */
624                         smb_delete_user_group(grp->gr_name, *unix_members);
625                 }
626                 unix_members += 1;
627         }
628
629         for (i=0; i<delta->num_members; i++) {
630                 BOOL is_unix_member = False;
631
632                 if (nt_members[i] == NULL) {
633                         /* This was the primary group */
634                         continue;
635                 }
636
637                 unix_members = grp->gr_mem;
638
639                 while (*unix_members) {
640                         if (strcmp(*unix_members, nt_members[i]) == 0) {
641                                 is_unix_member = True;
642                                 break;
643                         }
644                         unix_members += 1;
645                 }
646
647                 if (!is_unix_member) {
648                         /* We look at a nt group member that is not a
649                            unix group member currently. So, add the nt
650                            group member. */
651                         smb_add_user_group(grp->gr_name, nt_members[i]);
652                 }
653         }
654         
655         talloc_destroy(t);
656         return NT_STATUS_OK;
657 }
658
659 static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
660                                  DOM_SID dom_sid)
661 {
662         fstring name;
663         fstring comment;
664         struct group *grp = NULL;
665         DOM_SID alias_sid;
666         fstring sid_string;
667         GROUP_MAP map;
668         BOOL insert = True;
669
670         unistr2_to_ascii(name, &delta->uni_als_name, sizeof(name)-1);
671         unistr2_to_ascii(comment, &delta->uni_als_desc, sizeof(comment)-1);
672
673         /* Find out whether the group is already mapped */
674         sid_copy(&alias_sid, &dom_sid);
675         sid_append_rid(&alias_sid, rid);
676         sid_to_string(sid_string, &alias_sid);
677
678         if (pdb_getgrsid(&map, alias_sid, False)) {
679                 grp = getgrgid(map.gid);
680                 insert = False;
681         }
682
683         if (grp == NULL) {
684                 gid_t gid;
685
686                 /* No group found from mapping, find it from its name. */
687                 if ((grp = getgrnam(name)) == NULL) {
688                         /* No appropriate group found, create one */
689                         d_printf("Creating unix group: '%s'\n", name);
690                         if (smb_create_group(name, &gid) != 0)
691                                 return NT_STATUS_ACCESS_DENIED;
692                         if ((grp = getgrgid(gid)) == NULL)
693                                 return NT_STATUS_ACCESS_DENIED;
694                 }
695         }
696
697         map.gid = grp->gr_gid;
698         map.sid = alias_sid;
699
700         if (sid_equal(&dom_sid, &global_sid_Builtin))
701                 map.sid_name_use = SID_NAME_WKN_GRP;
702         else
703                 map.sid_name_use = SID_NAME_ALIAS;
704
705         fstrcpy(map.nt_name, name);
706         fstrcpy(map.comment, comment);
707
708         map.priv_set.count = 0;
709         map.priv_set.set = NULL;
710
711         if (insert)
712                 pdb_add_group_mapping_entry(&map);
713         else
714                 pdb_update_group_mapping_entry(&map);
715
716         return NT_STATUS_OK;
717 }
718
719 static NTSTATUS
720 fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
721 {
722         
723         return NT_STATUS_OK;
724 }
725
726 static void
727 fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
728                 DOM_SID dom_sid)
729 {
730         switch(hdr_delta->type) {
731         case SAM_DELTA_ACCOUNT_INFO:
732                 fetch_account_info(hdr_delta->target_rid,
733                                    &delta->account_info);
734                 break;
735         case SAM_DELTA_GROUP_INFO:
736                 fetch_group_info(hdr_delta->target_rid,
737                                  &delta->group_info);
738                 break;
739         case SAM_DELTA_GROUP_MEM:
740                 fetch_group_mem_info(hdr_delta->target_rid,
741                                      &delta->grp_mem_info);
742                 break;
743         case SAM_DELTA_ALIAS_INFO:
744                 fetch_alias_info(hdr_delta->target_rid,
745                                  &delta->alias_info, dom_sid);
746                 break;
747         case SAM_DELTA_ALIAS_MEM:
748                 fetch_alias_mem(hdr_delta->target_rid,
749                                 &delta->als_mem_info, dom_sid);
750                 break;
751         case SAM_DELTA_DOMAIN_INFO:
752                 d_printf("SAMBA_DELTA_DOMAIN_INFO not handled\n");
753                 break;
754         default:
755                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
756                 break;
757         }
758 }
759
760 static void
761 fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
762                DOM_SID dom_sid)
763 {
764         unsigned sync_context = 0;
765         NTSTATUS result;
766         int i;
767         TALLOC_CTX *mem_ctx;
768         SAM_DELTA_HDR *hdr_deltas;
769         SAM_DELTA_CTR *deltas;
770         uint32 num_deltas;
771
772         if (!(mem_ctx = talloc_init("fetch_database"))) {
773                 return;
774         }
775
776         switch( db_type ) {
777         case SAM_DATABASE_DOMAIN:
778                 d_printf("Fetching DOMAIN database\n");
779                 break;
780         case SAM_DATABASE_BUILTIN:
781                 d_printf("Fetching BUILTIN database\n");
782                 break;
783         case SAM_DATABASE_PRIVS:
784                 d_printf("Fetching PRIVS databases\n");
785                 break;
786         default:
787                 d_printf("Fetching unknown database type %u\n", db_type );
788                 break;
789         }
790
791         do {
792                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
793                                                db_type, sync_context,
794                                                &num_deltas,
795                                                &hdr_deltas, &deltas);
796                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
797                                      ret_creds);
798                 for (i = 0; i < num_deltas; i++) {
799                         fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
800                 }
801                 sync_context += 1;
802         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
803
804         talloc_destroy(mem_ctx);
805 }
806
807 /* dump sam database via samsync rpc calls */
808 int rpc_vampire(int argc, const char **argv)
809 {
810         NTSTATUS result;
811         struct cli_state *cli = NULL;
812         uchar trust_password[16];
813         DOM_CRED ret_creds;
814         uint32 neg_flags = 0x000001ff;
815         DOM_SID dom_sid;
816
817         ZERO_STRUCT(ret_creds);
818
819         /* Connect to remote machine */
820         if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS |
821                                             NET_FLAGS_PDC))) {
822                 return 1;
823         }
824
825         if (!cli_nt_session_open(cli, PI_NETLOGON)) {
826                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
827                 goto fail;
828         }
829
830         if (!secrets_fetch_trust_account_password(lp_workgroup(),
831                                                   trust_password, NULL)) {
832                 d_printf("Could not retrieve domain trust secret\n");
833                 goto fail;
834         }
835         
836         result = cli_nt_setup_creds(cli, SEC_CHAN_BDC,  trust_password,
837                                     &neg_flags, 2);
838         if (!NT_STATUS_IS_OK(result)) {
839                 d_printf("Failed to setup BDC creds\n");
840                 goto fail;
841         }
842
843         dom_sid = *get_global_sam_sid();
844         fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds, dom_sid);
845
846         sid_copy(&dom_sid, &global_sid_Builtin);
847         fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, dom_sid);
848
849         /* Currently we crash on PRIVS somewhere in unmarshalling */
850         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
851
852         cli_nt_session_close(cli);
853         
854         return 0;
855
856 fail:
857         if (cli) {
858                 cli_nt_session_close(cli);
859         }
860         return -1;
861 }