r8786: Fix amazing and long-standing bug where user-accounts are just crippled
[tprouty/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    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2005
8    Modified by Volker Lendecke 2002
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "utils/net.h"
27
28 /* uid's and gid's for writing deltas to ldif */
29 static uint32 ldif_gid = 999;
30 static uint32 ldif_uid = 999;
31 /* Kkeep track of ldap initialization */
32 static int init_ldap = 1;
33
34 static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
35 {
36         int i;
37         d_printf("Group mem %u: ", rid);
38         for (i=0;i<g->num_members;i++) {
39                 d_printf("%u ", g->rids[i]);
40         }
41         d_printf("\n");
42 }
43
44
45 static const char *display_time(NTTIME *nttime)
46 {
47         static fstring string;
48
49         float high;
50         float low;
51         int sec;
52         int days, hours, mins, secs;
53         int offset = 1;
54
55         if (nttime->high==0 && nttime->low==0)
56                 return "Now";
57
58         if (nttime->high==0x80000000 && nttime->low==0)
59                 return "Never";
60
61         high = 65536;   
62         high = high/10000;
63         high = high*65536;
64         high = high/1000;
65         high = high * (~nttime->high);
66
67         low = ~nttime->low;     
68         low = low/(1000*1000*10);
69
70         sec=high+low;
71         sec+=offset;
72
73         days=sec/(60*60*24);
74         hours=(sec - (days*60*60*24)) / (60*60);
75         mins=(sec - (days*60*60*24) - (hours*60*60) ) / 60;
76         secs=sec - (days*60*60*24) - (hours*60*60) - (mins*60);
77
78         fstr_sprintf(string, "%u days, %u hours, %u minutes, %u seconds", days, hours, mins, secs);
79         return (string);
80 }
81
82
83 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
84 {
85         d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
86         d_printf("desc='%s' rid=%u\n", unistr2_static(&a->uni_als_desc), a->als_rid);
87 }
88
89 static void display_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *a)
90 {
91         int i;
92         d_printf("Alias rid %u: ", rid);
93         for (i=0;i<a->num_members;i++) {
94                 d_printf("%s ", sid_string_static(&a->sids[i].sid));
95         }
96         d_printf("\n");
97 }
98
99 static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
100 {
101         fstring hex_nt_passwd, hex_lm_passwd;
102         uchar lm_passwd[16], nt_passwd[16];
103         static uchar zero_buf[16];
104
105         /* Decode hashes from password hash (if they are not NULL) */
106         
107         if (memcmp(a->pass.buf_lm_pwd, zero_buf, 16) != 0) {
108                 sam_pwd_hash(a->user_rid, a->pass.buf_lm_pwd, lm_passwd, 0);
109                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
110         } else {
111                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
112         }
113
114         if (memcmp(a->pass.buf_nt_pwd, zero_buf, 16) != 0) {
115                 sam_pwd_hash(a->user_rid, a->pass.buf_nt_pwd, nt_passwd, 0);
116                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
117         } else {
118                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
119         }
120         
121         printf("%s:%d:%s:%s:%s:LCT-0\n", unistr2_static(&a->uni_acct_name),
122                a->user_rid, hex_lm_passwd, hex_nt_passwd,
123                pdb_encode_acct_ctrl(a->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN));
124 }
125
126 static void display_domain_info(SAM_DOMAIN_INFO *a)
127 {
128         time_t u_logout;
129
130         u_logout = nt_time_to_unix_abs((NTTIME *)&a->force_logoff);
131
132         d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
133
134         d_printf("Minimal Password Length: %d\n", a->min_pwd_len);
135         d_printf("Password History Length: %d\n", a->pwd_history_len);
136
137         d_printf("Force Logoff: %d\n", (int)u_logout);
138
139         d_printf("Max Password Age: %s\n", display_time((NTTIME *)&a->max_pwd_age));
140         d_printf("Min Password Age: %s\n", display_time((NTTIME *)&a->min_pwd_age));
141
142         d_printf("Lockout Time: %s\n", display_time((NTTIME *)&a->account_lockout.lockout_duration));
143         d_printf("Lockout Reset Time: %s\n", display_time((NTTIME *)&a->account_lockout.reset_count));
144
145         d_printf("Bad Attempt Lockout: %d\n", a->account_lockout.bad_attempt_lockout);
146         d_printf("User must logon to change password: %d\n", a->logon_chgpass);
147 }
148
149 static void display_group_info(uint32 rid, SAM_GROUP_INFO *a)
150 {
151         d_printf("Group '%s' ", unistr2_static(&a->uni_grp_name));
152         d_printf("desc='%s', rid=%u\n", unistr2_static(&a->uni_grp_desc), rid);
153 }
154
155 static void display_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta)
156 {
157         switch (hdr_delta->type) {
158         case SAM_DELTA_ACCOUNT_INFO:
159                 display_account_info(hdr_delta->target_rid, &delta->account_info);
160                 break;
161         case SAM_DELTA_GROUP_MEM:
162                 display_group_mem_info(hdr_delta->target_rid, &delta->grp_mem_info);
163                 break;
164         case SAM_DELTA_ALIAS_INFO:
165                 display_alias_info(hdr_delta->target_rid, &delta->alias_info);
166                 break;
167         case SAM_DELTA_ALIAS_MEM:
168                 display_alias_mem(hdr_delta->target_rid, &delta->als_mem_info);
169                 break;
170         case SAM_DELTA_DOMAIN_INFO:
171                 display_domain_info(&delta->domain_info);
172                 break;
173         case SAM_DELTA_GROUP_INFO:
174                 display_group_info(hdr_delta->target_rid, &delta->group_info);
175                 break;
176                 /* The following types are recognised but not handled */
177         case SAM_DELTA_RENAME_GROUP:
178                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
179                 break;
180         case SAM_DELTA_RENAME_USER:
181                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
182                 break;
183         case SAM_DELTA_RENAME_ALIAS:
184                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
185                 break;
186         case SAM_DELTA_POLICY_INFO:
187                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
188                 break;
189         case SAM_DELTA_TRUST_DOMS:
190                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
191                 break;
192         case SAM_DELTA_PRIVS_INFO:
193                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
194                 break;
195         case SAM_DELTA_SECRET_INFO:
196                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
197                 break;
198         case SAM_DELTA_DELETE_GROUP:
199                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
200                 break;
201         case SAM_DELTA_DELETE_USER:
202                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
203                 break;
204         case SAM_DELTA_MODIFIED_COUNT:
205                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
206                 break;
207         default:
208                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
209                 break;
210         }
211 }
212
213
214 static void dump_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds)
215 {
216         unsigned sync_context = 0;
217         NTSTATUS result;
218         int i;
219         TALLOC_CTX *mem_ctx;
220         SAM_DELTA_HDR *hdr_deltas;
221         SAM_DELTA_CTR *deltas;
222         uint32 num_deltas;
223
224         if (!(mem_ctx = talloc_init("dump_database"))) {
225                 return;
226         }
227
228         switch( db_type ) {
229         case SAM_DATABASE_DOMAIN:
230                 d_printf("Dumping DOMAIN database\n");
231                 break;
232         case SAM_DATABASE_BUILTIN:
233                 d_printf("Dumping BUILTIN database\n");
234                 break;
235         case SAM_DATABASE_PRIVS:
236                 d_printf("Dumping PRIVS databases\n");
237                 break;
238         default:
239                 d_printf("Dumping unknown database type %u\n", db_type );
240                 break;
241         }
242
243         do {
244                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds, db_type,
245                                                sync_context,
246                                                &num_deltas, &hdr_deltas, &deltas);
247                 if (NT_STATUS_IS_ERR(result))
248                         break;
249
250                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), ret_creds);
251                 for (i = 0; i < num_deltas; i++) {
252                         display_sam_entry(&hdr_deltas[i], &deltas[i]);
253                 }
254                 sync_context += 1;
255         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
256
257         talloc_destroy(mem_ctx);
258 }
259
260 /* dump sam database via samsync rpc calls */
261 NTSTATUS rpc_samdump_internals(const DOM_SID *domain_sid, 
262                                const char *domain_name, 
263                                struct cli_state *cli, TALLOC_CTX *mem_ctx, 
264                                int argc, const char **argv) 
265 {
266         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
267         uchar trust_password[16];
268         DOM_CRED ret_creds;
269         uint32 sec_channel;
270
271         ZERO_STRUCT(ret_creds);
272
273         fstrcpy(cli->domain, domain_name);
274
275         if (!secrets_fetch_trust_account_password(domain_name,
276                                                   trust_password,
277                                                   NULL, &sec_channel)) {
278                 DEBUG(0,("Could not fetch trust account password\n"));
279                 goto fail;
280         }
281
282         if (!NT_STATUS_IS_OK(nt_status = cli_nt_establish_netlogon(cli, sec_channel,
283                                                                    trust_password))) {
284                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
285                 goto fail;
286         }
287
288         dump_database(cli, SAM_DATABASE_DOMAIN, &ret_creds);
289         dump_database(cli, SAM_DATABASE_BUILTIN, &ret_creds);
290         dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds);
291
292         nt_status = NT_STATUS_OK;
293
294 fail:
295         cli_nt_session_close(cli);
296         return nt_status;
297 }
298
299 /* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
300 #define STRING_CHANGED (old_string && !new_string) ||\
301                     (!old_string && new_string) ||\
302                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
303
304 static NTSTATUS
305 sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
306 {
307         const char *old_string, *new_string;
308         time_t unix_time, stored_time;
309         uchar lm_passwd[16], nt_passwd[16];
310         static uchar zero_buf[16];
311
312         /* Username, fullname, home dir, dir drive, logon script, acct
313            desc, workstations, profile. */
314
315         if (delta->hdr_acct_name.buffer) {
316                 old_string = pdb_get_nt_username(account);
317                 new_string = unistr2_static(&delta->uni_acct_name);
318
319                 if (STRING_CHANGED) {
320                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
321               
322                 }
323          
324                 /* Unix username is the same - for sanity */
325                 old_string = pdb_get_username( account );
326                 if (STRING_CHANGED) {
327                         pdb_set_username(account, new_string, PDB_CHANGED);
328                 }
329         }
330
331         if (delta->hdr_full_name.buffer) {
332                 old_string = pdb_get_fullname(account);
333                 new_string = unistr2_static(&delta->uni_full_name);
334
335                 if (STRING_CHANGED)
336                         pdb_set_fullname(account, new_string, PDB_CHANGED);
337         }
338
339         if (delta->hdr_home_dir.buffer) {
340                 old_string = pdb_get_homedir(account);
341                 new_string = unistr2_static(&delta->uni_home_dir);
342
343                 if (STRING_CHANGED)
344                         pdb_set_homedir(account, new_string, PDB_CHANGED);
345         }
346
347         if (delta->hdr_dir_drive.buffer) {
348                 old_string = pdb_get_dir_drive(account);
349                 new_string = unistr2_static(&delta->uni_dir_drive);
350
351                 if (STRING_CHANGED)
352                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
353         }
354
355         if (delta->hdr_logon_script.buffer) {
356                 old_string = pdb_get_logon_script(account);
357                 new_string = unistr2_static(&delta->uni_logon_script);
358
359                 if (STRING_CHANGED)
360                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
361         }
362
363         if (delta->hdr_acct_desc.buffer) {
364                 old_string = pdb_get_acct_desc(account);
365                 new_string = unistr2_static(&delta->uni_acct_desc);
366
367                 if (STRING_CHANGED)
368                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
369         }
370
371         if (delta->hdr_workstations.buffer) {
372                 old_string = pdb_get_workstations(account);
373                 new_string = unistr2_static(&delta->uni_workstations);
374
375                 if (STRING_CHANGED)
376                         pdb_set_workstations(account, new_string, PDB_CHANGED);
377         }
378
379         if (delta->hdr_profile.buffer) {
380                 old_string = pdb_get_profile_path(account);
381                 new_string = unistr2_static(&delta->uni_profile);
382
383                 if (STRING_CHANGED)
384                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
385         }
386
387         if (delta->hdr_parameters.buffer) {
388                 DATA_BLOB mung;
389                 old_string = pdb_get_munged_dial(account);
390                 mung.length = delta->hdr_parameters.uni_str_len;
391                 mung.data = (uint8 *) delta->uni_parameters.buffer;
392                 new_string = (mung.length == 0) ? NULL : base64_encode_data_blob(mung);
393
394                 if (STRING_CHANGED)
395                         pdb_set_munged_dial(account, new_string, PDB_CHANGED);
396         }
397
398         /* User and group sid */
399         if (pdb_get_user_rid(account) != delta->user_rid)
400                 pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
401         if (pdb_get_group_rid(account) != delta->group_rid)
402                 pdb_set_group_sid_from_rid(account, delta->group_rid, PDB_CHANGED);
403
404         /* Logon and password information */
405         if (!nt_time_is_zero(&delta->logon_time)) {
406                 unix_time = nt_time_to_unix(&delta->logon_time);
407                 stored_time = pdb_get_logon_time(account);
408                 if (stored_time != unix_time)
409                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
410         }
411
412         if (!nt_time_is_zero(&delta->logoff_time)) {
413                 unix_time = nt_time_to_unix(&delta->logoff_time);
414                 stored_time = pdb_get_logoff_time(account);
415                 if (stored_time != unix_time)
416                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
417         }
418
419         /* Logon Divs */
420         if (pdb_get_logon_divs(account) != delta->logon_divs)
421                 pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
422
423         /* Max Logon Hours */
424         if (delta->unknown1 != pdb_get_unknown_6(account)) {
425                 pdb_set_unknown_6(account, delta->unknown1, PDB_CHANGED);
426         }
427
428         /* Logon Hours Len */
429         if (delta->buf_logon_hrs.buf_len != pdb_get_hours_len(account)) {
430                 pdb_set_hours_len(account, delta->buf_logon_hrs.buf_len, PDB_CHANGED);
431         }
432
433         /* Logon Hours */
434         if (delta->buf_logon_hrs.buffer) {
435                 pstring oldstr, newstr;
436                 pdb_sethexhours(oldstr, pdb_get_hours(account));
437                 pdb_sethexhours(newstr, delta->buf_logon_hrs.buffer);
438                 if (!strequal(oldstr, newstr))
439                         pdb_set_hours(account, (const uint8 *)delta->buf_logon_hrs.buffer, PDB_CHANGED);
440         }
441
442         if (pdb_get_bad_password_count(account) != delta->bad_pwd_count)
443                 pdb_set_bad_password_count(account, delta->bad_pwd_count, PDB_CHANGED);
444
445         if (pdb_get_logon_count(account) != delta->logon_count)
446                 pdb_set_logon_count(account, delta->logon_count, PDB_CHANGED);
447
448         if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
449                 unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
450                 stored_time = pdb_get_pass_last_set_time(account);
451                 if (stored_time != unix_time)
452                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
453         } else {
454                 /* no last set time, make it now */
455                 pdb_set_pass_last_set_time(account, time(NULL), PDB_CHANGED);
456         }
457
458 #if 0
459 /*      No kickoff time in the delta? */
460         if (!nt_time_is_zero(&delta->kickoff_time)) {
461                 unix_time = nt_time_to_unix(&delta->kickoff_time);
462                 stored_time = pdb_get_kickoff_time(account);
463                 if (stored_time != unix_time)
464                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
465         }
466 #endif
467
468         /* Decode hashes from password hash 
469            Note that win2000 may send us all zeros for the hashes if it doesn't 
470            think this channel is secure enough - don't set the passwords at all
471            in that case
472         */
473         if (memcmp(delta->pass.buf_lm_pwd, zero_buf, 16) != 0) {
474                 sam_pwd_hash(delta->user_rid, delta->pass.buf_lm_pwd, lm_passwd, 0);
475                 pdb_set_lanman_passwd(account, lm_passwd, PDB_CHANGED);
476         }
477
478         if (memcmp(delta->pass.buf_nt_pwd, zero_buf, 16) != 0) {
479                 sam_pwd_hash(delta->user_rid, delta->pass.buf_nt_pwd, nt_passwd, 0);
480                 pdb_set_nt_passwd(account, nt_passwd, PDB_CHANGED);
481         }
482
483         /* TODO: account expiry time */
484
485         pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
486
487         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
488
489         return NT_STATUS_OK;
490 }
491
492 static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
493 {
494         NTSTATUS nt_ret;
495         fstring account;
496         pstring add_script;
497         SAM_ACCOUNT *sam_account=NULL;
498         GROUP_MAP map;
499         struct group *grp;
500         DOM_SID user_sid;
501         DOM_SID group_sid;
502         struct passwd *passwd;
503         fstring sid_string;
504
505         fstrcpy(account, unistr2_static(&delta->uni_acct_name));
506         d_printf("Creating account: %s\n", account);
507
508         if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
509                 return nt_ret;
510
511         if (!(passwd = Get_Pwnam(account))) {
512                 /* Create appropriate user */
513                 if (delta->acb_info & ACB_NORMAL) {
514                         pstrcpy(add_script, lp_adduser_script());
515                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
516                             (delta->acb_info & ACB_SVRTRUST) ||
517                             (delta->acb_info & ACB_DOMTRUST) ) {
518                         pstrcpy(add_script, lp_addmachine_script());
519                 } else {
520                         DEBUG(1, ("Unknown user type: %s\n",
521                                   pdb_encode_acct_ctrl(delta->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
522                         nt_ret = NT_STATUS_UNSUCCESSFUL;
523                         goto done;
524                 }
525                 if (*add_script) {
526                         int add_ret;
527                         all_string_sub(add_script, "%u", account,
528                                        sizeof(account));
529                         add_ret = smbrun(add_script,NULL);
530                         DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
531                                  "gave %d\n", add_script, add_ret));
532                 } 
533                 
534                 /* try and find the possible unix account again */
535                 if ( !(passwd = Get_Pwnam(account)) ) {
536                         d_printf("Could not create posix account info for '%s'\n", account);
537                         nt_ret = NT_STATUS_NO_SUCH_USER;
538                         goto done;
539                 }
540         }
541         
542         sid_copy(&user_sid, get_global_sam_sid());
543         sid_append_rid(&user_sid, delta->user_rid);
544
545         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n", sid_to_string(sid_string, &user_sid), account));
546         if (!pdb_getsampwsid(sam_account, &user_sid)) {
547                 sam_account_from_delta(sam_account, delta);
548                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
549                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
550                 if (!pdb_add_sam_account(sam_account)) {
551                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
552                                   account));
553                         return NT_STATUS_ACCESS_DENIED; 
554                 }
555         } else {
556                 sam_account_from_delta(sam_account, delta);
557                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
558                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
559                 if (!pdb_update_sam_account(sam_account)) {
560                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
561                                   account));
562                         pdb_free_sam(&sam_account);
563                         return NT_STATUS_ACCESS_DENIED; 
564                 }
565         }
566
567         group_sid = *pdb_get_group_sid(sam_account);
568
569         if (!pdb_getgrsid(&map, group_sid)) {
570                 DEBUG(0, ("Primary group of %s has no mapping!\n",
571                           pdb_get_username(sam_account)));
572         } else {
573                 if (map.gid != passwd->pw_gid) {
574                         if (!(grp = getgrgid(map.gid))) {
575                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
576                                           (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_static(&group_sid)));
577                         } else {
578                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
579                         }
580                 }
581         }       
582
583         if ( !passwd ) {
584                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
585                         pdb_get_username(sam_account)));
586         }
587
588  done:
589         pdb_free_sam(&sam_account);
590         return nt_ret;
591 }
592
593 static NTSTATUS
594 fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
595 {
596         fstring name;
597         fstring comment;
598         struct group *grp = NULL;
599         DOM_SID group_sid;
600         fstring sid_string;
601         GROUP_MAP map;
602         BOOL insert = True;
603
604         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name)-1);
605         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment)-1);
606
607         /* add the group to the mapping table */
608         sid_copy(&group_sid, get_global_sam_sid());
609         sid_append_rid(&group_sid, rid);
610         sid_to_string(sid_string, &group_sid);
611
612         if (pdb_getgrsid(&map, group_sid)) {
613                 if ( map.gid != -1 )
614                         grp = getgrgid(map.gid);
615                 insert = False;
616         }
617
618         if (grp == NULL) {
619                 gid_t gid;
620
621                 /* No group found from mapping, find it from its name. */
622                 if ((grp = getgrnam(name)) == NULL) {
623                 
624                         /* No appropriate group found, create one */
625                         
626                         d_printf("Creating unix group: '%s'\n", name);
627                         
628                         if (smb_create_group(name, &gid) != 0)
629                                 return NT_STATUS_ACCESS_DENIED;
630                                 
631                         if ((grp = getgrnam(name)) == NULL)
632                                 return NT_STATUS_ACCESS_DENIED;
633                 }
634         }
635
636         map.gid = grp->gr_gid;
637         map.sid = group_sid;
638         map.sid_name_use = SID_NAME_DOM_GRP;
639         fstrcpy(map.nt_name, name);
640         if (delta->hdr_grp_desc.buffer) {
641                 fstrcpy(map.comment, comment);
642         } else {
643                 fstrcpy(map.comment, "");
644         }
645
646         if (insert)
647                 pdb_add_group_mapping_entry(&map);
648         else
649                 pdb_update_group_mapping_entry(&map);
650
651         return NT_STATUS_OK;
652 }
653
654 static NTSTATUS
655 fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
656 {
657         int i;
658         TALLOC_CTX *t = NULL;
659         char **nt_members = NULL;
660         char **unix_members;
661         DOM_SID group_sid;
662         GROUP_MAP map;
663         struct group *grp;
664
665         if (delta->num_members == 0) {
666                 return NT_STATUS_OK;
667         }
668
669         sid_copy(&group_sid, get_global_sam_sid());
670         sid_append_rid(&group_sid, rid);
671
672         if (!get_domain_group_from_sid(group_sid, &map)) {
673                 DEBUG(0, ("Could not find global group %d\n", rid));
674                 return NT_STATUS_NO_SUCH_GROUP;
675         }
676
677         if (!(grp = getgrgid(map.gid))) {
678                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
679                 return NT_STATUS_NO_SUCH_GROUP;
680         }
681
682         d_printf("Group members of %s: ", grp->gr_name);
683
684         if (!(t = talloc_init("fetch_group_mem_info"))) {
685                 DEBUG(0, ("could not talloc_init\n"));
686                 return NT_STATUS_NO_MEMORY;
687         }
688
689         nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
690
691         for (i=0; i<delta->num_members; i++) {
692                 NTSTATUS nt_status;
693                 SAM_ACCOUNT *member = NULL;
694                 DOM_SID member_sid;
695
696                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
697                         talloc_destroy(t);
698                         return nt_status;
699                 }
700
701                 sid_copy(&member_sid, get_global_sam_sid());
702                 sid_append_rid(&member_sid, delta->rids[i]);
703
704                 if (!pdb_getsampwsid(member, &member_sid)) {
705                         DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
706                                   delta->rids[i], sid_string_static(&member_sid), grp->gr_name));
707                         pdb_free_sam(&member);
708                         continue;
709                 }
710
711                 if (pdb_get_group_rid(member) == rid) {
712                         d_printf("%s(primary),", pdb_get_username(member));
713                         pdb_free_sam(&member);
714                         continue;
715                 }
716                 
717                 d_printf("%s,", pdb_get_username(member));
718                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
719                 pdb_free_sam(&member);
720         }
721
722         d_printf("\n");
723
724         unix_members = grp->gr_mem;
725
726         while (*unix_members) {
727                 BOOL is_nt_member = False;
728                 for (i=0; i<delta->num_members; i++) {
729                         if (nt_members[i] == NULL) {
730                                 /* This was a primary group */
731                                 continue;
732                         }
733
734                         if (strcmp(*unix_members, nt_members[i]) == 0) {
735                                 is_nt_member = True;
736                                 break;
737                         }
738                 }
739                 if (!is_nt_member) {
740                         /* We look at a unix group member that is not
741                            an nt group member. So, remove it. NT is
742                            boss here. */
743                         smb_delete_user_group(grp->gr_name, *unix_members);
744                 }
745                 unix_members += 1;
746         }
747
748         for (i=0; i<delta->num_members; i++) {
749                 BOOL is_unix_member = False;
750
751                 if (nt_members[i] == NULL) {
752                         /* This was the primary group */
753                         continue;
754                 }
755
756                 unix_members = grp->gr_mem;
757
758                 while (*unix_members) {
759                         if (strcmp(*unix_members, nt_members[i]) == 0) {
760                                 is_unix_member = True;
761                                 break;
762                         }
763                         unix_members += 1;
764                 }
765
766                 if (!is_unix_member) {
767                         /* We look at a nt group member that is not a
768                            unix group member currently. So, add the nt
769                            group member. */
770                         smb_add_user_group(grp->gr_name, nt_members[i]);
771                 }
772         }
773         
774         talloc_destroy(t);
775         return NT_STATUS_OK;
776 }
777
778 static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
779                                  DOM_SID dom_sid)
780 {
781         fstring name;
782         fstring comment;
783         struct group *grp = NULL;
784         DOM_SID alias_sid;
785         fstring sid_string;
786         GROUP_MAP map;
787         BOOL insert = True;
788
789         unistr2_to_ascii(name, &delta->uni_als_name, sizeof(name)-1);
790         unistr2_to_ascii(comment, &delta->uni_als_desc, sizeof(comment)-1);
791
792         /* Find out whether the group is already mapped */
793         sid_copy(&alias_sid, &dom_sid);
794         sid_append_rid(&alias_sid, rid);
795         sid_to_string(sid_string, &alias_sid);
796
797         if (pdb_getgrsid(&map, alias_sid)) {
798                 grp = getgrgid(map.gid);
799                 insert = False;
800         }
801
802         if (grp == NULL) {
803                 gid_t gid;
804
805                 /* No group found from mapping, find it from its name. */
806                 if ((grp = getgrnam(name)) == NULL) {
807                         /* No appropriate group found, create one */
808                         d_printf("Creating unix group: '%s'\n", name);
809                         if (smb_create_group(name, &gid) != 0)
810                                 return NT_STATUS_ACCESS_DENIED;
811                         if ((grp = getgrgid(gid)) == NULL)
812                                 return NT_STATUS_ACCESS_DENIED;
813                 }
814         }
815
816         map.gid = grp->gr_gid;
817         map.sid = alias_sid;
818
819         if (sid_equal(&dom_sid, &global_sid_Builtin))
820                 map.sid_name_use = SID_NAME_WKN_GRP;
821         else
822                 map.sid_name_use = SID_NAME_ALIAS;
823
824         fstrcpy(map.nt_name, name);
825         fstrcpy(map.comment, comment);
826
827         if (insert)
828                 pdb_add_group_mapping_entry(&map);
829         else
830                 pdb_update_group_mapping_entry(&map);
831
832         return NT_STATUS_OK;
833 }
834
835 static NTSTATUS
836 fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
837 {
838 #if 0   /* 
839          * commented out right now after talking to Volker.  Can't
840          * do much with the membership but seemed a shame to waste
841          * somewhat working code.  Needs testing because the membership
842          * that shows up surprises me.  Also can't do much with groups
843          * in groups (e.g. Domain Admins being a member of Adminsitrators).
844          * --jerry
845          */
846         
847         int i;
848         TALLOC_CTX *t = NULL;
849         char **nt_members = NULL;
850         char **unix_members;
851         DOM_SID group_sid;
852         GROUP_MAP map;
853         struct group *grp;
854         enum SID_NAME_USE sid_type;
855
856         if (delta->num_members == 0) {
857                 return NT_STATUS_OK;
858         }
859
860         sid_copy(&group_sid, &dom_sid);
861         sid_append_rid(&group_sid, rid);
862
863         if (sid_equal(&dom_sid, &global_sid_Builtin)) {
864                 sid_type = SID_NAME_WKN_GRP;
865                 if (!get_builtin_group_from_sid(&group_sid, &map, False)) {
866                         DEBUG(0, ("Could not find builtin group %s\n", sid_string_static(&group_sid)));
867                         return NT_STATUS_NO_SUCH_GROUP;
868                 }
869         } else {
870                 sid_type = SID_NAME_ALIAS;
871                 if (!get_local_group_from_sid(&group_sid, &map, False)) {
872                         DEBUG(0, ("Could not find local group %s\n", sid_string_static(&group_sid)));
873                         return NT_STATUS_NO_SUCH_GROUP;
874                 }
875         }       
876
877         if (!(grp = getgrgid(map.gid))) {
878                 DEBUG(0, ("Could not find unix group %d\n", map.gid));
879                 return NT_STATUS_NO_SUCH_GROUP;
880         }
881
882         d_printf("Group members of %s: ", grp->gr_name);
883
884         if (!(t = talloc_init("fetch_group_mem_info"))) {
885                 DEBUG(0, ("could not talloc_init\n"));
886                 return NT_STATUS_NO_MEMORY;
887         }
888
889         nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
890
891         for (i=0; i<delta->num_members; i++) {
892                 NTSTATUS nt_status;
893                 SAM_ACCOUNT *member = NULL;
894                 DOM_SID member_sid;
895
896                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
897                         talloc_destroy(t);
898                         return nt_status;
899                 }
900
901                 sid_copy(&member_sid, &delta->sids[i].sid);
902
903                 if (!pdb_getsampwsid(member, &member_sid)) {
904                         DEBUG(1, ("Found bogus group member: (member_sid=%s group=%s)\n",
905                                   sid_string_static(&member_sid), grp->gr_name));
906                         pdb_free_sam(&member);
907                         continue;
908                 }
909
910                 if (pdb_get_group_rid(member) == rid) {
911                         d_printf("%s(primary),", pdb_get_username(member));
912                         pdb_free_sam(&member);
913                         continue;
914                 }
915                 
916                 d_printf("%s,", pdb_get_username(member));
917                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
918                 pdb_free_sam(&member);
919         }
920
921         d_printf("\n");
922
923         unix_members = grp->gr_mem;
924
925         while (*unix_members) {
926                 BOOL is_nt_member = False;
927                 for (i=0; i<delta->num_members; i++) {
928                         if (nt_members[i] == NULL) {
929                                 /* This was a primary group */
930                                 continue;
931                         }
932
933                         if (strcmp(*unix_members, nt_members[i]) == 0) {
934                                 is_nt_member = True;
935                                 break;
936                         }
937                 }
938                 if (!is_nt_member) {
939                         /* We look at a unix group member that is not
940                            an nt group member. So, remove it. NT is
941                            boss here. */
942                         smb_delete_user_group(grp->gr_name, *unix_members);
943                 }
944                 unix_members += 1;
945         }
946
947         for (i=0; i<delta->num_members; i++) {
948                 BOOL is_unix_member = False;
949
950                 if (nt_members[i] == NULL) {
951                         /* This was the primary group */
952                         continue;
953                 }
954
955                 unix_members = grp->gr_mem;
956
957                 while (*unix_members) {
958                         if (strcmp(*unix_members, nt_members[i]) == 0) {
959                                 is_unix_member = True;
960                                 break;
961                         }
962                         unix_members += 1;
963                 }
964
965                 if (!is_unix_member) {
966                         /* We look at a nt group member that is not a
967                            unix group member currently. So, add the nt
968                            group member. */
969                         smb_add_user_group(grp->gr_name, nt_members[i]);
970                 }
971         }
972         
973         talloc_destroy(t);
974
975 #endif  /* end of fetch_alias_mem() */
976
977         return NT_STATUS_OK;
978 }
979
980 static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
981 {
982         time_t u_max_age, u_min_age, u_logout, u_lockoutreset, u_lockouttime;
983         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
984         pstring domname;
985
986         u_max_age = nt_time_to_unix_abs((NTTIME *)&delta->max_pwd_age);
987         u_min_age = nt_time_to_unix_abs((NTTIME *)&delta->min_pwd_age);
988         u_logout = nt_time_to_unix_abs((NTTIME *)&delta->force_logoff);
989         u_lockoutreset = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.reset_count);
990         u_lockouttime = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.lockout_duration);
991
992         unistr2_to_ascii(domname, &delta->uni_dom_name, sizeof(domname) - 1);
993
994         /* we don't handle BUILTIN account policies */  
995         if (!strequal(domname, get_global_sam_name())) {
996                 printf("skipping SAM_DOMAIN_INFO delta for '%s' (is not my domain)\n", domname);
997                 return NT_STATUS_OK;
998         }
999
1000
1001         if (!account_policy_set(AP_PASSWORD_HISTORY, delta->pwd_history_len))
1002                 return nt_status;
1003
1004         if (!account_policy_set(AP_MIN_PASSWORD_LEN, delta->min_pwd_len))
1005                 return nt_status;
1006
1007         if (!account_policy_set(AP_MAX_PASSWORD_AGE, (uint32)u_max_age))
1008                 return nt_status;
1009
1010         if (!account_policy_set(AP_MIN_PASSWORD_AGE, (uint32)u_min_age))
1011                 return nt_status;
1012
1013         if (!account_policy_set(AP_TIME_TO_LOGOUT, (uint32)u_logout))
1014                 return nt_status;
1015
1016         if (!account_policy_set(AP_BAD_ATTEMPT_LOCKOUT, delta->account_lockout.bad_attempt_lockout))
1017                 return nt_status;
1018
1019         if (!account_policy_set(AP_RESET_COUNT_TIME, (uint32)u_lockoutreset/60))
1020                 return nt_status;
1021
1022         if (u_lockouttime != -1)
1023                 u_lockouttime /= 60;
1024
1025         if (!account_policy_set(AP_LOCK_ACCOUNT_DURATION, (uint32)u_lockouttime))
1026                 return nt_status;
1027
1028         if (!account_policy_set(AP_USER_MUST_LOGON_TO_CHG_PASS, delta->logon_chgpass))
1029                 return nt_status;
1030
1031         return NT_STATUS_OK;
1032 }
1033
1034
1035 static void
1036 fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
1037                 DOM_SID dom_sid)
1038 {
1039         switch(hdr_delta->type) {
1040         case SAM_DELTA_ACCOUNT_INFO:
1041                 fetch_account_info(hdr_delta->target_rid,
1042                                    &delta->account_info);
1043                 break;
1044         case SAM_DELTA_GROUP_INFO:
1045                 fetch_group_info(hdr_delta->target_rid,
1046                                  &delta->group_info);
1047                 break;
1048         case SAM_DELTA_GROUP_MEM:
1049                 fetch_group_mem_info(hdr_delta->target_rid,
1050                                      &delta->grp_mem_info);
1051                 break;
1052         case SAM_DELTA_ALIAS_INFO:
1053                 fetch_alias_info(hdr_delta->target_rid,
1054                                  &delta->alias_info, dom_sid);
1055                 break;
1056         case SAM_DELTA_ALIAS_MEM:
1057                 fetch_alias_mem(hdr_delta->target_rid,
1058                                 &delta->als_mem_info, dom_sid);
1059                 break;
1060         case SAM_DELTA_DOMAIN_INFO:
1061                 fetch_domain_info(hdr_delta->target_rid,
1062                                 &delta->domain_info);
1063                 break;
1064         /* The following types are recognised but not handled */
1065         case SAM_DELTA_RENAME_GROUP:
1066                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
1067                 break;
1068         case SAM_DELTA_RENAME_USER:
1069                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
1070                 break;
1071         case SAM_DELTA_RENAME_ALIAS:
1072                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
1073                 break;
1074         case SAM_DELTA_POLICY_INFO:
1075                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
1076                 break;
1077         case SAM_DELTA_TRUST_DOMS:
1078                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
1079                 break;
1080         case SAM_DELTA_PRIVS_INFO:
1081                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
1082                 break;
1083         case SAM_DELTA_SECRET_INFO:
1084                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
1085                 break;
1086         case SAM_DELTA_DELETE_GROUP:
1087                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
1088                 break;
1089         case SAM_DELTA_DELETE_USER:
1090                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
1091                 break;
1092         case SAM_DELTA_MODIFIED_COUNT:
1093                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
1094                 break;
1095         default:
1096                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
1097                 break;
1098         }
1099 }
1100
1101 static NTSTATUS
1102 fetch_database(struct cli_state *cli, unsigned db_type, DOM_CRED *ret_creds,
1103                DOM_SID dom_sid)
1104 {
1105         unsigned sync_context = 0;
1106         NTSTATUS result;
1107         int i;
1108         TALLOC_CTX *mem_ctx;
1109         SAM_DELTA_HDR *hdr_deltas;
1110         SAM_DELTA_CTR *deltas;
1111         uint32 num_deltas;
1112
1113         if (!(mem_ctx = talloc_init("fetch_database")))
1114                 return NT_STATUS_NO_MEMORY;
1115
1116         switch( db_type ) {
1117         case SAM_DATABASE_DOMAIN:
1118                 d_printf("Fetching DOMAIN database\n");
1119                 break;
1120         case SAM_DATABASE_BUILTIN:
1121                 d_printf("Fetching BUILTIN database\n");
1122                 break;
1123         case SAM_DATABASE_PRIVS:
1124                 d_printf("Fetching PRIVS databases\n");
1125                 break;
1126         default:
1127                 d_printf("Fetching unknown database type %u\n", db_type );
1128                 break;
1129         }
1130
1131         do {
1132                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
1133                                                db_type, sync_context,
1134                                                &num_deltas,
1135                                                &hdr_deltas, &deltas);
1136
1137                 if (NT_STATUS_IS_OK(result) ||
1138                     NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1139
1140                         clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
1141                                              ret_creds);
1142
1143                         for (i = 0; i < num_deltas; i++) {
1144                                 fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
1145                         }
1146                 } else
1147                         return result;
1148
1149                 sync_context += 1;
1150         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1151
1152         talloc_destroy(mem_ctx);
1153
1154         return result;
1155 }
1156
1157 static NTSTATUS
1158 populate_ldap_for_ldif(fstring sid, const char *suffix, const char 
1159                        *builtin_sid, FILE *add_fd)
1160 {
1161         char *user_suffix, *group_suffix, *machine_suffix, *idmap_suffix;
1162         char *user_attr=NULL, *group_attr=NULL;
1163         char *suffix_attr;
1164         int len;
1165
1166         /* Get the suffix attribute */
1167         suffix_attr = sstring_sub(suffix, '=', ',');
1168         if (suffix_attr == NULL) {
1169                 len = strlen(suffix);
1170                 suffix_attr = (char*)SMB_MALLOC(len+1);
1171                 memcpy(suffix_attr, suffix, len);
1172                 suffix_attr[len] = '\0';
1173         }
1174
1175         /* Write the base */
1176         fprintf(add_fd, "# %s\n", suffix);
1177         fprintf(add_fd, "dn: %s\n", suffix);
1178         fprintf(add_fd, "objectClass: dcObject\n");
1179         fprintf(add_fd, "objectClass: organization\n");
1180         fprintf(add_fd, "o: %s\n", suffix_attr);
1181         fprintf(add_fd, "dc: %s\n", suffix_attr);
1182         fprintf(add_fd, "\n");
1183         fflush(add_fd);
1184
1185         user_suffix = lp_ldap_user_suffix();
1186         /* If it exists and is distinct from other containers, 
1187            Write the Users entity */
1188         if (user_suffix && *user_suffix &&
1189             strcmp(user_suffix, suffix)) {
1190                 user_attr = sstring_sub(lp_ldap_user_suffix(), '=', ',');
1191                 fprintf(add_fd, "# %s\n", user_suffix);
1192                 fprintf(add_fd, "dn: %s\n", user_suffix);
1193                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1194                 fprintf(add_fd, "ou: %s\n", user_attr);
1195                 fprintf(add_fd, "\n");
1196                 fflush(add_fd);
1197         }
1198
1199
1200         group_suffix = lp_ldap_group_suffix();
1201         /* If it exists and is distinct from other containers, 
1202            Write the Groups entity */
1203         if (group_suffix && *group_suffix &&
1204             strcmp(group_suffix, suffix)) {
1205                 group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1206                 fprintf(add_fd, "# %s\n", group_suffix);
1207                 fprintf(add_fd, "dn: %s\n", group_suffix);
1208                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1209                 fprintf(add_fd, "ou: %s\n", group_attr);
1210                 fprintf(add_fd, "\n");
1211                 fflush(add_fd);
1212         }
1213
1214         /* If it exists and is distinct from other containers, 
1215            Write the Computers entity */
1216         machine_suffix = lp_ldap_machine_suffix();
1217         if (machine_suffix && *machine_suffix && 
1218             strcmp(machine_suffix, user_suffix) &&
1219             strcmp(machine_suffix, suffix)) {
1220                 fprintf(add_fd, "# %s\n", lp_ldap_machine_suffix());
1221                 fprintf(add_fd, "dn: %s\n", lp_ldap_machine_suffix());
1222                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1223                 fprintf(add_fd, "ou: %s\n", 
1224                         sstring_sub(lp_ldap_machine_suffix(), '=', ','));
1225                 fprintf(add_fd, "\n");
1226                 fflush(add_fd);
1227         }
1228
1229         /* If it exists and is distinct from other containers, 
1230            Write the IdMap entity */
1231         idmap_suffix = lp_ldap_idmap_suffix();
1232         if (idmap_suffix && *idmap_suffix &&
1233             strcmp(idmap_suffix, user_suffix) &&
1234             strcmp(idmap_suffix, suffix)) {
1235                 fprintf(add_fd, "# %s\n", idmap_suffix);
1236                 fprintf(add_fd, "dn: %s\n", idmap_suffix);
1237                 fprintf(add_fd, "ObjectClass: organizationalUnit\n");
1238                 fprintf(add_fd, "ou: %s\n", 
1239                         sstring_sub(lp_ldap_idmap_suffix(), '=', ','));
1240                 fprintf(add_fd, "\n");
1241                 fflush(add_fd);
1242         }
1243
1244         /* Write the root entity */
1245         fprintf(add_fd, "# root, %s, %s\n", user_attr, suffix);
1246         fprintf(add_fd, "dn: uid=root,ou=%s,%s\n", user_attr, suffix);
1247         fprintf(add_fd, "cn: root\n");
1248         fprintf(add_fd, "sn: root\n");
1249         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1250         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1251         fprintf(add_fd, "objectClass: posixAccount\n");
1252         fprintf(add_fd, "objectClass: shadowAccount\n");
1253         fprintf(add_fd, "gidNumber: 0\n");
1254         fprintf(add_fd, "uid: root\n");
1255         fprintf(add_fd, "uidNumber: 0\n");
1256         fprintf(add_fd, "homeDirectory: /home/root\n");
1257         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1258         fprintf(add_fd, "sambaLogonTime: 0\n");
1259         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1260         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1261         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1262         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1263         fprintf(add_fd, "sambaHomePath: \\\\PDC-SRV\root\n");
1264         fprintf(add_fd, "sambaHomeDrive: H:\n");
1265         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SRV\\profiles\\root\n");
1266         fprintf(add_fd, "sambaprimaryGroupSID: %s-512\n", sid);
1267         fprintf(add_fd, "sambaLMPassword: XXX\n");
1268         fprintf(add_fd, "sambaNTPassword: XXX\n");
1269         fprintf(add_fd, "sambaAcctFlags: [U\n");
1270         fprintf(add_fd, "sambaSID: %s-500\n", sid);
1271         fprintf(add_fd, "loginShell: /bin/false\n");
1272         fprintf(add_fd, "\n");
1273         fflush(add_fd);
1274
1275         /* Write the domain entity */
1276         fprintf(add_fd, "# %s, %s\n", lp_workgroup(), suffix);
1277         fprintf(add_fd, "dn: sambaDomainName=%s,%s\n", lp_workgroup(),
1278                 suffix);
1279         fprintf(add_fd, "objectClass: sambaDomain\n");
1280         fprintf(add_fd, "objectClass: sambaUnixIdPool\n");
1281         fprintf(add_fd, "sambaDomainName: %s\n", lp_workgroup());
1282         fprintf(add_fd, "sambaSID: %s\n", sid);
1283         fprintf(add_fd, "uidNumber: %d\n", ++ldif_uid);
1284         fprintf(add_fd, "gidNumber: %d\n", ++ldif_gid);
1285         fprintf(add_fd, "\n");
1286         fflush(add_fd);
1287
1288         /* Write user nobody entity */
1289         fprintf(add_fd, "# nobody, %s, %s\n", user_attr, suffix);
1290         fprintf(add_fd, "dn: uid=nobody,ou=%s,%s\n", user_attr, suffix);
1291         fprintf(add_fd, "cn: nobody\n");
1292         fprintf(add_fd, "sn: nobody\n");
1293         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1294         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1295         fprintf(add_fd, "objectClass: posixAccount\n");
1296         fprintf(add_fd, "objectClass: shadowAccount\n");
1297         fprintf(add_fd, "gidNumber: 514\n");
1298         fprintf(add_fd, "uid: nobody\n");
1299         fprintf(add_fd, "uidNumber: 999\n");
1300         fprintf(add_fd, "homeDirectory: /dev/null\n");
1301         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1302         fprintf(add_fd, "sambaLogonTime: 0\n");
1303         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1304         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1305         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1306         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1307         fprintf(add_fd, "sambaHomePath: \\\\PDC-SMD3\\homes\\nobody\n");
1308         fprintf(add_fd, "sambaHomeDrive: H:\n");
1309         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SMB3\\profiles\\nobody\n");
1310         fprintf(add_fd, "sambaprimaryGroupSID: %s-514\n", sid);
1311         fprintf(add_fd, "sambaLMPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1312         fprintf(add_fd, "sambaNTPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1313         fprintf(add_fd, "sambaAcctFlags: [NU\n");
1314         fprintf(add_fd, "sambaSID: %s-2998\n", sid);
1315         fprintf(add_fd, "loginShell: /bin/false\n");
1316         fprintf(add_fd, "\n");
1317         fflush(add_fd);
1318
1319         /* Write the Domain Admins entity */ 
1320         fprintf(add_fd, "# Domain Admins, %s, %s\n", group_attr,
1321                 suffix);
1322         fprintf(add_fd, "dn: cn=Domain Admins,ou=%s,%s\n", group_attr,
1323                 suffix);
1324         fprintf(add_fd, "objectClass: posixGroup\n");
1325         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1326         fprintf(add_fd, "cn: Domain Admins\n");
1327         fprintf(add_fd, "memberUid: Administrator\n");
1328         fprintf(add_fd, "description: Netbios Domain Administrators\n");
1329         fprintf(add_fd, "gidNumber: 512\n");
1330         fprintf(add_fd, "sambaSID: %s-512\n", sid);
1331         fprintf(add_fd, "sambaGroupType: 2\n");
1332         fprintf(add_fd, "displayName: Domain Admins\n");
1333         fprintf(add_fd, "\n");
1334         fflush(add_fd);
1335
1336         /* Write the Domain Users entity */ 
1337         fprintf(add_fd, "# Domain Users, %s, %s\n", group_attr,
1338                 suffix);
1339         fprintf(add_fd, "dn: cn=Domain Users,ou=%s,%s\n", group_attr,
1340                 suffix);
1341         fprintf(add_fd, "objectClass: posixGroup\n");
1342         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1343         fprintf(add_fd, "cn: Domain Users\n");
1344         fprintf(add_fd, "description: Netbios Domain Users\n");
1345         fprintf(add_fd, "gidNumber: 513\n");
1346         fprintf(add_fd, "sambaSID: %s-513\n", sid);
1347         fprintf(add_fd, "sambaGroupType: 2\n");
1348         fprintf(add_fd, "displayName: Domain Users\n");
1349         fprintf(add_fd, "\n");
1350         fflush(add_fd);
1351
1352         /* Write the Domain Guests entity */ 
1353         fprintf(add_fd, "# Domain Guests, %s, %s\n", group_attr,
1354                 suffix);
1355         fprintf(add_fd, "dn: cn=Domain Guests,ou=%s,%s\n", group_attr,
1356                 suffix);
1357         fprintf(add_fd, "objectClass: posixGroup\n");
1358         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1359         fprintf(add_fd, "cn: Domain Guests\n");
1360         fprintf(add_fd, "description: Netbios Domain Guests\n");
1361         fprintf(add_fd, "gidNumber: 514\n");
1362         fprintf(add_fd, "sambaSID: %s-514\n", sid);
1363         fprintf(add_fd, "sambaGroupType: 2\n");
1364         fprintf(add_fd, "displayName: Domain Guests\n");
1365         fprintf(add_fd, "\n");
1366         fflush(add_fd);
1367
1368         /* Write the Domain Computers entity */
1369         fprintf(add_fd, "# Domain Computers, %s, %s\n", group_attr,
1370                 suffix);
1371         fprintf(add_fd, "dn: cn=Domain Computers,ou=%s,%s\n",
1372                 group_attr, suffix);
1373         fprintf(add_fd, "objectClass: posixGroup\n");
1374         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1375         fprintf(add_fd, "gidNumber: 515\n");
1376         fprintf(add_fd, "cn: Domain Computers\n");
1377         fprintf(add_fd, "description: Netbios Domain Computers accounts\n");
1378         fprintf(add_fd, "sambaSID: %s-515\n", sid);
1379         fprintf(add_fd, "sambaGroupType: 2\n");
1380         fprintf(add_fd, "displayName: Domain Computers\n");
1381         fprintf(add_fd, "\n");
1382         fflush(add_fd);
1383
1384         /* Write the Admininistrators Groups entity */
1385         fprintf(add_fd, "# Administrators, %s, %s\n", group_attr,
1386                 suffix);
1387         fprintf(add_fd, "dn: cn=Administrators,ou=%s,%s\n", group_attr,
1388                 suffix);
1389         fprintf(add_fd, "objectClass: posixGroup\n");
1390         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1391         fprintf(add_fd, "gidNumber: 544\n");
1392         fprintf(add_fd, "cn: Administrators\n");
1393         fprintf(add_fd, "description: Netbios Domain Members can fully administer the computer/sambaDomainName\n");
1394         fprintf(add_fd, "sambaSID: %s-544\n", builtin_sid);
1395         fprintf(add_fd, "sambaGroupType: 5\n");
1396         fprintf(add_fd, "displayName: Administrators\n");
1397         fprintf(add_fd, "\n");
1398
1399         /* Write the Print Operator entity */
1400         fprintf(add_fd, "# Print Operators, %s, %s\n", group_attr,
1401                 suffix);
1402         fprintf(add_fd, "dn: cn=Print Operators,ou=%s,%s\n",
1403                 group_attr, suffix);
1404         fprintf(add_fd, "objectClass: posixGroup\n");
1405         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1406         fprintf(add_fd, "gidNumber: 550\n");
1407         fprintf(add_fd, "cn: Print Operators\n");
1408         fprintf(add_fd, "description: Netbios Domain Print Operators\n");
1409         fprintf(add_fd, "sambaSID: %s-550\n", builtin_sid);
1410         fprintf(add_fd, "sambaGroupType: 5\n");
1411         fprintf(add_fd, "displayName: Print Operators\n");
1412         fprintf(add_fd, "\n");
1413         fflush(add_fd);
1414
1415         /* Write the Backup Operators entity */
1416         fprintf(add_fd, "# Backup Operators, %s, %s\n", group_attr,
1417                 suffix);
1418         fprintf(add_fd, "dn: cn=Backup Operators,ou=%s,%s\n",
1419                 group_attr, suffix);
1420         fprintf(add_fd, "objectClass: posixGroup\n");
1421         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1422         fprintf(add_fd, "gidNumber: 551\n");
1423         fprintf(add_fd, "cn: Backup Operators\n");
1424         fprintf(add_fd, "description: Netbios Domain Members can bypass file security to back up files\n");
1425         fprintf(add_fd, "sambaSID: %s-551\n", builtin_sid);
1426         fprintf(add_fd, "sambaGroupType: 5\n");
1427         fprintf(add_fd, "displayName: Backup Operators\n");
1428         fprintf(add_fd, "\n");
1429         fflush(add_fd);
1430
1431         /* Write the Replicators entity */
1432         fprintf(add_fd, "# Replicators, %s, %s\n", group_attr, suffix);
1433         fprintf(add_fd, "dn: cn=Replicators,ou=%s,%s\n", group_attr,
1434                 suffix);
1435         fprintf(add_fd, "objectClass: posixGroup\n");
1436         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1437         fprintf(add_fd, "gidNumber: 552\n");
1438         fprintf(add_fd, "cn: Replicators\n");
1439         fprintf(add_fd, "description: Netbios Domain Supports file replication in a sambaDomainName\n");
1440         fprintf(add_fd, "sambaSID: %s-552\n", builtin_sid);
1441         fprintf(add_fd, "sambaGroupType: 5\n");
1442         fprintf(add_fd, "displayName: Replicators\n");
1443         fprintf(add_fd, "\n");
1444         fflush(add_fd);
1445
1446         /* Deallocate memory, and return */
1447         if (suffix_attr != NULL) SAFE_FREE(suffix_attr);
1448         return NT_STATUS_OK;
1449 }
1450
1451 static NTSTATUS
1452 map_populate_groups(GROUPMAP *groupmap, ACCOUNTMAP *accountmap, fstring sid, 
1453                     const char *suffix, const char *builtin_sid)
1454 {
1455         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1456
1457         /* Map the groups created by populate_ldap_for_ldif */
1458         groupmap[0].rid = 512;
1459         groupmap[0].gidNumber = 512;
1460         pstr_sprintf(groupmap[0].sambaSID, "%s-512", sid);
1461         pstr_sprintf(groupmap[0].group_dn, "cn=Domain Admins,ou=%s,%s", 
1462                      group_attr, suffix);
1463         accountmap[0].rid = 512;
1464         pstr_sprintf(accountmap[0].cn, "%s", "Domain Admins");
1465
1466         groupmap[1].rid = 513;
1467         groupmap[1].gidNumber = 513;
1468         pstr_sprintf(groupmap[1].sambaSID, "%s-513", sid);
1469         pstr_sprintf(groupmap[1].group_dn, "cn=Domain Users,ou=%s,%s", 
1470                      group_attr, suffix);
1471         accountmap[1].rid = 513;
1472         pstr_sprintf(accountmap[1].cn, "%s", "Domain Users");
1473
1474         groupmap[2].rid = 514;
1475         groupmap[2].gidNumber = 514;
1476         pstr_sprintf(groupmap[2].sambaSID, "%s-514", sid);
1477         pstr_sprintf(groupmap[2].group_dn, "cn=Domain Guests,ou=%s,%s", 
1478                      group_attr, suffix);
1479         accountmap[2].rid = 514;
1480         pstr_sprintf(accountmap[2].cn, "%s", "Domain Guests");
1481
1482         groupmap[3].rid = 515;
1483         groupmap[3].gidNumber = 515;
1484         pstr_sprintf(groupmap[3].sambaSID, "%s-515", sid);
1485         pstr_sprintf(groupmap[3].group_dn, "cn=Domain Computers,ou=%s,%s",
1486                      group_attr, suffix);
1487         accountmap[3].rid = 515;
1488         pstr_sprintf(accountmap[3].cn, "%s", "Domain Computers");
1489
1490         groupmap[4].rid = 544;
1491         groupmap[4].gidNumber = 544;
1492         pstr_sprintf(groupmap[4].sambaSID, "%s-544", builtin_sid);
1493         pstr_sprintf(groupmap[4].group_dn, "cn=Administrators,ou=%s,%s",
1494                      group_attr, suffix);
1495         accountmap[4].rid = 515;
1496         pstr_sprintf(accountmap[4].cn, "%s", "Administrators");
1497
1498         groupmap[5].rid = 550;
1499         groupmap[5].gidNumber = 550;
1500         pstr_sprintf(groupmap[5].sambaSID, "%s-550", builtin_sid);
1501         pstr_sprintf(groupmap[5].group_dn, "cn=Print Operators,ou=%s,%s",
1502                      group_attr, suffix);
1503         accountmap[5].rid = 550;
1504         pstr_sprintf(accountmap[5].cn, "%s", "Print Operators");
1505
1506         groupmap[6].rid = 551;
1507         groupmap[6].gidNumber = 551;
1508         pstr_sprintf(groupmap[6].sambaSID, "%s-551", builtin_sid);
1509         pstr_sprintf(groupmap[6].group_dn, "cn=Backup Operators,ou=%s,%s",
1510                      group_attr, suffix);
1511         accountmap[6].rid = 551;
1512         pstr_sprintf(accountmap[6].cn, "%s", "Backup Operators");
1513
1514         groupmap[7].rid = 552;
1515         groupmap[7].gidNumber = 552;
1516         pstr_sprintf(groupmap[7].sambaSID, "%s-552", builtin_sid);
1517         pstr_sprintf(groupmap[7].group_dn, "cn=Replicators,ou=%s,%s",
1518                      group_attr, suffix);
1519         accountmap[7].rid = 551;
1520         pstr_sprintf(accountmap[7].cn, "%s", "Replicators");
1521         return NT_STATUS_OK;
1522 }
1523
1524 static NTSTATUS
1525 fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1526                          FILE *add_fd, fstring sid, char *suffix)
1527 {
1528         fstring groupname;
1529         uint32 grouptype = 0, g_rid = 0;
1530         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1531
1532         /* Get the group name */
1533         unistr2_to_ascii(groupname, 
1534                          &(delta->group_info.uni_grp_name),
1535                          sizeof(groupname)-1);
1536
1537         /* Set up the group type (always 2 for group info) */
1538         grouptype = 2;
1539
1540         /* These groups are entered by populate_ldap_for_ldif */
1541         if (strcmp(groupname, "Domain Admins") == 0 ||
1542             strcmp(groupname, "Domain Users") == 0 ||
1543             strcmp(groupname, "Domain Guests") == 0 ||
1544             strcmp(groupname, "Domain Computers") == 0 ||
1545             strcmp(groupname, "Administrators") == 0 ||
1546             strcmp(groupname, "Print Operators") == 0 ||
1547             strcmp(groupname, "Backup Operators") == 0 ||
1548             strcmp(groupname, "Replicators") == 0) {
1549                 return NT_STATUS_OK;
1550         } else {
1551                 /* Increment the gid for the new group */
1552                 ldif_gid++;
1553         }
1554
1555         /* Map the group rid, gid, and dn */
1556         g_rid = delta->group_info.gid.g_rid;
1557         groupmap->rid = g_rid;
1558         groupmap->gidNumber = ldif_gid;
1559         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1560         pstr_sprintf(groupmap->group_dn, 
1561                      "cn=%s,ou=%s,%s", groupname, group_attr, suffix);
1562
1563         /* Write the data to the temporary add ldif file */
1564         fprintf(add_fd, "# %s, %s, %s\n", groupname, group_attr,
1565                 suffix);
1566         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", groupname, group_attr,
1567                 suffix);
1568         fprintf(add_fd, "objectClass: posixGroup\n");
1569         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1570         fprintf(add_fd, "cn: %s\n", groupname);
1571         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1572         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1573         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1574         fprintf(add_fd, "displayName: %s\n", groupname);
1575         fprintf(add_fd, "\n");
1576         fflush(add_fd);
1577
1578         /* Return */
1579         return NT_STATUS_OK;
1580 }
1581
1582 static NTSTATUS
1583 fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1584                            ACCOUNTMAP *accountmap, FILE *add_fd,
1585                            fstring sid, char *suffix, int alloced)
1586 {
1587         fstring username, homedir, logonscript, homedrive, homepath;
1588         fstring hex_nt_passwd, hex_lm_passwd;
1589         fstring description, fullname, sambaSID;
1590         uchar lm_passwd[16], nt_passwd[16];
1591         char *flags;
1592         const char *blank = "", *shell = "/bin/bash";
1593         const char* nopasswd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1594         static uchar zero_buf[16];
1595         uint32 rid = 0, group_rid = 0, gidNumber = 0;
1596         time_t unix_time;
1597         int i;
1598
1599         /* Get the username */
1600         unistr2_to_ascii(username, 
1601                          &(delta->account_info.uni_acct_name),
1602                          sizeof(username)-1);
1603
1604         /* Get the rid */
1605         rid = delta->account_info.user_rid;
1606
1607         /* Map the rid and username for group member info later */
1608         accountmap->rid = rid;
1609         pstr_sprintf(accountmap->cn, "%s", username);
1610
1611         /* Get the home directory */
1612         unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
1613                          sizeof(homedir)-1);
1614         if (strcmp(homedir, blank) == 0) {
1615                 pstr_sprintf(homedir, "/home/%s", username);
1616         } else {
1617                 strncpy(homepath, homedir, sizeof(homepath));
1618         }       
1619
1620         /* Get the logon script */
1621         unistr2_to_ascii(logonscript, &(delta->account_info.uni_logon_script),
1622                         sizeof(logonscript)-1);
1623
1624         /* Get the home drive */
1625         unistr2_to_ascii(homedrive, &(delta->account_info.uni_dir_drive),
1626                         sizeof(homedrive)-1);
1627
1628         /* Get the description */
1629         unistr2_to_ascii(description, &(delta->account_info.uni_acct_desc),
1630                          sizeof(description)-1);
1631         if (strcmp(description, blank) == 0) {
1632                 pstr_sprintf(description, "System User");
1633         }
1634
1635         /* Get the display name */
1636         unistr2_to_ascii(fullname, &(delta->account_info.uni_full_name),
1637                          sizeof(fullname)-1);
1638
1639         /* Get lm and nt password data */
1640         if (memcmp(delta->account_info.pass.buf_lm_pwd, zero_buf, 16) != 0) {
1641                 sam_pwd_hash(delta->account_info.user_rid, 
1642                              delta->account_info.pass.buf_lm_pwd, 
1643                              lm_passwd, 0);
1644                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, 
1645                               delta->account_info.acb_info);
1646         } else {
1647                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
1648         }
1649         if (memcmp(delta->account_info.pass.buf_nt_pwd, zero_buf, 16) != 0) {
1650                 sam_pwd_hash(delta->account_info.user_rid, 
1651                              delta->account_info.pass.buf_nt_pwd, 
1652                                      nt_passwd, 0);
1653                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, 
1654                               delta->account_info.acb_info);
1655         } else {
1656                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
1657         }
1658         unix_time = nt_time_to_unix(&(delta->account_info.pwd_last_set_time));
1659
1660         /* The nobody user is entered by populate_ldap_for_ldif */
1661         if (strcmp(username, "nobody") == 0) {
1662                 return NT_STATUS_OK;
1663         } else {
1664                 /* Increment the uid for the new user */
1665                 ldif_uid++;
1666         }
1667
1668         /* Set up group id and sambaSID for the user */
1669         group_rid = delta->account_info.group_rid;
1670         for (i=0; i<alloced; i++) {
1671                 if (groupmap[i].rid == group_rid) break;
1672         }
1673         if (i == alloced){
1674                 DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1675                           group_rid));
1676                 return NT_STATUS_UNSUCCESSFUL;
1677         }
1678         gidNumber = groupmap[i].gidNumber;
1679         pstr_sprintf(sambaSID, groupmap[i].sambaSID);
1680
1681         /* Set up sambaAcctFlags */
1682         flags = pdb_encode_acct_ctrl(delta->account_info.acb_info,
1683                                      NEW_PW_FORMAT_SPACE_PADDED_LEN);
1684
1685         /* Add the user to the temporary add ldif file */
1686         fprintf(add_fd, "# %s, %s, %s\n", username, 
1687                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1688         fprintf(add_fd, "dn: uid=%s,ou=%s,%s\n", username, 
1689                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1690         fprintf(add_fd, "ObjectClass: top\n");
1691         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1692         fprintf(add_fd, "objectClass: posixAccount\n");
1693         fprintf(add_fd, "objectClass: shadowAccount\n");
1694         fprintf(add_fd, "objectClass: sambaSamAccount\n");
1695         fprintf(add_fd, "cn: %s\n", username);
1696         fprintf(add_fd, "sn: %s\n", username);
1697         fprintf(add_fd, "uid: %s\n", username);
1698         fprintf(add_fd, "uidNumber: %d\n", ldif_uid);
1699         fprintf(add_fd, "gidNumber: %d\n", gidNumber);
1700         fprintf(add_fd, "homeDirectory: %s\n", homedir);
1701         if (strcmp(homepath, blank) != 0)
1702                 fprintf(add_fd, "SambaHomePath: %s\n", homepath);
1703         if (strcmp(homedrive, blank) != 0)
1704                 fprintf(add_fd, "SambaHomeDrive: %s\n", homedrive);
1705         if (strcmp(logonscript, blank) != 0)
1706                 fprintf(add_fd, "SambaLogonScript: %s\n", logonscript);
1707         fprintf(add_fd, "loginShell: %s\n", shell);
1708         fprintf(add_fd, "gecos: System User\n");
1709         fprintf(add_fd, "description: %s\n", description);
1710         fprintf(add_fd, "sambaSID: %s-%d\n", sid, rid);
1711         fprintf(add_fd, "sambaPrimaryGroupSID: %s\n", sambaSID);
1712         if(strcmp(fullname, blank) != 0)
1713                 fprintf(add_fd, "displayName: %s\n", fullname);
1714         if (strcmp(nopasswd, hex_lm_passwd) != 0)
1715                 fprintf(add_fd, "sambaLMPassword: %s\n", hex_lm_passwd);
1716         if (strcmp(nopasswd, hex_nt_passwd) != 0)
1717                 fprintf(add_fd, "sambaNTPassword: %s\n", hex_nt_passwd);
1718         fprintf(add_fd, "sambaPwdLastSet: %d\n", (int)unix_time);
1719         fprintf(add_fd, "sambaAcctFlags: %s\n", flags);
1720         fprintf(add_fd, "\n");
1721         fflush(add_fd);
1722
1723         /* Return */
1724         return NT_STATUS_OK;
1725 }
1726
1727 static NTSTATUS
1728 fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1729                          FILE *add_fd, fstring sid, char *suffix, 
1730                          unsigned db_type)
1731 {
1732         fstring aliasname, description;
1733         uint32 grouptype = 0, g_rid = 0;
1734         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1735
1736         /* Get the alias name */
1737         unistr2_to_ascii(aliasname, &(delta->alias_info.uni_als_name),
1738                          sizeof(aliasname)-1);
1739
1740         /* Get the alias description */
1741         unistr2_to_ascii(description, &(delta->alias_info.uni_als_desc),
1742                          sizeof(description)-1);
1743
1744         /* Set up the group type */
1745         switch (db_type) {
1746                 case SAM_DATABASE_DOMAIN:
1747                         grouptype = 4;
1748                         break;
1749                 case SAM_DATABASE_BUILTIN:
1750                         grouptype = 5;
1751                         break;
1752                 default:
1753                         grouptype = 4;
1754                         break;
1755         }
1756
1757         /*
1758         These groups are entered by populate_ldap_for_ldif
1759         Note that populate creates a group called Relicators, 
1760         but NT returns a group called Replicator
1761         */
1762         if (strcmp(aliasname, "Domain Admins") == 0 ||
1763             strcmp(aliasname, "Domain Users") == 0 ||
1764             strcmp(aliasname, "Domain Guests") == 0 ||
1765             strcmp(aliasname, "Domain Computers") == 0 ||
1766             strcmp(aliasname, "Administrators") == 0 ||
1767             strcmp(aliasname, "Print Operators") == 0 ||
1768             strcmp(aliasname, "Backup Operators") == 0 ||
1769             strcmp(aliasname, "Replicator") == 0) {
1770                 return NT_STATUS_OK;
1771         } else {
1772                 /* Increment the gid for the new group */
1773                 ldif_gid++;
1774         }
1775
1776         /* Map the group rid and gid */
1777         g_rid = delta->group_info.gid.g_rid;
1778         groupmap->gidNumber = ldif_gid;
1779         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1780
1781         /* Write the data to the temporary add ldif file */
1782         fprintf(add_fd, "# %s, %s, %s\n", aliasname, group_attr,
1783                 suffix);
1784         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", aliasname, group_attr,
1785                 suffix);
1786         fprintf(add_fd, "objectClass: posixGroup\n");
1787         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1788         fprintf(add_fd, "cn: %s\n", aliasname);
1789         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1790         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1791         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1792         fprintf(add_fd, "displayName: %s\n", aliasname);
1793         fprintf(add_fd, "description: %s\n", description);
1794         fprintf(add_fd, "\n");
1795         fflush(add_fd);
1796
1797         /* Return */
1798         return NT_STATUS_OK;
1799 }
1800
1801 static NTSTATUS
1802 fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR *hdr_delta,
1803                             GROUPMAP *groupmap, ACCOUNTMAP *accountmap, 
1804                             FILE *mod_fd, int alloced)
1805 {
1806         fstring group_dn;
1807         uint32 group_rid = 0, rid = 0;
1808         int i, j, k;
1809
1810         /* Get the dn for the group */
1811         if (delta->grp_mem_info.num_members > 0) {
1812                 group_rid = hdr_delta->target_rid;
1813                 for (j=0; j<alloced; j++) {
1814                         if (groupmap[j].rid == group_rid) break;
1815                 }
1816                 if (j == alloced){
1817                         DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1818                                   group_rid));
1819                         return NT_STATUS_UNSUCCESSFUL;
1820                 }
1821                 pstr_sprintf(group_dn, "%s", groupmap[j].group_dn);
1822                 fprintf(mod_fd, "dn: %s\n", group_dn);
1823
1824                 /* Get the cn for each member */
1825                 for (i=0; i<delta->grp_mem_info.num_members; i++) {
1826                         rid = delta->grp_mem_info.rids[i];
1827                         for (k=0; k<alloced; k++) {
1828                                 if (accountmap[k].rid == rid) break;
1829                         }
1830                         if (k == alloced){
1831                                 DEBUG(1, ("Could not find rid %d in accountmap array\n", rid));
1832                                 return NT_STATUS_UNSUCCESSFUL;
1833                         }
1834                         fprintf(mod_fd, "memberUid: %s\n", accountmap[k].cn);
1835                 }
1836                 fprintf(mod_fd, "\n");
1837         }
1838         fflush(mod_fd);
1839
1840         /* Return */
1841         return NT_STATUS_OK;
1842 }
1843
1844 static NTSTATUS
1845 fetch_database_to_ldif(struct cli_state *cli, unsigned db_type, 
1846                        DOM_CRED *ret_creds, DOM_SID dom_sid,
1847                        const char *user_file)
1848 {
1849         char *suffix;
1850         const char *builtin_sid = "S-1-5-32";
1851         char *ldif_file;
1852         fstring sid, domainname;
1853         unsigned sync_context = 0;
1854         NTSTATUS result;
1855         int k;
1856         TALLOC_CTX *mem_ctx;
1857         SAM_DELTA_HDR *hdr_deltas;
1858         SAM_DELTA_CTR *deltas;
1859         uint32 num_deltas;
1860         const char *add_ldif = "/tmp/add.ldif", *mod_ldif = "/tmp/mod.ldif";
1861         FILE *add_fd, *mod_fd, *ldif_fd;
1862         char sys_cmd[1024];
1863         int num_alloced = 0, g_index = 0, a_index = 0;
1864
1865         /* Set up array for mapping accounts to groups */
1866         /* Array element is the group rid */
1867         GROUPMAP *groupmap = NULL;
1868
1869         /* Set up array for mapping account rid's to cn's */
1870         /* Array element is the account rid */
1871         ACCOUNTMAP *accountmap = NULL; 
1872
1873         if (!(mem_ctx = talloc_init("fetch_database"))) {
1874                 return NT_STATUS_NO_MEMORY;
1875         }
1876
1877         /* Ensure we have an output file */
1878         if (user_file)
1879                 ldif_file = talloc_strdup(mem_ctx, user_file);
1880         else
1881                 ldif_file = talloc_strdup(mem_ctx, "/tmp/tmp.ldif");
1882         
1883         if (ldif_file == NULL)
1884                 return NT_STATUS_NO_MEMORY;
1885
1886         /* Open the add and mod ldif files */
1887         add_fd = fopen(add_ldif, "a");
1888         mod_fd = fopen(mod_ldif, "a");
1889         if (add_fd == NULL || mod_fd == NULL) {
1890                 DEBUG(1, ("Could not open %s\n", add_ldif));
1891                 return NT_STATUS_UNSUCCESSFUL;
1892         } 
1893
1894         /* Open the user's ldif file */
1895         ldif_fd = fopen(ldif_file, "a");
1896         if (ldif_fd == NULL) {
1897                 DEBUG(1, ("Could not open %s\n", ldif_file));
1898                 return NT_STATUS_UNSUCCESSFUL;
1899         }
1900
1901         /* Get the sid */
1902         sid_to_string(sid, &dom_sid);
1903
1904         /* Get the ldap suffix */
1905         suffix = lp_ldap_suffix();
1906         if (suffix == NULL || strcmp(suffix, "") == 0) {
1907                 DEBUG(0,("ldap suffix missing from smb.conf--exiting\n"));
1908                 exit(1);
1909         }
1910
1911         /* Get other smb.conf data */
1912         if (!(lp_workgroup()) || !*(lp_workgroup())) {
1913                 DEBUG(0,("workgroup missing from smb.conf--exiting\n"));
1914                 exit(1);
1915         }
1916
1917         /* Allocate initial memory for groupmap and accountmap arrays */
1918         if (init_ldap == 1) {
1919                 groupmap = SMB_MALLOC_ARRAY(GROUPMAP, 8);
1920                 accountmap = SMB_MALLOC_ARRAY(ACCOUNTMAP, 8);
1921                 if (groupmap == NULL || accountmap == NULL) {
1922                         DEBUG(1,("GROUPMAP malloc failed\n"));
1923                         return NT_STATUS_NO_MEMORY;
1924                 }
1925
1926                 /* Initialize the arrays */
1927                 memset(groupmap, 0, sizeof(GROUPMAP)*8);
1928                 memset(accountmap, 0, sizeof(ACCOUNTMAP)*8);
1929
1930                 /* Remember how many we malloced */
1931                 num_alloced = 8;
1932
1933                 /* Initial database population */
1934                 populate_ldap_for_ldif(sid, suffix, builtin_sid, add_fd);
1935                 map_populate_groups(groupmap, accountmap, sid, suffix,
1936                             builtin_sid);
1937
1938                 /* Don't do this again */
1939                 init_ldap = 0;
1940         }
1941
1942         /* Announce what we are doing */
1943         switch( db_type ) {
1944                 case SAM_DATABASE_DOMAIN:
1945                         d_printf("Fetching DOMAIN database\n");
1946                         break;
1947                 case SAM_DATABASE_BUILTIN:
1948                         d_printf("Fetching BUILTIN database\n");
1949                         break;
1950                 case SAM_DATABASE_PRIVS:
1951                         d_printf("Fetching PRIVS databases\n");
1952                         break;
1953                 default:
1954                         d_printf("Fetching unknown database type %u\n", db_type );
1955                         break;
1956         }
1957
1958         do {
1959                 result = cli_netlogon_sam_sync(cli, mem_ctx, ret_creds,
1960                                                db_type, sync_context,
1961                                                &num_deltas, &hdr_deltas, 
1962                                                &deltas);
1963                 if (!NT_STATUS_IS_OK(result) &&
1964                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1965                         return NT_STATUS_OK;
1966                 }
1967
1968                 clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred),
1969                                      ret_creds);
1970
1971                 /* Re-allocate memory for groupmap and accountmap arrays */
1972                 groupmap = SMB_REALLOC_ARRAY(groupmap, GROUPMAP,
1973                                         num_deltas+num_alloced);
1974                 accountmap = SMB_REALLOC_ARRAY(accountmap, ACCOUNTMAP,
1975                                         num_deltas+num_alloced);
1976                 if (groupmap == NULL || accountmap == NULL) {
1977                         DEBUG(1,("GROUPMAP malloc failed\n"));
1978                         return NT_STATUS_NO_MEMORY;
1979                 }
1980
1981                 /* Initialize the new records */
1982                 memset(&groupmap[num_alloced], 0, 
1983                        sizeof(GROUPMAP)*num_deltas);
1984                 memset(&accountmap[num_alloced], 0,
1985                        sizeof(ACCOUNTMAP)*num_deltas);
1986
1987                 /* Remember how many we alloced this time */
1988                 num_alloced += num_deltas;
1989
1990                 /* Loop through the deltas */
1991                 for (k=0; k<num_deltas; k++) {
1992                         switch(hdr_deltas[k].type) {
1993                                 case SAM_DELTA_DOMAIN_INFO:
1994                                         /* Is this case needed? */
1995                                         unistr2_to_ascii(domainname, 
1996                                         &deltas[k].domain_info.uni_dom_name,
1997                                                 sizeof(domainname)-1);
1998                                         break;
1999
2000                                 case SAM_DELTA_GROUP_INFO:
2001                                         fetch_group_info_to_ldif(
2002                                                 &deltas[k], &groupmap[g_index],
2003                                                 add_fd, sid, suffix);
2004                                         g_index++;
2005                                         break;
2006
2007                                 case SAM_DELTA_ACCOUNT_INFO:
2008                                         fetch_account_info_to_ldif(
2009                                                 &deltas[k], groupmap, 
2010                                                 &accountmap[a_index], add_fd,
2011                                                 sid, suffix, num_alloced);
2012                                         a_index++;
2013                                         break;
2014
2015                                 case SAM_DELTA_ALIAS_INFO:
2016                                         fetch_alias_info_to_ldif(
2017                                                 &deltas[k], &groupmap[g_index],
2018                                                 add_fd, sid, suffix, db_type);
2019                                         g_index++;
2020                                         break;
2021
2022                                 case SAM_DELTA_GROUP_MEM:
2023                                         fetch_groupmem_info_to_ldif(
2024                                                 &deltas[k], &hdr_deltas[k], 
2025                                                 groupmap, accountmap, 
2026                                                 mod_fd, num_alloced);
2027                                         break;
2028
2029                                 case SAM_DELTA_ALIAS_MEM:
2030                                         break;
2031                                 case SAM_DELTA_POLICY_INFO:
2032                                         break;
2033                                 case SAM_DELTA_PRIVS_INFO:
2034                                         break;
2035                                 case SAM_DELTA_TRUST_DOMS:
2036                                         /* Implemented but broken */
2037                                         break;
2038                                 case SAM_DELTA_SECRET_INFO:
2039                                         /* Implemented but broken */
2040                                         break;
2041                                 case SAM_DELTA_RENAME_GROUP:
2042                                         /* Not yet implemented */
2043                                         break;
2044                                 case SAM_DELTA_RENAME_USER:
2045                                         /* Not yet implemented */
2046                                         break;
2047                                 case SAM_DELTA_RENAME_ALIAS:
2048                                         /* Not yet implemented */
2049                                         break;
2050                                 case SAM_DELTA_DELETE_GROUP:
2051                                         /* Not yet implemented */
2052                                         break;
2053                                 case SAM_DELTA_DELETE_USER:
2054                                         /* Not yet implemented */
2055                                         break;
2056                                 case SAM_DELTA_MODIFIED_COUNT:
2057                                         break;
2058                                 default:
2059                                 break;
2060                         } /* end of switch */
2061                 } /* end of for loop */
2062
2063                 /* Increment sync_context */
2064                 sync_context += 1;
2065
2066         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2067
2068         /* Close the ldif files */
2069         fclose(add_fd);
2070         fclose(mod_fd);
2071
2072         /* Write ldif data to the user's file */
2073         if (db_type == SAM_DATABASE_DOMAIN) {
2074                 fprintf(ldif_fd,
2075                         "# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
2076                 fprintf(ldif_fd,
2077                         "# =================================\n\n");
2078                 fflush(ldif_fd);
2079         } else if (db_type == SAM_DATABASE_BUILTIN) {
2080                 fprintf(ldif_fd,
2081                         "# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
2082                 fprintf(ldif_fd,
2083                         "# ==================================\n\n");
2084                 fflush(ldif_fd);
2085         }
2086         pstr_sprintf(sys_cmd, "cat %s >> %s", add_ldif, ldif_file);
2087         system(sys_cmd);
2088         if (db_type == SAM_DATABASE_DOMAIN) {
2089                 fprintf(ldif_fd,
2090                         "# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
2091                 fprintf(ldif_fd,
2092                         "# ====================================\n\n");
2093                 fflush(ldif_fd);
2094         } else if (db_type == SAM_DATABASE_BUILTIN) {
2095                 fprintf(ldif_fd,
2096                         "# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
2097                 fprintf(ldif_fd,
2098                         "# =====================================\n\n");
2099                 fflush(ldif_fd);
2100         }
2101         pstr_sprintf(sys_cmd, "cat %s >> %s", mod_ldif, ldif_file);
2102         system(sys_cmd);
2103
2104         /* Delete the temporary ldif files */
2105         pstr_sprintf(sys_cmd, "rm -f %s %s", add_ldif, mod_ldif);
2106         system(sys_cmd);
2107
2108         /* Close the ldif file */
2109         fclose(ldif_fd);
2110
2111         /* Deallocate memory for the mapping arrays */
2112         SAFE_FREE(groupmap);
2113         SAFE_FREE(accountmap);
2114
2115         /* Return */
2116         talloc_destroy(mem_ctx);
2117         return NT_STATUS_OK;
2118 }
2119
2120 /** 
2121  * Basic usage function for 'net rpc vampire'
2122  * @param argc  Standard main() style argc
2123  * @param argc  Standard main() style argv.  Initial components are already
2124  *              stripped
2125  **/
2126
2127 int rpc_vampire_usage(int argc, const char **argv) 
2128 {       
2129         d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"\
2130                  "\t to pull accounts from a remote PDC where we are a BDC\n"\
2131                  "\t\t no args puts accounts in local passdb from smb.conf\n"\
2132                  "\t\t ldif - put accounts in ldif format (file defaults to /tmp/tmp.ldif\n");
2133
2134         net_common_flags_usage(argc, argv);
2135         return -1;
2136 }
2137
2138
2139 /* dump sam database via samsync rpc calls */
2140 NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
2141                                const char *domain_name, 
2142                                struct cli_state *cli, TALLOC_CTX *mem_ctx, 
2143                                int argc, const char **argv) 
2144 {
2145         NTSTATUS result;
2146         uchar trust_password[16];
2147         DOM_CRED ret_creds;
2148         fstring my_dom_sid_str;
2149         fstring rem_dom_sid_str;
2150         uint32 sec_channel;
2151
2152         ZERO_STRUCT(ret_creds);
2153
2154         if (!sid_equal(domain_sid, get_global_sam_sid())) {
2155                 d_printf("Cannot import users from %s at this time, "
2156                          "as the current domain:\n\t%s: %s\nconflicts "
2157                          "with the remote domain\n\t%s: %s\n"
2158                          "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
2159                          domain_name,
2160                          get_global_sam_name(), sid_to_string(my_dom_sid_str, 
2161                                                               get_global_sam_sid()),
2162                          domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
2163                          domain_name);
2164                 return NT_STATUS_UNSUCCESSFUL;
2165         }
2166
2167         fstrcpy(cli->domain, domain_name);
2168
2169         if (!secrets_fetch_trust_account_password(domain_name,
2170                                                   trust_password, NULL,
2171                                                   &sec_channel)) {
2172                 result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2173                 d_printf("Could not retrieve domain trust secret\n");
2174                 goto fail;
2175         }
2176         
2177         result = cli_nt_establish_netlogon(cli, sec_channel, trust_password);
2178
2179         if (!NT_STATUS_IS_OK(result)) {
2180                 d_printf("Failed to setup BDC creds\n");
2181                 goto fail;
2182         }
2183
2184         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2185                 result = fetch_database_to_ldif(cli, SAM_DATABASE_DOMAIN,
2186                                         &ret_creds, *domain_sid, argv[1]);
2187         } else {
2188                 result = fetch_database(cli, SAM_DATABASE_DOMAIN, &ret_creds,
2189                                         *domain_sid);
2190         }
2191
2192         if (!NT_STATUS_IS_OK(result)) {
2193                 d_printf("Failed to fetch domain database: %s\n",
2194                          nt_errstr(result));
2195                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
2196                         d_printf("Perhaps %s is a Windows 2000 native mode "
2197                                  "domain?\n", domain_name);
2198                 goto fail;
2199         }
2200
2201         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2202                 result = fetch_database_to_ldif(cli, SAM_DATABASE_BUILTIN, 
2203                                             &ret_creds, global_sid_Builtin,
2204                                             argv[1]);
2205         } else {
2206                 result = fetch_database(cli, SAM_DATABASE_BUILTIN, &ret_creds, 
2207                                             global_sid_Builtin);
2208         }
2209
2210         if (!NT_STATUS_IS_OK(result)) {
2211                 d_printf("Failed to fetch builtin database: %s\n",
2212                          nt_errstr(result));
2213                 goto fail;
2214         }
2215
2216         /* Currently we crash on PRIVS somewhere in unmarshalling */
2217         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
2218
2219 fail:
2220         return result;
2221 }
2222