r4291: More *alloc fixes inspired by Albert Chin (china@thewrittenword.com).
[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
40 static const char *display_time(NTTIME *nttime)
41 {
42         static fstring string;
43
44         float high;
45         float low;
46         int sec;
47         int days, hours, mins, secs;
48         int offset = 1;
49
50         if (nttime->high==0 && nttime->low==0)
51                 return "Now";
52
53         if (nttime->high==0x80000000 && nttime->low==0)
54                 return "Never";
55
56         high = 65536;   
57         high = high/10000;
58         high = high*65536;
59         high = high/1000;
60         high = high * (~nttime->high);
61
62         low = ~nttime->low;     
63         low = low/(1000*1000*10);
64
65         sec=high+low;
66         sec+=offset;
67
68         days=sec/(60*60*24);
69         hours=(sec - (days*60*60*24)) / (60*60);
70         mins=(sec - (days*60*60*24) - (hours*60*60) ) / 60;
71         secs=sec - (days*60*60*24) - (hours*60*60) - (mins*60);
72
73         fstr_sprintf(string, "%u days, %u hours, %u minutes, %u seconds", days, hours, mins, secs);
74         return (string);
75 }
76
77
78 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
79 {
80         d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
81         d_printf("desc='%s' rid=%u\n", unistr2_static(&a->uni_als_desc), a->als_rid);
82 }
83
84 static void display_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *a)
85 {
86         int i;
87         d_printf("Alias rid %u: ", rid);
88         for (i=0;i<a->num_members;i++) {
89                 d_printf("%s ", sid_string_static(&a->sids[i].sid));
90         }
91         d_printf("\n");
92 }
93
94 static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
95 {
96         fstring hex_nt_passwd, hex_lm_passwd;
97         uchar lm_passwd[16], nt_passwd[16];
98         static uchar zero_buf[16];
99
100         /* Decode hashes from password hash (if they are not NULL) */
101         
102         if (memcmp(a->pass.buf_lm_pwd, zero_buf, 16) != 0) {
103                 sam_pwd_hash(a->user_rid, a->pass.buf_lm_pwd, lm_passwd, 0);
104                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
105         } else {
106                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
107         }
108
109         if (memcmp(a->pass.buf_nt_pwd, zero_buf, 16) != 0) {
110                 sam_pwd_hash(a->user_rid, a->pass.buf_nt_pwd, nt_passwd, 0);
111                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
112         } else {
113                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
114         }
115         
116         printf("%s:%d:%s:%s:%s:LCT-0\n", unistr2_static(&a->uni_acct_name),
117                a->user_rid, hex_lm_passwd, hex_nt_passwd,
118                pdb_encode_acct_ctrl(a->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN));
119 }
120
121 static void display_domain_info(SAM_DOMAIN_INFO *a)
122 {
123         time_t u_logout;
124
125         u_logout = nt_time_to_unix_abs((NTTIME *)&a->force_logoff);
126
127         d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
128
129         d_printf("Minimal Password Length: %d\n", a->min_pwd_len);
130         d_printf("Password History Length: %d\n", a->pwd_history_len);
131
132         d_printf("Force Logoff: %d\n", (int)u_logout);
133
134         d_printf("Max Password Age: %s\n", display_time((NTTIME *)&a->max_pwd_age));
135         d_printf("Min Password Age: %s\n", display_time((NTTIME *)&a->min_pwd_age));
136
137         d_printf("Lockout Time: %s\n", display_time((NTTIME *)&a->account_lockout.lockout_duration));
138         d_printf("Lockout Reset Time: %s\n", display_time((NTTIME *)&a->account_lockout.reset_count));
139
140         d_printf("Bad Attempt Lockout: %d\n", a->account_lockout.bad_attempt_lockout);
141         d_printf("User must logon to change password: %d\n", a->logon_chgpass);
142 }
143
144 static void display_group_info(uint32 rid, SAM_GROUP_INFO *a)
145 {
146         d_printf("Group '%s' ", unistr2_static(&a->uni_grp_name));
147         d_printf("desc='%s', rid=%u\n", unistr2_static(&a->uni_grp_desc), rid);
148 }
149
150 static void display_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta)
151 {
152         switch (hdr_delta->type) {
153         case SAM_DELTA_ACCOUNT_INFO:
154                 display_account_info(hdr_delta->target_rid, &delta->account_info);
155                 break;
156         case SAM_DELTA_GROUP_MEM:
157                 display_group_mem_info(hdr_delta->target_rid, &delta->grp_mem_info);
158                 break;
159         case SAM_DELTA_ALIAS_INFO:
160                 display_alias_info(hdr_delta->target_rid, &delta->alias_info);
161                 break;
162         case SAM_DELTA_ALIAS_MEM:
163                 display_alias_mem(hdr_delta->target_rid, &delta->als_mem_info);
164                 break;
165         case SAM_DELTA_DOMAIN_INFO:
166                 display_domain_info(&delta->domain_info);
167                 break;
168         case SAM_DELTA_GROUP_INFO:
169                 display_group_info(hdr_delta->target_rid, &delta->group_info);
170                 break;
171                 /* The following types are recognised but not handled */
172         case SAM_DELTA_RENAME_GROUP:
173                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
174                 break;
175         case SAM_DELTA_RENAME_USER:
176                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
177                 break;
178         case SAM_DELTA_RENAME_ALIAS:
179                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
180                 break;
181         case SAM_DELTA_POLICY_INFO:
182                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
183                 break;
184         case SAM_DELTA_TRUST_DOMS:
185                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
186                 break;
187         case SAM_DELTA_PRIVS_INFO:
188                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
189                 break;
190         case SAM_DELTA_SECRET_INFO:
191                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
192                 break;
193         case SAM_DELTA_DELETE_GROUP:
194                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
195                 break;
196         case SAM_DELTA_DELETE_USER:
197                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
198                 break;
199         case SAM_DELTA_MODIFIED_COUNT:
200                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
201                 break;
202         default:
203                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
204                 break;
205         }
206 }
207
208
209 static void dump_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds)
210 {
211         unsigned sync_context = 0;
212         NTSTATUS result;
213         int i;
214         TALLOC_CTX *mem_ctx;
215         SAM_DELTA_HDR *hdr_deltas;
216         SAM_DELTA_CTR *deltas;
217         uint32 num_deltas;
218
219         if (!(mem_ctx = talloc_init("dump_database"))) {
220                 return;
221         }
222
223         switch( db_type ) {
224         case SAM_DATABASE_DOMAIN:
225                 d_printf("Dumping DOMAIN database\n");
226                 break;
227         case SAM_DATABASE_BUILTIN:
228                 d_printf("Dumping BUILTIN database\n");
229                 break;
230         case SAM_DATABASE_PRIVS:
231                 d_printf("Dumping PRIVS databases\n");
232                 break;
233         default:
234                 d_printf("Dumping unknown database type %u\n", db_type );
235                 break;
236         }
237
238         do {
239                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds, db_type,
240                                                sync_context,
241                                                &num_deltas, &hdr_deltas, &deltas);
242                 if (NT_STATUS_IS_ERR(result))
243                         break;
244
245                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), ret_creds);
246                 for (i = 0; i < num_deltas; i++) {
247                         display_sam_entry(&hdr_deltas[i], &deltas[i]);
248                 }
249                 sync_context += 1;
250         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
251
252         talloc_destroy(mem_ctx);
253 }
254
255 /* dump sam database via samsync rpc calls */
256 NTSTATUS rpc_samdump_internals(const DOM_SID *domain_sid, 
257                                const char *domain_name, 
258                                struct cli_state *cli, TALLOC_CTX *mem_ctx, 
259                                int argc, const char **argv) 
260 {
261         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
262         uchar trust_password[16];
263         DOM_CRED ret_creds;
264         uint32 sec_channel;
265
266         ZERO_STRUCT(ret_creds);
267
268         fstrcpy(cli->domain, domain_name);
269
270         if (!secrets_fetch_trust_account_password(domain_name,
271                                                   trust_password,
272                                                   NULL, &sec_channel)) {
273                 DEBUG(0,("Could not fetch trust account password\n"));
274                 goto fail;
275         }
276
277         if (!NT_STATUS_IS_OK(nt_status = cli_nt_establish_netlogon(cli, sec_channel,
278                                                                    trust_password))) {
279                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
280                 goto fail;
281         }
282
283         dump_database(cli, SAM_DATABASE_DOMAIN, &ret_creds);
284         dump_database(cli, SAM_DATABASE_BUILTIN, &ret_creds);
285         dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds);
286
287         nt_status = NT_STATUS_OK;
288
289 fail:
290         cli_nt_session_close(cli);
291         return nt_status;
292 }
293
294 /* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
295 #define STRING_CHANGED (old_string && !new_string) ||\
296                     (!old_string && new_string) ||\
297                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
298
299 static NTSTATUS
300 sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
301 {
302         const char *old_string, *new_string;
303         time_t unix_time, stored_time;
304         uchar lm_passwd[16], nt_passwd[16];
305         static uchar zero_buf[16];
306
307         /* Username, fullname, home dir, dir drive, logon script, acct
308            desc, workstations, profile. */
309
310         if (delta->hdr_acct_name.buffer) {
311                 old_string = pdb_get_nt_username(account);
312                 new_string = unistr2_static(&delta->uni_acct_name);
313
314                 if (STRING_CHANGED) {
315                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
316               
317                 }
318          
319                 /* Unix username is the same - for sanity */
320                 old_string = pdb_get_username( account );
321                 if (STRING_CHANGED) {
322                         pdb_set_username(account, new_string, PDB_CHANGED);
323                 }
324         }
325
326         if (delta->hdr_full_name.buffer) {
327                 old_string = pdb_get_fullname(account);
328                 new_string = unistr2_static(&delta->uni_full_name);
329
330                 if (STRING_CHANGED)
331                         pdb_set_fullname(account, new_string, PDB_CHANGED);
332         }
333
334         if (delta->hdr_home_dir.buffer) {
335                 old_string = pdb_get_homedir(account);
336                 new_string = unistr2_static(&delta->uni_home_dir);
337
338                 if (STRING_CHANGED)
339                         pdb_set_homedir(account, new_string, PDB_CHANGED);
340         }
341
342         if (delta->hdr_dir_drive.buffer) {
343                 old_string = pdb_get_dir_drive(account);
344                 new_string = unistr2_static(&delta->uni_dir_drive);
345
346                 if (STRING_CHANGED)
347                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
348         }
349
350         if (delta->hdr_logon_script.buffer) {
351                 old_string = pdb_get_logon_script(account);
352                 new_string = unistr2_static(&delta->uni_logon_script);
353
354                 if (STRING_CHANGED)
355                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
356         }
357
358         if (delta->hdr_acct_desc.buffer) {
359                 old_string = pdb_get_acct_desc(account);
360                 new_string = unistr2_static(&delta->uni_acct_desc);
361
362                 if (STRING_CHANGED)
363                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
364         }
365
366         if (delta->hdr_workstations.buffer) {
367                 old_string = pdb_get_workstations(account);
368                 new_string = unistr2_static(&delta->uni_workstations);
369
370                 if (STRING_CHANGED)
371                         pdb_set_workstations(account, new_string, PDB_CHANGED);
372         }
373
374         if (delta->hdr_profile.buffer) {
375                 old_string = pdb_get_profile_path(account);
376                 new_string = unistr2_static(&delta->uni_profile);
377
378                 if (STRING_CHANGED)
379                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
380         }
381
382         if (delta->hdr_parameters.buffer) {
383                 old_string = pdb_get_munged_dial(account);
384                 new_string = unistr2_static(&delta->uni_parameters);
385
386                 if (STRING_CHANGED)
387                         pdb_set_munged_dial(account, new_string, PDB_CHANGED);
388         }
389
390         /* User and group sid */
391         if (pdb_get_user_rid(account) != delta->user_rid)
392                 pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
393         if (pdb_get_group_rid(account) != delta->group_rid)
394                 pdb_set_group_sid_from_rid(account, delta->group_rid, PDB_CHANGED);
395
396         /* Logon and password information */
397         if (!nt_time_is_zero(&delta->logon_time)) {
398                 unix_time = nt_time_to_unix(&delta->logon_time);
399                 stored_time = pdb_get_logon_time(account);
400                 if (stored_time != unix_time)
401                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
402         }
403
404         if (!nt_time_is_zero(&delta->logoff_time)) {
405                 unix_time = nt_time_to_unix(&delta->logoff_time);
406                 stored_time = pdb_get_logoff_time(account);
407                 if (stored_time != unix_time)
408                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
409         }
410
411         if (pdb_get_logon_divs(account) != delta->logon_divs)
412                 pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
413
414         /* TODO: logon hours */
415         if (pdb_get_bad_password_count(account) != delta->bad_pwd_count)
416                 pdb_set_bad_password_count(account, delta->bad_pwd_count, PDB_CHANGED);
417
418         if (pdb_get_logon_count(account) != delta->logon_count)
419                 pdb_set_logon_count(account, delta->logon_count, PDB_CHANGED);
420
421         if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
422                 unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
423                 stored_time = pdb_get_pass_last_set_time(account);
424                 if (stored_time != unix_time)
425                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
426         }
427
428 #if 0
429 /*      No kickoff time in the delta? */
430         if (!nt_time_is_zero(&delta->kickoff_time)) {
431                 unix_time = nt_time_to_unix(&delta->kickoff_time);
432                 stored_time = pdb_get_kickoff_time(account);
433                 if (stored_time != unix_time)
434                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
435         }
436 #endif
437
438         /* Decode hashes from password hash 
439            Note that win2000 may send us all zeros for the hashes if it doesn't 
440            think this channel is secure enough - don't set the passwords at all
441            in that case
442         */
443         if (memcmp(delta->pass.buf_lm_pwd, zero_buf, 16) != 0) {
444                 sam_pwd_hash(delta->user_rid, delta->pass.buf_lm_pwd, lm_passwd, 0);
445                 pdb_set_lanman_passwd(account, lm_passwd, PDB_CHANGED);
446         }
447
448         if (memcmp(delta->pass.buf_nt_pwd, zero_buf, 16) != 0) {
449                 sam_pwd_hash(delta->user_rid, delta->pass.buf_nt_pwd, nt_passwd, 0);
450                 pdb_set_nt_passwd(account, nt_passwd, PDB_CHANGED);
451         }
452
453         /* TODO: account expiry time */
454
455         if (pdb_get_acct_ctrl(account) != delta->acb_info)
456                 pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
457
458         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
459
460         return NT_STATUS_OK;
461 }
462
463 static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
464 {
465         NTSTATUS nt_ret;
466         fstring account;
467         pstring add_script;
468         SAM_ACCOUNT *sam_account=NULL;
469         GROUP_MAP map;
470         struct group *grp;
471         DOM_SID user_sid;
472         DOM_SID group_sid;
473         struct passwd *passwd;
474         fstring sid_string;
475
476         fstrcpy(account, unistr2_static(&delta->uni_acct_name));
477         d_printf("Creating account: %s\n", account);
478
479         if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
480                 return nt_ret;
481
482         if (!(passwd = Get_Pwnam(account))) {
483                 /* Create appropriate user */
484                 if (delta->acb_info & ACB_NORMAL) {
485                         pstrcpy(add_script, lp_adduser_script());
486                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
487                             (delta->acb_info & ACB_SVRTRUST) ||
488                             (delta->acb_info & ACB_DOMTRUST) ) {
489                         pstrcpy(add_script, lp_addmachine_script());
490                 } else {
491                         DEBUG(1, ("Unknown user type: %s\n",
492                                   pdb_encode_acct_ctrl(delta->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
493                         nt_ret = NT_STATUS_UNSUCCESSFUL;
494                         goto done;
495                 }
496                 if (*add_script) {
497                         int add_ret;
498                         all_string_sub(add_script, "%u", account,
499                                        sizeof(account));
500                         add_ret = smbrun(add_script,NULL);
501                         DEBUG(1,("fetch_account: Running the command `%s' "
502                                  "gave %d\n", add_script, add_ret));
503                 } else {
504                         DEBUG(8,("fetch_account_info: no add user/machine script.  Asking winbindd\n"));
505                         
506                         /* don't need a RID allocated since the user already has a SID */
507                         if ( !winbind_create_user( account, NULL ) )
508                                 DEBUG(4,("fetch_account_info: winbind_create_user() failed\n"));
509                 }
510                 
511                 /* try and find the possible unix account again */
512                 if ( !(passwd = Get_Pwnam(account)) ) {
513                         d_printf("Could not create posix account info for '%s'\n", account);
514                         nt_ret = NT_STATUS_NO_SUCH_USER;
515                         goto done;
516                 }
517         }
518         
519         sid_copy(&user_sid, get_global_sam_sid());
520         sid_append_rid(&user_sid, delta->user_rid);
521
522         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n", sid_to_string(sid_string, &user_sid), account));
523         if (!pdb_getsampwsid(sam_account, &user_sid)) {
524                 sam_account_from_delta(sam_account, delta);
525                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
526                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
527                 if (!pdb_add_sam_account(sam_account)) {
528                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
529                                   account));
530                         return NT_STATUS_ACCESS_DENIED; 
531                 }
532         } else {
533                 sam_account_from_delta(sam_account, delta);
534                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
535                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
536                 if (!pdb_update_sam_account(sam_account)) {
537                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
538                                   account));
539                         pdb_free_sam(&sam_account);
540                         return NT_STATUS_ACCESS_DENIED; 
541                 }
542         }
543
544         group_sid = *pdb_get_group_sid(sam_account);
545
546         if (!pdb_getgrsid(&map, group_sid)) {
547                 DEBUG(0, ("Primary group of %s has no mapping!\n",
548                           pdb_get_username(sam_account)));
549         } else {
550                 if (map.gid != passwd->pw_gid) {
551                         if (!(grp = getgrgid(map.gid))) {
552                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
553                                           (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_static(&group_sid)));
554                         } else {
555                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
556                         }
557                 }
558         }       
559
560         if ( !passwd ) {
561                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
562                         pdb_get_username(sam_account)));
563         }
564
565  done:
566         pdb_free_sam(&sam_account);
567         return nt_ret;
568 }
569
570 static NTSTATUS
571 fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
572 {
573         fstring name;
574         fstring comment;
575         struct group *grp = NULL;
576         DOM_SID group_sid;
577         fstring sid_string;
578         GROUP_MAP map;
579         BOOL insert = True;
580
581         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name)-1);
582         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment)-1);
583
584         /* add the group to the mapping table */
585         sid_copy(&group_sid, get_global_sam_sid());
586         sid_append_rid(&group_sid, rid);
587         sid_to_string(sid_string, &group_sid);
588
589         if (pdb_getgrsid(&map, group_sid)) {
590                 if ( map.gid != -1 )
591                         grp = getgrgid(map.gid);
592                 insert = False;
593         }
594
595         if (grp == NULL) {
596                 gid_t gid;
597
598                 /* No group found from mapping, find it from its name. */
599                 if ((grp = getgrnam(name)) == NULL) {
600                 
601                         /* No appropriate group found, create one */
602                         
603                         d_printf("Creating unix group: '%s'\n", name);
604                         
605                         if (smb_create_group(name, &gid) != 0)
606                                 return NT_STATUS_ACCESS_DENIED;
607                                 
608                         if ((grp = getgrnam(name)) == NULL)
609                                 return NT_STATUS_ACCESS_DENIED;
610                 }
611         }
612
613         map.gid = grp->gr_gid;
614         map.sid = group_sid;
615         map.sid_name_use = SID_NAME_DOM_GRP;
616         fstrcpy(map.nt_name, name);
617         if (delta->hdr_grp_desc.buffer) {
618                 fstrcpy(map.comment, comment);
619         } else {
620                 fstrcpy(map.comment, "");
621         }
622
623         if (insert)
624                 pdb_add_group_mapping_entry(&map);
625         else
626                 pdb_update_group_mapping_entry(&map);
627
628         return NT_STATUS_OK;
629 }
630
631 static NTSTATUS
632 fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
633 {
634         int i;
635         TALLOC_CTX *t = NULL;
636         char **nt_members = NULL;
637         char **unix_members;
638         DOM_SID group_sid;
639         GROUP_MAP map;
640         struct group *grp;
641
642         if (delta->num_members == 0) {
643                 return NT_STATUS_OK;
644         }
645
646         sid_copy(&group_sid, get_global_sam_sid());
647         sid_append_rid(&group_sid, rid);
648
649         if (!get_domain_group_from_sid(group_sid, &map)) {
650                 DEBUG(0, ("Could not find global group %d\n", rid));
651                 return NT_STATUS_NO_SUCH_GROUP;
652         }
653
654         if (!(grp = getgrgid(map.gid))) {
655                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
656                 return NT_STATUS_NO_SUCH_GROUP;
657         }
658
659         d_printf("Group members of %s: ", grp->gr_name);
660
661         if (!(t = talloc_init("fetch_group_mem_info"))) {
662                 DEBUG(0, ("could not talloc_init\n"));
663                 return NT_STATUS_NO_MEMORY;
664         }
665
666         nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
667
668         for (i=0; i<delta->num_members; i++) {
669                 NTSTATUS nt_status;
670                 SAM_ACCOUNT *member = NULL;
671                 DOM_SID member_sid;
672
673                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
674                         talloc_destroy(t);
675                         return nt_status;
676                 }
677
678                 sid_copy(&member_sid, get_global_sam_sid());
679                 sid_append_rid(&member_sid, delta->rids[i]);
680
681                 if (!pdb_getsampwsid(member, &member_sid)) {
682                         DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
683                                   delta->rids[i], sid_string_static(&member_sid), grp->gr_name));
684                         pdb_free_sam(&member);
685                         continue;
686                 }
687
688                 if (pdb_get_group_rid(member) == rid) {
689                         d_printf("%s(primary),", pdb_get_username(member));
690                         pdb_free_sam(&member);
691                         continue;
692                 }
693                 
694                 d_printf("%s,", pdb_get_username(member));
695                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
696                 pdb_free_sam(&member);
697         }
698
699         d_printf("\n");
700
701         unix_members = grp->gr_mem;
702
703         while (*unix_members) {
704                 BOOL is_nt_member = False;
705                 for (i=0; i<delta->num_members; i++) {
706                         if (nt_members[i] == NULL) {
707                                 /* This was a primary group */
708                                 continue;
709                         }
710
711                         if (strcmp(*unix_members, nt_members[i]) == 0) {
712                                 is_nt_member = True;
713                                 break;
714                         }
715                 }
716                 if (!is_nt_member) {
717                         /* We look at a unix group member that is not
718                            an nt group member. So, remove it. NT is
719                            boss here. */
720                         smb_delete_user_group(grp->gr_name, *unix_members);
721                 }
722                 unix_members += 1;
723         }
724
725         for (i=0; i<delta->num_members; i++) {
726                 BOOL is_unix_member = False;
727
728                 if (nt_members[i] == NULL) {
729                         /* This was the primary group */
730                         continue;
731                 }
732
733                 unix_members = grp->gr_mem;
734
735                 while (*unix_members) {
736                         if (strcmp(*unix_members, nt_members[i]) == 0) {
737                                 is_unix_member = True;
738                                 break;
739                         }
740                         unix_members += 1;
741                 }
742
743                 if (!is_unix_member) {
744                         /* We look at a nt group member that is not a
745                            unix group member currently. So, add the nt
746                            group member. */
747                         smb_add_user_group(grp->gr_name, nt_members[i]);
748                 }
749         }
750         
751         talloc_destroy(t);
752         return NT_STATUS_OK;
753 }
754
755 static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
756                                  DOM_SID dom_sid)
757 {
758         fstring name;
759         fstring comment;
760         struct group *grp = NULL;
761         DOM_SID alias_sid;
762         fstring sid_string;
763         GROUP_MAP map;
764         BOOL insert = True;
765
766         unistr2_to_ascii(name, &delta->uni_als_name, sizeof(name)-1);
767         unistr2_to_ascii(comment, &delta->uni_als_desc, sizeof(comment)-1);
768
769         /* Find out whether the group is already mapped */
770         sid_copy(&alias_sid, &dom_sid);
771         sid_append_rid(&alias_sid, rid);
772         sid_to_string(sid_string, &alias_sid);
773
774         if (pdb_getgrsid(&map, alias_sid)) {
775                 grp = getgrgid(map.gid);
776                 insert = False;
777         }
778
779         if (grp == NULL) {
780                 gid_t gid;
781
782                 /* No group found from mapping, find it from its name. */
783                 if ((grp = getgrnam(name)) == NULL) {
784                         /* No appropriate group found, create one */
785                         d_printf("Creating unix group: '%s'\n", name);
786                         if (smb_create_group(name, &gid) != 0)
787                                 return NT_STATUS_ACCESS_DENIED;
788                         if ((grp = getgrgid(gid)) == NULL)
789                                 return NT_STATUS_ACCESS_DENIED;
790                 }
791         }
792
793         map.gid = grp->gr_gid;
794         map.sid = alias_sid;
795
796         if (sid_equal(&dom_sid, &global_sid_Builtin))
797                 map.sid_name_use = SID_NAME_WKN_GRP;
798         else
799                 map.sid_name_use = SID_NAME_ALIAS;
800
801         fstrcpy(map.nt_name, name);
802         fstrcpy(map.comment, comment);
803
804         if (insert)
805                 pdb_add_group_mapping_entry(&map);
806         else
807                 pdb_update_group_mapping_entry(&map);
808
809         return NT_STATUS_OK;
810 }
811
812 static NTSTATUS
813 fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
814 {
815 #if 0   /* 
816          * commented out right now after talking to Volker.  Can't
817          * do much with the membership but seemed a shame to waste
818          * somewhat working code.  Needs testing because the membership
819          * that shows up surprises me.  Also can't do much with groups
820          * in groups (e.g. Domain Admins being a member of Adminsitrators).
821          * --jerry
822          */
823         
824         int i;
825         TALLOC_CTX *t = NULL;
826         char **nt_members = NULL;
827         char **unix_members;
828         DOM_SID group_sid;
829         GROUP_MAP map;
830         struct group *grp;
831         enum SID_NAME_USE sid_type;
832
833         if (delta->num_members == 0) {
834                 return NT_STATUS_OK;
835         }
836
837         sid_copy(&group_sid, &dom_sid);
838         sid_append_rid(&group_sid, rid);
839
840         if (sid_equal(&dom_sid, &global_sid_Builtin)) {
841                 sid_type = SID_NAME_WKN_GRP;
842                 if (!get_builtin_group_from_sid(&group_sid, &map, False)) {
843                         DEBUG(0, ("Could not find builtin group %s\n", sid_string_static(&group_sid)));
844                         return NT_STATUS_NO_SUCH_GROUP;
845                 }
846         } else {
847                 sid_type = SID_NAME_ALIAS;
848                 if (!get_local_group_from_sid(&group_sid, &map, False)) {
849                         DEBUG(0, ("Could not find local group %s\n", sid_string_static(&group_sid)));
850                         return NT_STATUS_NO_SUCH_GROUP;
851                 }
852         }       
853
854         if (!(grp = getgrgid(map.gid))) {
855                 DEBUG(0, ("Could not find unix group %d\n", map.gid));
856                 return NT_STATUS_NO_SUCH_GROUP;
857         }
858
859         d_printf("Group members of %s: ", grp->gr_name);
860
861         if (!(t = talloc_init("fetch_group_mem_info"))) {
862                 DEBUG(0, ("could not talloc_init\n"));
863                 return NT_STATUS_NO_MEMORY;
864         }
865
866         nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
867
868         for (i=0; i<delta->num_members; i++) {
869                 NTSTATUS nt_status;
870                 SAM_ACCOUNT *member = NULL;
871                 DOM_SID member_sid;
872
873                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
874                         talloc_destroy(t);
875                         return nt_status;
876                 }
877
878                 sid_copy(&member_sid, &delta->sids[i].sid);
879
880                 if (!pdb_getsampwsid(member, &member_sid)) {
881                         DEBUG(1, ("Found bogus group member: (member_sid=%s group=%s)\n",
882                                   sid_string_static(&member_sid), grp->gr_name));
883                         pdb_free_sam(&member);
884                         continue;
885                 }
886
887                 if (pdb_get_group_rid(member) == rid) {
888                         d_printf("%s(primary),", pdb_get_username(member));
889                         pdb_free_sam(&member);
890                         continue;
891                 }
892                 
893                 d_printf("%s,", pdb_get_username(member));
894                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
895                 pdb_free_sam(&member);
896         }
897
898         d_printf("\n");
899
900         unix_members = grp->gr_mem;
901
902         while (*unix_members) {
903                 BOOL is_nt_member = False;
904                 for (i=0; i<delta->num_members; i++) {
905                         if (nt_members[i] == NULL) {
906                                 /* This was a primary group */
907                                 continue;
908                         }
909
910                         if (strcmp(*unix_members, nt_members[i]) == 0) {
911                                 is_nt_member = True;
912                                 break;
913                         }
914                 }
915                 if (!is_nt_member) {
916                         /* We look at a unix group member that is not
917                            an nt group member. So, remove it. NT is
918                            boss here. */
919                         smb_delete_user_group(grp->gr_name, *unix_members);
920                 }
921                 unix_members += 1;
922         }
923
924         for (i=0; i<delta->num_members; i++) {
925                 BOOL is_unix_member = False;
926
927                 if (nt_members[i] == NULL) {
928                         /* This was the primary group */
929                         continue;
930                 }
931
932                 unix_members = grp->gr_mem;
933
934                 while (*unix_members) {
935                         if (strcmp(*unix_members, nt_members[i]) == 0) {
936                                 is_unix_member = True;
937                                 break;
938                         }
939                         unix_members += 1;
940                 }
941
942                 if (!is_unix_member) {
943                         /* We look at a nt group member that is not a
944                            unix group member currently. So, add the nt
945                            group member. */
946                         smb_add_user_group(grp->gr_name, nt_members[i]);
947                 }
948         }
949         
950         talloc_destroy(t);
951
952 #endif  /* end of fetch_alias_mem() */
953
954         return NT_STATUS_OK;
955 }
956
957 static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
958 {
959         time_t u_max_age, u_min_age, u_logout, u_lockoutreset, u_lockouttime;
960         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
961         pstring domname;
962
963         u_max_age = nt_time_to_unix_abs((NTTIME *)&delta->max_pwd_age);
964         u_min_age = nt_time_to_unix_abs((NTTIME *)&delta->min_pwd_age);
965         u_logout = nt_time_to_unix_abs((NTTIME *)&delta->force_logoff);
966         u_lockoutreset = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.reset_count);
967         u_lockouttime = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.lockout_duration);
968
969         unistr2_to_ascii(domname, &delta->uni_dom_name, sizeof(domname) - 1);
970
971         /* we don't handle BUILTIN account policies */  
972         if (!strequal(domname, get_global_sam_name())) {
973                 printf("skipping SAM_DOMAIN_INFO delta for '%s' (is not my domain)\n", domname);
974                 return NT_STATUS_OK;
975         }
976
977
978         if (!account_policy_set(AP_PASSWORD_HISTORY, delta->pwd_history_len))
979                 return nt_status;
980
981         if (!account_policy_set(AP_MIN_PASSWORD_LEN, delta->min_pwd_len))
982                 return nt_status;
983
984         if (!account_policy_set(AP_MAX_PASSWORD_AGE, (uint32)u_max_age))
985                 return nt_status;
986
987         if (!account_policy_set(AP_MIN_PASSWORD_AGE, (uint32)u_min_age))
988                 return nt_status;
989
990         if (!account_policy_set(AP_TIME_TO_LOGOUT, (uint32)u_logout))
991                 return nt_status;
992
993         if (!account_policy_set(AP_BAD_ATTEMPT_LOCKOUT, delta->account_lockout.bad_attempt_lockout))
994                 return nt_status;
995
996         if (!account_policy_set(AP_RESET_COUNT_TIME, (uint32)u_lockoutreset/60))
997                 return nt_status;
998
999         if (!account_policy_set(AP_LOCK_ACCOUNT_DURATION, (uint32)u_lockouttime/60))
1000                 return nt_status;
1001
1002         if (!account_policy_set(AP_USER_MUST_LOGON_TO_CHG_PASS, delta->logon_chgpass))
1003                 return nt_status;
1004
1005         return NT_STATUS_OK;
1006 }
1007
1008
1009 static void
1010 fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
1011                 DOM_SID dom_sid)
1012 {
1013         switch(hdr_delta->type) {
1014         case SAM_DELTA_ACCOUNT_INFO:
1015                 fetch_account_info(hdr_delta->target_rid,
1016                                    &delta->account_info);
1017                 break;
1018         case SAM_DELTA_GROUP_INFO:
1019                 fetch_group_info(hdr_delta->target_rid,
1020                                  &delta->group_info);
1021                 break;
1022         case SAM_DELTA_GROUP_MEM:
1023                 fetch_group_mem_info(hdr_delta->target_rid,
1024                                      &delta->grp_mem_info);
1025                 break;
1026         case SAM_DELTA_ALIAS_INFO:
1027                 fetch_alias_info(hdr_delta->target_rid,
1028                                  &delta->alias_info, dom_sid);
1029                 break;
1030         case SAM_DELTA_ALIAS_MEM:
1031                 fetch_alias_mem(hdr_delta->target_rid,
1032                                 &delta->als_mem_info, dom_sid);
1033                 break;
1034         case SAM_DELTA_DOMAIN_INFO:
1035                 fetch_domain_info(hdr_delta->target_rid,
1036                                 &delta->domain_info);
1037                 break;
1038         /* The following types are recognised but not handled */
1039         case SAM_DELTA_RENAME_GROUP:
1040                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
1041                 break;
1042         case SAM_DELTA_RENAME_USER:
1043                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
1044                 break;
1045         case SAM_DELTA_RENAME_ALIAS:
1046                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
1047                 break;
1048         case SAM_DELTA_POLICY_INFO:
1049                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
1050                 break;
1051         case SAM_DELTA_TRUST_DOMS:
1052                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
1053                 break;
1054         case SAM_DELTA_PRIVS_INFO:
1055                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
1056                 break;
1057         case SAM_DELTA_SECRET_INFO:
1058                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
1059                 break;
1060         case SAM_DELTA_DELETE_GROUP:
1061                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
1062                 break;
1063         case SAM_DELTA_DELETE_USER:
1064                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
1065                 break;
1066         case SAM_DELTA_MODIFIED_COUNT:
1067                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
1068                 break;
1069         default:
1070                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
1071                 break;
1072         }
1073 }
1074
1075 static NTSTATUS
1076 fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
1077                DOM_SID dom_sid)
1078 {
1079         unsigned sync_context = 0;
1080         NTSTATUS result;
1081         int i;
1082         TALLOC_CTX *mem_ctx;
1083         SAM_DELTA_HDR *hdr_deltas;
1084         SAM_DELTA_CTR *deltas;
1085         uint32 num_deltas;
1086
1087         if (!(mem_ctx = talloc_init("fetch_database")))
1088                 return NT_STATUS_NO_MEMORY;
1089
1090         switch( db_type ) {
1091         case SAM_DATABASE_DOMAIN:
1092                 d_printf("Fetching DOMAIN database\n");
1093                 break;
1094         case SAM_DATABASE_BUILTIN:
1095                 d_printf("Fetching BUILTIN database\n");
1096                 break;
1097         case SAM_DATABASE_PRIVS:
1098                 d_printf("Fetching PRIVS databases\n");
1099                 break;
1100         default:
1101                 d_printf("Fetching unknown database type %u\n", db_type );
1102                 break;
1103         }
1104
1105         do {
1106                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
1107                                                db_type, sync_context,
1108                                                &num_deltas,
1109                                                &hdr_deltas, &deltas);
1110
1111                 if (NT_STATUS_IS_OK(result) ||
1112                     NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1113
1114                         clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
1115                                              ret_creds);
1116
1117                         for (i = 0; i < num_deltas; i++) {
1118                                 fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
1119                         }
1120                 } else
1121                         return result;
1122
1123                 sync_context += 1;
1124         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1125
1126         talloc_destroy(mem_ctx);
1127
1128         return result;
1129 }
1130
1131 /* dump sam database via samsync rpc calls */
1132 NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
1133                                const char *domain_name, 
1134                                struct cli_state *cli, TALLOC_CTX *mem_ctx, 
1135                                int argc, const char **argv) 
1136 {
1137         NTSTATUS result;
1138         uchar trust_password[16];
1139         DOM_CRED ret_creds;
1140         fstring my_dom_sid_str;
1141         fstring rem_dom_sid_str;
1142         uint32 sec_channel;
1143
1144         ZERO_STRUCT(ret_creds);
1145
1146         if (!sid_equal(domain_sid, get_global_sam_sid())) {
1147                 d_printf("Cannot import users from %s at this time, "
1148                          "as the current domain:\n\t%s: %s\nconflicts "
1149                          "with the remote domain\n\t%s: %s\n"
1150                          "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
1151                          domain_name,
1152                          get_global_sam_name(), sid_to_string(my_dom_sid_str, 
1153                                                               get_global_sam_sid()),
1154                          domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
1155                          domain_name);
1156                 return NT_STATUS_UNSUCCESSFUL;
1157         }
1158
1159         fstrcpy(cli->domain, domain_name);
1160
1161         if (!secrets_fetch_trust_account_password(domain_name,
1162                                                   trust_password, NULL,
1163                                                   &sec_channel)) {
1164                 result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1165                 d_printf("Could not retrieve domain trust secret\n");
1166                 goto fail;
1167         }
1168         
1169         result = cli_nt_establish_netlogon(cli, sec_channel, trust_password);
1170
1171         if (!NT_STATUS_IS_OK(result)) {
1172                 d_printf("Failed to setup BDC creds\n");
1173                 goto fail;
1174         }
1175
1176         result = fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds, *domain_sid);
1177
1178         if (!NT_STATUS_IS_OK(result)) {
1179                 d_printf("Failed to fetch domain database: %s\n",
1180                          nt_errstr(result));
1181                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
1182                         d_printf("Perhaps %s is a Windows 2000 native mode "
1183                                  "domain?\n", domain_name);
1184                 goto fail;
1185         }
1186
1187         result = fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, 
1188                                 global_sid_Builtin);
1189
1190         if (!NT_STATUS_IS_OK(result)) {
1191                 d_printf("Failed to fetch builtin database: %s\n",
1192                          nt_errstr(result));
1193                 goto fail;
1194         }
1195
1196         /* Currently we crash on PRIVS somewhere in unmarshalling */
1197         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
1198
1199 fail:
1200         return result;
1201 }