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