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