JHT came up with a nasty (broken) torture case in preparing examples for
[tprouty/samba.git] / source / 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                 if (NT_STATUS_IS_ERR(result))
186                         break;
187
188                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), ret_creds);
189                 for (i = 0; i < num_deltas; i++) {
190                         display_sam_entry(&hdr_deltas[i], &deltas[i]);
191                 }
192                 sync_context += 1;
193         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
194
195         talloc_destroy(mem_ctx);
196 }
197
198 /* dump sam database via samsync rpc calls */
199 int rpc_samdump(int argc, const char **argv)
200 {
201         struct cli_state *cli = NULL;
202         uchar trust_password[16];
203         DOM_CRED ret_creds;
204         uint32 sec_channel;
205
206         ZERO_STRUCT(ret_creds);
207
208         /* Connect to remote machine */
209         if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC))) {
210                 return 1;
211         }
212
213         fstrcpy(cli->domain, lp_workgroup());
214
215         if (!cli_nt_session_open(cli, PI_NETLOGON)) {
216                 DEBUG(0,("Could not open connection to NETLOGON pipe\n"));
217                 goto fail;
218         }
219
220         if (!secrets_fetch_trust_account_password(lp_workgroup(),
221                                                   trust_password,
222                                                   NULL, &sec_channel)) {
223                 DEBUG(0,("Could not fetch trust account password\n"));
224                 goto fail;
225         }
226
227         if (!NT_STATUS_IS_OK(cli_nt_establish_netlogon(cli, sec_channel,
228                                                        trust_password))) {
229                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
230                 goto fail;
231         }
232
233         dump_database(cli, SAM_DATABASE_DOMAIN, &ret_creds);
234         dump_database(cli, SAM_DATABASE_BUILTIN, &ret_creds);
235         dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds);
236
237         cli_nt_session_close(cli);
238         
239         return 0;
240
241 fail:
242         if (cli) {
243                 cli_nt_session_close(cli);
244         }
245         return -1;
246 }
247
248 /* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
249 #define STRING_CHANGED (old_string && !new_string) ||\
250                     (!old_string && new_string) ||\
251                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
252
253 static NTSTATUS
254 sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
255 {
256         const char *old_string, *new_string;
257         time_t unix_time, stored_time;
258         uchar lm_passwd[16], nt_passwd[16];
259         static uchar zero_buf[16];
260
261         /* Username, fullname, home dir, dir drive, logon script, acct
262            desc, workstations, profile. */
263
264         if (delta->hdr_acct_name.buffer) {
265                 old_string = pdb_get_nt_username(account);
266                 new_string = unistr2_static(&delta->uni_acct_name);
267
268                 if (STRING_CHANGED) {
269                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
270               
271                 }
272          
273                 /* Unix username is the same - for sanity */
274                 old_string = pdb_get_username( account );
275                 if (STRING_CHANGED) {
276                         pdb_set_username(account, new_string, PDB_CHANGED);
277                 }
278         }
279
280         if (delta->hdr_full_name.buffer) {
281                 old_string = pdb_get_fullname(account);
282                 new_string = unistr2_static(&delta->uni_full_name);
283
284                 if (STRING_CHANGED)
285                         pdb_set_fullname(account, new_string, PDB_CHANGED);
286         }
287
288         if (delta->hdr_home_dir.buffer) {
289                 old_string = pdb_get_homedir(account);
290                 new_string = unistr2_static(&delta->uni_home_dir);
291
292                 if (STRING_CHANGED)
293                         pdb_set_homedir(account, new_string, PDB_CHANGED);
294         }
295
296         if (delta->hdr_dir_drive.buffer) {
297                 old_string = pdb_get_dir_drive(account);
298                 new_string = unistr2_static(&delta->uni_dir_drive);
299
300                 if (STRING_CHANGED)
301                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
302         }
303
304         if (delta->hdr_logon_script.buffer) {
305                 old_string = pdb_get_logon_script(account);
306                 new_string = unistr2_static(&delta->uni_logon_script);
307
308                 if (STRING_CHANGED)
309                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
310         }
311
312         if (delta->hdr_acct_desc.buffer) {
313                 old_string = pdb_get_acct_desc(account);
314                 new_string = unistr2_static(&delta->uni_acct_desc);
315
316                 if (STRING_CHANGED)
317                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
318         }
319
320         if (delta->hdr_workstations.buffer) {
321                 old_string = pdb_get_workstations(account);
322                 new_string = unistr2_static(&delta->uni_workstations);
323
324                 if (STRING_CHANGED)
325                         pdb_set_workstations(account, new_string, PDB_CHANGED);
326         }
327
328         if (delta->hdr_profile.buffer) {
329                 old_string = pdb_get_profile_path(account);
330                 new_string = unistr2_static(&delta->uni_profile);
331
332                 if (STRING_CHANGED)
333                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
334         }
335
336         /* User and group sid */
337         if (pdb_get_user_rid(account) != delta->user_rid)
338                 pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
339         if (pdb_get_group_rid(account) != delta->group_rid)
340                 pdb_set_group_sid_from_rid(account, delta->group_rid, PDB_CHANGED);
341
342         /* Logon and password information */
343         if (!nt_time_is_zero(&delta->logon_time)) {
344                 unix_time = nt_time_to_unix(&delta->logon_time);
345                 stored_time = pdb_get_logon_time(account);
346                 if (stored_time != unix_time)
347                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
348         }
349
350         if (!nt_time_is_zero(&delta->logoff_time)) {
351                 unix_time = nt_time_to_unix(&delta->logoff_time);
352                 stored_time = pdb_get_logoff_time(account);
353                 if (stored_time != unix_time)
354                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
355         }
356
357         if (pdb_get_logon_divs(account) != delta->logon_divs)
358                 pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
359
360         /* TODO: logon hours */
361         /* TODO: bad password count */
362         /* TODO: logon count */
363
364         if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
365                 unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
366                 stored_time = pdb_get_pass_last_set_time(account);
367                 if (stored_time != unix_time)
368                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
369         }
370
371 #if 0
372 /*      No kickoff time in the delta? */
373         if (!nt_time_is_zero(&delta->kickoff_time)) {
374                 unix_time = nt_time_to_unix(&delta->kickoff_time);
375                 stored_time = pdb_get_kickoff_time(account);
376                 if (stored_time != unix_time)
377                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
378         }
379 #endif
380
381         /* Decode hashes from password hash 
382            Note that win2000 may send us all zeros for the hashes if it doesn't 
383            think this channel is secure enough - don't set the passwords at all
384            in that case
385         */
386         if (memcmp(delta->pass.buf_lm_pwd, zero_buf, 16) != 0) {
387                 sam_pwd_hash(delta->user_rid, delta->pass.buf_lm_pwd, lm_passwd, 0);
388                 pdb_set_lanman_passwd(account, lm_passwd, PDB_CHANGED);
389         }
390
391         if (memcmp(delta->pass.buf_nt_pwd, zero_buf, 16) != 0) {
392                 sam_pwd_hash(delta->user_rid, delta->pass.buf_nt_pwd, nt_passwd, 0);
393                 pdb_set_nt_passwd(account, nt_passwd, PDB_CHANGED);
394         }
395
396         /* TODO: account expiry time */
397
398         if (pdb_get_acct_ctrl(account) != delta->acb_info)
399                 pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
400
401         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
402
403         return NT_STATUS_OK;
404 }
405
406 static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
407 {
408         NTSTATUS nt_ret;
409         fstring account;
410         pstring add_script;
411         SAM_ACCOUNT *sam_account=NULL;
412         GROUP_MAP map;
413         struct group *grp;
414         DOM_SID user_sid;
415         DOM_SID group_sid;
416         struct passwd *passwd;
417         fstring sid_string;
418
419         fstrcpy(account, unistr2_static(&delta->uni_acct_name));
420         d_printf("Creating account: %s\n", account);
421
422         if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
423                 return nt_ret;
424
425         if (!(passwd = Get_Pwnam(account))) {
426                 /* Create appropriate user */
427                 if (delta->acb_info & ACB_NORMAL) {
428                         pstrcpy(add_script, lp_adduser_script());
429                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
430                             (delta->acb_info & ACB_SVRTRUST) ||
431                             (delta->acb_info & ACB_DOMTRUST) ) {
432                         pstrcpy(add_script, lp_addmachine_script());
433                 } else {
434                         DEBUG(1, ("Unknown user type: %s\n",
435                                   smbpasswd_encode_acb_info(delta->acb_info)));
436                         nt_ret = NT_STATUS_UNSUCCESSFUL;
437                         goto done;
438                 }
439                 if (*add_script) {
440                         int add_ret;
441                         all_string_sub(add_script, "%u", account,
442                                        sizeof(account));
443                         add_ret = smbrun(add_script,NULL);
444                         DEBUG(1,("fetch_account: Running the command `%s' "
445                                  "gave %d\n", add_script, add_ret));
446                 } else {
447                         DEBUG(8,("fetch_account_info: no add user/machine script.  Asking winbindd\n"));
448                         
449                         /* don't need a RID allocated since the user already has a SID */
450                         if ( !winbind_create_user( account, NULL ) )
451                                 DEBUG(4,("fetch_account_info: winbind_create_user() failed\n"));
452                 }
453                 
454                 /* try and find the possible unix account again */
455                 if ( !(passwd = Get_Pwnam(account)) ) {
456                         d_printf("Could not create posix account info for '%s'\n", account);
457                         nt_ret = NT_STATUS_NO_SUCH_USER;
458                         goto done;
459                 }
460                         
461         }
462         
463         sid_copy(&user_sid, get_global_sam_sid());
464         sid_append_rid(&user_sid, delta->user_rid);
465
466         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n", sid_to_string(sid_string, &user_sid), account));
467         if (!pdb_getsampwsid(sam_account, &user_sid)) {
468                 sam_account_from_delta(sam_account, delta);
469                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
470                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
471                 if (!pdb_add_sam_account(sam_account)) {
472                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
473                                   account));
474                         return NT_STATUS_ACCESS_DENIED; 
475                 }
476         } else {
477                 sam_account_from_delta(sam_account, delta);
478                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
479                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
480                 if (!pdb_update_sam_account(sam_account)) {
481                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
482                                   account));
483                         pdb_free_sam(&sam_account);
484                         return NT_STATUS_ACCESS_DENIED; 
485                 }
486         }
487
488         group_sid = *pdb_get_group_sid(sam_account);
489
490         if (!pdb_getgrsid(&map, group_sid)) {
491                 DEBUG(0, ("Primary group of %s has no mapping!\n",
492                           pdb_get_username(sam_account)));
493         } else {
494                 if (map.gid != passwd->pw_gid) {
495                         if (!(grp = getgrgid(map.gid))) {
496                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
497                                           (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_static(&group_sid)));
498                         } else {
499                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
500                         }
501                 }
502         }       
503
504         if ( !passwd ) {
505                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
506                         pdb_get_username(sam_account)));
507         }
508
509  done:
510         pdb_free_sam(&sam_account);
511         return nt_ret;
512 }
513
514 static NTSTATUS
515 fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
516 {
517         fstring name;
518         fstring comment;
519         struct group *grp = NULL;
520         DOM_SID group_sid;
521         fstring sid_string;
522         GROUP_MAP map;
523         BOOL insert = True;
524
525         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name)-1);
526         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment)-1);
527
528         /* add the group to the mapping table */
529         sid_copy(&group_sid, get_global_sam_sid());
530         sid_append_rid(&group_sid, rid);
531         sid_to_string(sid_string, &group_sid);
532
533         if (pdb_getgrsid(&map, group_sid)) {
534                 if ( map.gid != -1 )
535                         grp = getgrgid(map.gid);
536                 insert = False;
537         }
538
539         if (grp == NULL) {
540                 gid_t gid;
541
542                 /* No group found from mapping, find it from its name. */
543                 if ((grp = getgrnam(name)) == NULL) {
544                 
545                         /* No appropriate group found, create one */
546                         
547                         d_printf("Creating unix group: '%s'\n", name);
548                         
549                         if (smb_create_group(name, &gid) != 0)
550                                 return NT_STATUS_ACCESS_DENIED;
551                                 
552                         if ((grp = getgrnam(name)) == NULL)
553                                 return NT_STATUS_ACCESS_DENIED;
554                 }
555         }
556
557         map.gid = grp->gr_gid;
558         map.sid = group_sid;
559         map.sid_name_use = SID_NAME_DOM_GRP;
560         fstrcpy(map.nt_name, name);
561         if (delta->hdr_grp_desc.buffer) {
562                 fstrcpy(map.comment, comment);
563         } else {
564                 fstrcpy(map.comment, "");
565         }
566
567         if (insert)
568                 pdb_add_group_mapping_entry(&map);
569         else
570                 pdb_update_group_mapping_entry(&map);
571
572         return NT_STATUS_OK;
573 }
574
575 static NTSTATUS
576 fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
577 {
578         int i;
579         TALLOC_CTX *t = NULL;
580         char **nt_members = NULL;
581         char **unix_members;
582         DOM_SID group_sid;
583         GROUP_MAP map;
584         struct group *grp;
585
586         if (delta->num_members == 0) {
587                 return NT_STATUS_OK;
588         }
589
590         sid_copy(&group_sid, get_global_sam_sid());
591         sid_append_rid(&group_sid, rid);
592
593         if (!get_domain_group_from_sid(group_sid, &map)) {
594                 DEBUG(0, ("Could not find global group %d\n", rid));
595                 return NT_STATUS_NO_SUCH_GROUP;
596         }
597
598         if (!(grp = getgrgid(map.gid))) {
599                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
600                 return NT_STATUS_NO_SUCH_GROUP;
601         }
602
603         d_printf("Group members of %s: ", grp->gr_name);
604
605         if (!(t = talloc_init("fetch_group_mem_info"))) {
606                 DEBUG(0, ("could not talloc_init\n"));
607                 return NT_STATUS_NO_MEMORY;
608         }
609
610         nt_members = talloc_zero(t, sizeof(char *) * delta->num_members);
611
612         for (i=0; i<delta->num_members; i++) {
613                 NTSTATUS nt_status;
614                 SAM_ACCOUNT *member = NULL;
615                 DOM_SID member_sid;
616
617                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
618                         talloc_destroy(t);
619                         return nt_status;
620                 }
621
622                 sid_copy(&member_sid, get_global_sam_sid());
623                 sid_append_rid(&member_sid, delta->rids[i]);
624
625                 if (!pdb_getsampwsid(member, &member_sid)) {
626                         DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
627                                   delta->rids[i], sid_string_static(&member_sid), grp->gr_name));
628                         pdb_free_sam(&member);
629                         continue;
630                 }
631
632                 if (pdb_get_group_rid(member) == rid) {
633                         d_printf("%s(primary),", pdb_get_username(member));
634                         pdb_free_sam(&member);
635                         continue;
636                 }
637                 
638                 d_printf("%s,", pdb_get_username(member));
639                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
640                 pdb_free_sam(&member);
641         }
642
643         d_printf("\n");
644
645         unix_members = grp->gr_mem;
646
647         while (*unix_members) {
648                 BOOL is_nt_member = False;
649                 for (i=0; i<delta->num_members; i++) {
650                         if (nt_members[i] == NULL) {
651                                 /* This was a primary group */
652                                 continue;
653                         }
654
655                         if (strcmp(*unix_members, nt_members[i]) == 0) {
656                                 is_nt_member = True;
657                                 break;
658                         }
659                 }
660                 if (!is_nt_member) {
661                         /* We look at a unix group member that is not
662                            an nt group member. So, remove it. NT is
663                            boss here. */
664                         smb_delete_user_group(grp->gr_name, *unix_members);
665                 }
666                 unix_members += 1;
667         }
668
669         for (i=0; i<delta->num_members; i++) {
670                 BOOL is_unix_member = False;
671
672                 if (nt_members[i] == NULL) {
673                         /* This was the primary group */
674                         continue;
675                 }
676
677                 unix_members = grp->gr_mem;
678
679                 while (*unix_members) {
680                         if (strcmp(*unix_members, nt_members[i]) == 0) {
681                                 is_unix_member = True;
682                                 break;
683                         }
684                         unix_members += 1;
685                 }
686
687                 if (!is_unix_member) {
688                         /* We look at a nt group member that is not a
689                            unix group member currently. So, add the nt
690                            group member. */
691                         smb_add_user_group(grp->gr_name, nt_members[i]);
692                 }
693         }
694         
695         talloc_destroy(t);
696         return NT_STATUS_OK;
697 }
698
699 static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
700                                  DOM_SID dom_sid)
701 {
702         fstring name;
703         fstring comment;
704         struct group *grp = NULL;
705         DOM_SID alias_sid;
706         fstring sid_string;
707         GROUP_MAP map;
708         BOOL insert = True;
709
710         unistr2_to_ascii(name, &delta->uni_als_name, sizeof(name)-1);
711         unistr2_to_ascii(comment, &delta->uni_als_desc, sizeof(comment)-1);
712
713         /* Find out whether the group is already mapped */
714         sid_copy(&alias_sid, &dom_sid);
715         sid_append_rid(&alias_sid, rid);
716         sid_to_string(sid_string, &alias_sid);
717
718         if (pdb_getgrsid(&map, alias_sid)) {
719                 grp = getgrgid(map.gid);
720                 insert = False;
721         }
722
723         if (grp == NULL) {
724                 gid_t gid;
725
726                 /* No group found from mapping, find it from its name. */
727                 if ((grp = getgrnam(name)) == NULL) {
728                         /* No appropriate group found, create one */
729                         d_printf("Creating unix group: '%s'\n", name);
730                         if (smb_create_group(name, &gid) != 0)
731                                 return NT_STATUS_ACCESS_DENIED;
732                         if ((grp = getgrgid(gid)) == NULL)
733                                 return NT_STATUS_ACCESS_DENIED;
734                 }
735         }
736
737         map.gid = grp->gr_gid;
738         map.sid = alias_sid;
739
740         if (sid_equal(&dom_sid, &global_sid_Builtin))
741                 map.sid_name_use = SID_NAME_WKN_GRP;
742         else
743                 map.sid_name_use = SID_NAME_ALIAS;
744
745         fstrcpy(map.nt_name, name);
746         fstrcpy(map.comment, comment);
747
748         if (insert)
749                 pdb_add_group_mapping_entry(&map);
750         else
751                 pdb_update_group_mapping_entry(&map);
752
753         return NT_STATUS_OK;
754 }
755
756 static NTSTATUS
757 fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
758 {
759 #if 0   /* 
760          * commented out right now after talking to Volker.  Can't
761          * do much with the membership but seemed a shame to waste
762          * somewhat working code.  Needs testing because the membership
763          * that shows up surprises me.  Also can't do much with groups
764          * in groups (e.g. Domain Admins being a member of Adminsitrators).
765          * --jerry
766          */
767         
768         int i;
769         TALLOC_CTX *t = NULL;
770         char **nt_members = NULL;
771         char **unix_members;
772         DOM_SID group_sid;
773         GROUP_MAP map;
774         struct group *grp;
775         enum SID_NAME_USE sid_type;
776
777         if (delta->num_members == 0) {
778                 return NT_STATUS_OK;
779         }
780
781         sid_copy(&group_sid, &dom_sid);
782         sid_append_rid(&group_sid, rid);
783
784         if (sid_equal(&dom_sid, &global_sid_Builtin)) {
785                 sid_type = SID_NAME_WKN_GRP;
786                 if (!get_builtin_group_from_sid(&group_sid, &map, False)) {
787                         DEBUG(0, ("Could not find builtin group %s\n", sid_string_static(&group_sid)));
788                         return NT_STATUS_NO_SUCH_GROUP;
789                 }
790         } else {
791                 sid_type = SID_NAME_ALIAS;
792                 if (!get_local_group_from_sid(&group_sid, &map, False)) {
793                         DEBUG(0, ("Could not find local group %s\n", sid_string_static(&group_sid)));
794                         return NT_STATUS_NO_SUCH_GROUP;
795                 }
796         }       
797
798         if (!(grp = getgrgid(map.gid))) {
799                 DEBUG(0, ("Could not find unix group %d\n", map.gid));
800                 return NT_STATUS_NO_SUCH_GROUP;
801         }
802
803         d_printf("Group members of %s: ", grp->gr_name);
804
805         if (!(t = talloc_init("fetch_group_mem_info"))) {
806                 DEBUG(0, ("could not talloc_init\n"));
807                 return NT_STATUS_NO_MEMORY;
808         }
809
810         nt_members = talloc_zero(t, sizeof(char *) * delta->num_members);
811
812         for (i=0; i<delta->num_members; i++) {
813                 NTSTATUS nt_status;
814                 SAM_ACCOUNT *member = NULL;
815                 DOM_SID member_sid;
816
817                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
818                         talloc_destroy(t);
819                         return nt_status;
820                 }
821
822                 sid_copy(&member_sid, &delta->sids[i].sid);
823
824                 if (!pdb_getsampwsid(member, &member_sid)) {
825                         DEBUG(1, ("Found bogus group member: (member_sid=%s group=%s)\n",
826                                   sid_string_static(&member_sid), grp->gr_name));
827                         pdb_free_sam(&member);
828                         continue;
829                 }
830
831                 if (pdb_get_group_rid(member) == rid) {
832                         d_printf("%s(primary),", pdb_get_username(member));
833                         pdb_free_sam(&member);
834                         continue;
835                 }
836                 
837                 d_printf("%s,", pdb_get_username(member));
838                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
839                 pdb_free_sam(&member);
840         }
841
842         d_printf("\n");
843
844         unix_members = grp->gr_mem;
845
846         while (*unix_members) {
847                 BOOL is_nt_member = False;
848                 for (i=0; i<delta->num_members; i++) {
849                         if (nt_members[i] == NULL) {
850                                 /* This was a primary group */
851                                 continue;
852                         }
853
854                         if (strcmp(*unix_members, nt_members[i]) == 0) {
855                                 is_nt_member = True;
856                                 break;
857                         }
858                 }
859                 if (!is_nt_member) {
860                         /* We look at a unix group member that is not
861                            an nt group member. So, remove it. NT is
862                            boss here. */
863                         smb_delete_user_group(grp->gr_name, *unix_members);
864                 }
865                 unix_members += 1;
866         }
867
868         for (i=0; i<delta->num_members; i++) {
869                 BOOL is_unix_member = False;
870
871                 if (nt_members[i] == NULL) {
872                         /* This was the primary group */
873                         continue;
874                 }
875
876                 unix_members = grp->gr_mem;
877
878                 while (*unix_members) {
879                         if (strcmp(*unix_members, nt_members[i]) == 0) {
880                                 is_unix_member = True;
881                                 break;
882                         }
883                         unix_members += 1;
884                 }
885
886                 if (!is_unix_member) {
887                         /* We look at a nt group member that is not a
888                            unix group member currently. So, add the nt
889                            group member. */
890                         smb_add_user_group(grp->gr_name, nt_members[i]);
891                 }
892         }
893         
894         talloc_destroy(t);
895
896 #endif  /* end of fetch_alias_mem() */
897
898         return NT_STATUS_OK;
899 }
900
901 static void
902 fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
903                 DOM_SID dom_sid)
904 {
905         switch(hdr_delta->type) {
906         case SAM_DELTA_ACCOUNT_INFO:
907                 fetch_account_info(hdr_delta->target_rid,
908                                    &delta->account_info);
909                 break;
910         case SAM_DELTA_GROUP_INFO:
911                 fetch_group_info(hdr_delta->target_rid,
912                                  &delta->group_info);
913                 break;
914         case SAM_DELTA_GROUP_MEM:
915                 fetch_group_mem_info(hdr_delta->target_rid,
916                                      &delta->grp_mem_info);
917                 break;
918         case SAM_DELTA_ALIAS_INFO:
919                 fetch_alias_info(hdr_delta->target_rid,
920                                  &delta->alias_info, dom_sid);
921                 break;
922         case SAM_DELTA_ALIAS_MEM:
923                 fetch_alias_mem(hdr_delta->target_rid,
924                                 &delta->als_mem_info, dom_sid);
925                 break;
926         /* The following types are recognised but not handled */
927         case SAM_DELTA_DOMAIN_INFO:
928                 d_printf("SAM_DELTA_DOMAIN_INFO not handled\n");
929                 break;
930         case SAM_DELTA_RENAME_GROUP:
931                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
932                 break;
933         case SAM_DELTA_RENAME_USER:
934                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
935                 break;
936         case SAM_DELTA_RENAME_ALIAS:
937                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
938                 break;
939         case SAM_DELTA_POLICY_INFO:
940                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
941                 break;
942         case SAM_DELTA_TRUST_DOMS:
943                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
944                 break;
945         case SAM_DELTA_PRIVS_INFO:
946                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
947                 break;
948         case SAM_DELTA_SECRET_INFO:
949                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
950                 break;
951         case SAM_DELTA_DELETE_GROUP:
952                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
953                 break;
954         case SAM_DELTA_DELETE_USER:
955                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
956                 break;
957         case SAM_DELTA_MODIFIED_COUNT:
958                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
959                 break;
960         default:
961                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
962                 break;
963         }
964 }
965
966 static NTSTATUS
967 fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
968                DOM_SID dom_sid)
969 {
970         unsigned sync_context = 0;
971         NTSTATUS result;
972         int i;
973         TALLOC_CTX *mem_ctx;
974         SAM_DELTA_HDR *hdr_deltas;
975         SAM_DELTA_CTR *deltas;
976         uint32 num_deltas;
977
978         if (!(mem_ctx = talloc_init("fetch_database")))
979                 return NT_STATUS_NO_MEMORY;
980
981         switch( db_type ) {
982         case SAM_DATABASE_DOMAIN:
983                 d_printf("Fetching DOMAIN database\n");
984                 break;
985         case SAM_DATABASE_BUILTIN:
986                 d_printf("Fetching BUILTIN database\n");
987                 break;
988         case SAM_DATABASE_PRIVS:
989                 d_printf("Fetching PRIVS databases\n");
990                 break;
991         default:
992                 d_printf("Fetching unknown database type %u\n", db_type );
993                 break;
994         }
995
996         do {
997                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
998                                                db_type, sync_context,
999                                                &num_deltas,
1000                                                &hdr_deltas, &deltas);
1001
1002                 if (NT_STATUS_IS_OK(result) ||
1003                     NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1004
1005                         clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
1006                                              ret_creds);
1007
1008                         for (i = 0; i < num_deltas; i++) {
1009                                 fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
1010                         }
1011                 } else
1012                         return result;
1013
1014                 sync_context += 1;
1015         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1016
1017         talloc_destroy(mem_ctx);
1018
1019         return result;
1020 }
1021
1022 /* dump sam database via samsync rpc calls */
1023 int rpc_vampire(int argc, const char **argv)
1024 {
1025         NTSTATUS result;
1026         struct cli_state *cli = NULL;
1027         uchar trust_password[16];
1028         DOM_CRED ret_creds;
1029         DOM_SID dom_sid;
1030         uint32 sec_channel;
1031
1032         ZERO_STRUCT(ret_creds);
1033
1034         /* Connect to remote machine */
1035         if (!(cli = net_make_ipc_connection(NET_FLAGS_ANONYMOUS |
1036                                             NET_FLAGS_PDC))) {
1037                 return 1;
1038         }
1039
1040         if (!cli_nt_session_open(cli, PI_NETLOGON)) {
1041                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
1042                 goto fail;
1043         }
1044
1045         if (!secrets_fetch_trust_account_password(opt_target_workgroup,
1046                                                   trust_password, NULL,
1047                                                   &sec_channel)) {
1048                 d_printf("Could not retrieve domain trust secret\n");
1049                 goto fail;
1050         }
1051         
1052         result = cli_nt_establish_netlogon(cli, sec_channel,  trust_password);
1053
1054         if (!NT_STATUS_IS_OK(result)) {
1055                 d_printf("Failed to setup BDC creds\n");
1056                 goto fail;
1057         }
1058
1059         sid_copy( &dom_sid, get_global_sam_sid() );
1060         result = fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds, dom_sid);
1061
1062         if (!NT_STATUS_IS_OK(result)) {
1063                 d_printf("Failed to fetch domain database: %s\n",
1064                          nt_errstr(result));
1065                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
1066                         d_printf("Perhaps %s is a Windows 2000 native mode "
1067                                  "domain?\n", opt_target_workgroup);
1068                 goto fail;
1069         }
1070
1071         sid_copy(&dom_sid, &global_sid_Builtin);
1072
1073         result = fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, 
1074                                 dom_sid);
1075
1076         if (!NT_STATUS_IS_OK(result)) {
1077                 d_printf("Failed to fetch builtin database: %s\n",
1078                          nt_errstr(result));
1079                 goto fail;
1080         }       
1081
1082         /* Currently we crash on PRIVS somewhere in unmarshalling */
1083         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
1084
1085         cli_nt_session_close(cli);
1086         
1087         return 0;
1088
1089 fail:
1090         if (cli)
1091                 cli_nt_session_close(cli);
1092
1093         return -1;
1094 }