r25950: Enable seperate module to prevent subtree deletes.
[jra/samba/.git] / source4 / scripting / libjs / provision.js
1 /*
2         backend code for provisioning a Samba4 server
3         Copyright Andrew Tridgell 2005
4         Released under the GNU GPL v2 or later
5 */
6
7 sys = sys_init();
8
9 /*
10   return true if the current install seems to be OK
11 */
12 function install_ok(session_info, credentials)
13 {
14         var lp = loadparm_init();
15         var ldb = ldb_init();
16         ldb.session_info = session_info;
17         ldb.credentials = credentials;
18         if (lp.get("realm") == "") {
19                 return false;
20         }
21         var ok = ldb.connect(lp.get("sam database"));
22         if (!ok) {
23                 return false;
24         }
25         var res = ldb.search("(cn=Administrator)");
26         if (res.error != 0 || res.msgs.length != 1) {
27                 return false;
28         }
29         return true;
30 }
31
32 /*
33   find a user or group from a list of possibilities
34 */
35 function findnss()
36 {
37         var i;
38         assert(arguments.length >= 2);
39         var nssfn = arguments[0];
40         for (i=1;i<arguments.length;i++) {
41                 if (nssfn(arguments[i]) != undefined) {
42                         return arguments[i];
43                 }
44         }
45         printf("Unable to find user/group for %s\n", arguments[1]);
46         assert(i<arguments.length);
47 }
48
49 /*
50    add a foreign security principle
51  */
52 function add_foreign(ldb, subobj, sid, desc)
53 {
54         var add = sprintf("
55 dn: CN=%s,CN=ForeignSecurityPrincipals,%s
56 objectClass: top
57 objectClass: foreignSecurityPrincipal
58 description: %s
59 ",
60                           sid, subobj.DOMAINDN, desc);
61         /* deliberately ignore errors from this, as the records may
62            already exist */
63         ldb.add(add);
64 }
65
66
67 /*
68   setup a mapping between a sam name and a unix name
69  */
70 function setup_name_mapping(info, ldb, sid, unixname)
71 {
72         var attrs = new Array("dn");
73         var res = ldb.search(sprintf("objectSid=%s", sid), 
74                              info.subobj.DOMAINDN, ldb.SCOPE_SUBTREE, attrs);
75         if (res.error != 0 || res.msgs.length != 1) {
76                 info.message("Failed to find record for objectSid %s\n", sid);
77                 return false;
78         }
79         var mod = sprintf("
80 dn: %s
81 changetype: modify
82 replace: unixName
83 unixName: %s
84 ",
85                           res.msgs[0].dn, unixname);
86         var ok = ldb.modify(mod);
87         if (ok.error != 0) {
88                 info.message("name mapping for %s failed - %s\n",
89                              sid, ldb.errstring());
90                 return false;
91         }
92         return true;
93 }
94
95 /*
96   return current time as a nt time string
97 */
98 function nttime()
99 {
100         return "" + sys.nttime();
101 }
102
103 /*
104   return current time as a ldap time string
105 */
106 function ldaptime()
107 {
108         return sys.ldaptime(sys.nttime());
109 }
110
111 /*
112   return a date string suitable for a dns zone serial number
113 */
114 function datestring()
115 {
116         var t = sys.ntgmtime(sys.nttime());
117         return sprintf("%04u%02u%02u%02u",
118                        t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour);
119 }
120
121 /*
122   return first host IP
123 */
124 function hostip()
125 {
126         var list = sys.interfaces();
127         return list[0];
128 }
129
130
131 /*
132   return first part of hostname
133 */
134 function hostname()
135 {
136         var s = split(".", sys.hostname());
137         return s[0];
138 }
139
140 /* the ldb is in bad shape, possibly due to being built from an
141    incompatible previous version of the code, so delete it
142    completely */
143 function ldb_delete(info, ldb)
144 {
145         info.message("Deleting " + ldb.filename + "\n");
146         var lp = loadparm_init();
147         sys.unlink(sprintf("%s/%s", lp.get("private dir"), ldb.filename));
148         ldb.transaction_cancel();
149         ldb.close();
150         var ok = ldb.connect(ldb.filename);
151         ldb.transaction_start();
152         assert(ok);
153 }
154
155 /*
156   erase an ldb, removing all records
157 */
158 function ldb_erase(info, ldb)
159 {
160         var res;
161
162         /* delete the specials */
163         ldb.del("@INDEXLIST");
164         ldb.del("@ATTRIBUTES");
165         ldb.del("@OPTIONS");
166         ldb.del("@MODULES");
167         ldb.del("@PARTITION");
168         ldb.del("@KLUDGEACL");
169
170         /* and the rest */
171         attrs = new Array("dn");
172         var basedn = "";
173         var res = ldb.search("(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", basedn, ldb.SCOPE_SUBTREE, attrs);
174         var i;
175         if (res.error != 0) {
176                 ldb_delete(info, ldb);
177                 return;
178         }
179         for (i=0;i<res.msgs.length;i++) {
180                 ldb.del(res.msgs[i].dn);
181         }
182
183         var res = ldb.search("(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", basedn, ldb.SCOPE_SUBTREE, attrs);
184         if (res.error != 0 || res.msgs.length != 0) {
185                 ldb_delete(info, ldb);
186                 return;
187         }
188         assert(res.msgs.length == 0);
189 }
190
191 /*
192   erase an ldb, removing all records
193 */
194 function ldb_erase_partitions(info, ldb, ldapbackend)
195 {
196         var rootDSE_attrs = new Array("namingContexts");
197         var lp = loadparm_init();
198         var j;
199
200         var res = ldb.search("(objectClass=*)", "", ldb.SCOPE_BASE, rootDSE_attrs);
201         assert(res.error == 0);
202         assert(res.msgs.length == 1);
203         if (typeof(res.msgs[0].namingContexts) == "undefined") {
204                 return;
205         }       
206         for (j=0; j<res.msgs[0].namingContexts.length; j++) {
207                 var anything = "(|(objectclass=*)(dn=*))";
208                 var attrs = new Array("dn");
209                 var basedn = res.msgs[0].namingContexts[j];
210                 var k;
211                 var previous_remaining = 1;
212                 var current_remaining = 0;
213
214                 if (ldapbackend && (basedn == info.subobj.DOMAINDN)) {
215                         /* Only delete objects that were created by provision */
216                         anything = "(objectcategory=*)";
217                 }
218
219                 for (k=0; k < 10 && (previous_remaining != current_remaining); k++) {
220                         /* and the rest */
221                         var res2 = ldb.search(anything, basedn, ldb.SCOPE_SUBTREE, attrs);
222                         var i;
223                         if (res2.error != 0) {
224                                 info.message("ldb search failed: " + res.errstr + "\n");
225                                 continue;
226                         }
227                         previous_remaining = current_remaining;
228                         current_remaining = res2.msgs.length;
229                         for (i=0;i<res2.msgs.length;i++) {
230                                 ldb.del(res2.msgs[i].dn);
231                         }
232                         
233                         var res3 = ldb.search(anything, basedn, ldb.SCOPE_SUBTREE, attrs);
234                         if (res3.error != 0) {
235                                 info.message("ldb search failed: " + res.errstr + "\n");
236                                 continue;
237                         }
238                         if (res3.msgs.length != 0) {
239                                 info.message("Failed to delete all records under " + basedn + ", " + res3.msgs.length + " records remaining\n");
240                         }
241                 }
242         }
243 }
244
245 function open_ldb(info, dbname, erase)
246 {
247         var ldb = ldb_init();
248         ldb.session_info = info.session_info;
249         ldb.credentials = info.credentials;
250         ldb.filename = dbname;
251
252         var connect_ok = ldb.connect(dbname);
253         if (!connect_ok) {
254                 var lp = loadparm_init();
255                 sys.unlink(sprintf("%s/%s", lp.get("private dir"), dbname));
256                 connect_ok = ldb.connect(dbname);
257                 assert(connect_ok);
258         }
259
260         ldb.transaction_start();
261
262         if (erase) {
263                 ldb_erase(info, ldb);   
264         }
265         return ldb;
266 }
267
268
269 /*
270   setup a ldb in the private dir
271  */
272 function setup_add_ldif(ldif, info, ldb, failok)
273 {
274         var lp = loadparm_init();
275         var src = lp.get("setup directory") + "/" + ldif;
276
277         var data = sys.file_load(src);
278         data = substitute_var(data, info.subobj);
279
280         var add_res = ldb.add(data);
281         if (add_res.error != 0) {
282                 info.message("ldb load failed: " + add_res.errstr + "\n");
283                 if (!failok) {
284                         assert(add_res.error == 0);
285                 }
286         }
287         return (add_res.error == 0);
288 }
289
290 function setup_modify_ldif(ldif, info, ldb, failok)
291 {
292         var lp = loadparm_init();
293         var src = lp.get("setup directory") + "/" + ldif;
294
295         var data = sys.file_load(src);
296         data = substitute_var(data, info.subobj);
297
298         var mod_res = ldb.modify(data);
299         if (mod_res.error != 0) {
300                 info.message("ldb load failed: " + mod_res.errstr + "\n");
301                 if (!failok) {
302                         assert(mod_res.error == 0);
303                 }
304         }
305         return (mod_res.error == 0);
306 }
307
308
309 function setup_ldb(ldif, info, dbname) 
310 {
311         var erase = true;
312         var failok = false;
313
314         if (arguments.length >= 4) {
315                 erase = arguments[3];
316         }
317         if (arguments.length == 5) {
318                 failok = arguments[4];
319         }
320         var ldb = open_ldb(info, dbname, erase);
321         if (setup_add_ldif(ldif, info, ldb, failok)) {
322                 var commit_ok = ldb.transaction_commit();
323                 if (!commit_ok) {
324                         info.message("ldb commit failed: " + ldb.errstring() + "\n");
325                         assert(commit_ok);
326                 }
327         }
328 }
329
330 /*
331   setup a ldb in the private dir
332  */
333 function setup_ldb_modify(ldif, info, ldb)
334 {
335         var lp = loadparm_init();
336
337         var src = lp.get("setup directory") + "/" + ldif;
338
339         var data = sys.file_load(src);
340         data = substitute_var(data, info.subobj);
341
342         var mod_res = ldb.modify(data);
343         if (mod_res.error != 0) {
344                 info.message("ldb load failed: " + mod_res.errstr + "\n");
345                 return (mod_res.error == 0);
346         }
347         return (mod_res.error == 0);
348 }
349
350 /*
351   setup a file in the private dir
352  */
353 function setup_file(template, message, fname, subobj)
354 {
355         var lp = loadparm_init();
356         var f = fname;
357         var src = lp.get("setup directory") + "/" + template;
358
359         if (! sys.stat(src)) {
360                 message("Template file not found: %s\n",src);
361                 assert(0);
362         }
363
364         sys.unlink(f);
365
366         var data = sys.file_load(src);
367         data = substitute_var(data, subobj);
368
369         ok = sys.file_save(f, data);
370         if (!ok) {
371                 message("failed to create file: " + f + "\n");
372                 assert(ok);
373         }
374 }
375
376 function provision_default_paths(subobj)
377 {
378         /* subobj.DNSDOMAIN isn't available at this point */
379         var dnsdomain = strlower(subobj.REALM);
380         var lp = loadparm_init();
381         var paths = new Object();
382         paths.smbconf = lp.get("config file");
383         paths.shareconf = lp.get("private dir") + "/" + "share.ldb";
384         paths.samdb = lp.get("sam database");
385         paths.secrets = lp.get("secrets database");
386         paths.templates = lp.get("private dir") + "/" + "templates.ldb";
387         paths.keytab = "secrets.keytab";
388         paths.dns_keytab = "dns.keytab";
389         paths.dns_keytab_abs = lp.get("private dir") + "/" + paths.dns_keytab;
390         paths.dns = lp.get("private dir") + "/" + dnsdomain + ".zone";
391         paths.named_conf = lp.get("private dir") + "/named.conf";
392         paths.winsdb = "wins.ldb";
393         paths.ldapdir = lp.get("private dir") + "/ldap";
394         paths.ldap_basedn_ldif = paths.ldapdir + "/" + dnsdomain + ".ldif";
395         paths.ldap_config_basedn_ldif = paths.ldapdir + "/" + dnsdomain + "-config.ldif";
396         paths.ldap_schema_basedn_ldif = paths.ldapdir + "/" + dnsdomain + "-schema.ldif";
397
398         paths.s4_ldapi_socket = lp.get("private dir") + "/ldapi";
399         paths.phpldapadminconfig = lp.get("private dir") + "/phpldapadmin-config.php";
400
401         paths.sysvol = lp.get("sysvol", "path");
402
403         if (paths.sysvol == undefined) {
404                 paths.sysvol = lp.get("lock dir") + "/sysvol";
405         }
406         
407         paths.netlogon = lp.get("netlogon", "path");
408         
409         if (paths.netlogon == undefined) {
410                 paths.netlogon = paths.sysvol + "/" + dnsdomain + "/scripts";
411         }
412
413         return paths;
414 }
415
416
417 /*
418   setup reasonable name mappings for sam names to unix names
419 */
420 function setup_name_mappings(info, ldb)
421 {
422         var lp = loadparm_init();
423         var attrs = new Array("objectSid");
424         var subobj = info.subobj;
425
426         res = ldb.search("objectSid=*", subobj.DOMAINDN, ldb.SCOPE_BASE, attrs);
427         assert(res.error == 0);
428         assert(res.msgs.length == 1 && res.msgs[0].objectSid != undefined);
429         var sid = res.msgs[0].objectSid;
430
431         /* add some foreign sids if they are not present already */
432         add_foreign(ldb, subobj, "S-1-5-7",  "Anonymous");
433         add_foreign(ldb, subobj, "S-1-1-0",  "World");
434         add_foreign(ldb, subobj, "S-1-5-2",  "Network");
435         add_foreign(ldb, subobj, "S-1-5-18", "System");
436         add_foreign(ldb, subobj, "S-1-5-11", "Authenticated Users");
437
438         /* some well known sids */
439         setup_name_mapping(info, ldb, "S-1-5-7",  subobj.NOBODY);
440         setup_name_mapping(info, ldb, "S-1-1-0",  subobj.NOGROUP);
441         setup_name_mapping(info, ldb, "S-1-5-2",  subobj.NOGROUP);
442         setup_name_mapping(info, ldb, "S-1-5-18", subobj.ROOT);
443         setup_name_mapping(info, ldb, "S-1-5-11", subobj.USERS);
444         setup_name_mapping(info, ldb, "S-1-5-32-544", subobj.WHEEL);
445         setup_name_mapping(info, ldb, "S-1-5-32-545", subobj.USERS);
446         setup_name_mapping(info, ldb, "S-1-5-32-546", subobj.NOGROUP);
447         setup_name_mapping(info, ldb, "S-1-5-32-551", subobj.BACKUP);
448
449         /* and some well known domain rids */
450         setup_name_mapping(info, ldb, sid + "-500", subobj.ROOT);
451         setup_name_mapping(info, ldb, sid + "-518", subobj.WHEEL);
452         setup_name_mapping(info, ldb, sid + "-519", subobj.WHEEL);
453         setup_name_mapping(info, ldb, sid + "-512", subobj.WHEEL);
454         setup_name_mapping(info, ldb, sid + "-513", subobj.USERS);
455         setup_name_mapping(info, ldb, sid + "-520", subobj.WHEEL);
456
457         return true;
458 }
459
460 function provision_fix_subobj(subobj, paths)
461 {
462         var ldb = ldb_init();
463         
464         subobj.REALM       = strupper(subobj.REALM);
465         subobj.HOSTNAME    = strlower(subobj.HOSTNAME);
466         subobj.DOMAIN      = strupper(subobj.DOMAIN);
467         assert(valid_netbios_name(subobj.DOMAIN));
468         subobj.NETBIOSNAME = strupper(subobj.HOSTNAME);
469         assert(valid_netbios_name(subobj.NETBIOSNAME));
470         subobj.DNSDOMAIN    = strlower(subobj.REALM);
471         subobj.DNSNAME      = sprintf("%s.%s", 
472                                       strlower(subobj.HOSTNAME), 
473                                       subobj.DNSDOMAIN);
474         var rdn_list = split(".", subobj.DNSDOMAIN);
475         subobj.DOMAINDN     = "DC=" + join(",DC=", rdn_list);
476         subobj.ROOTDN       = subobj.DOMAINDN;
477         subobj.CONFIGDN     = "CN=Configuration," + subobj.ROOTDN;
478         subobj.SCHEMADN     = "CN=Schema," + subobj.CONFIGDN;
479
480         subobj.MACHINEPASS_B64 = ldb.encode(subobj.MACHINEPASS);
481         subobj.KRBTGTPASS_B64  = ldb.encode(subobj.KRBTGTPASS);
482         subobj.ADMINPASS_B64   = ldb.encode(subobj.ADMINPASS);
483         subobj.DNSPASS_B64     = ldb.encode(subobj.DNSPASS);
484
485         var rdns = split(",", subobj.DOMAINDN);
486         subobj.RDN_DC = substr(rdns[0], strlen("DC="));
487
488         subobj.SAM_LDB          = "tdb://" + paths.samdb;
489         subobj.SECRETS_KEYTAB   = paths.keytab;
490         subobj.DNS_KEYTAB       = paths.dns_keytab;
491         subobj.DNS_KEYTAB_ABS   = paths.dns_keytab_abs;
492
493         subobj.LDAPDIR = paths.ldapdir;
494         var ldap_path_list = split("/", paths.ldapdir);
495         subobj.LDAPI_URI = "ldapi://" + join("%2F", ldap_path_list) + "%2Fldapi";
496
497         var s4ldap_path_list = split("/", paths.s4_ldapi_socket);
498         subobj.S4_LDAPI_URI = "ldapi://" + join("%2F", s4ldap_path_list);
499
500         subobj.LDAPMANAGERDN = "cn=Manager," + subobj.DOMAINDN;
501
502         subobj.NETLOGONPATH = paths.netlogon;
503         subobj.SYSVOLPATH = paths.sysvol;
504
505         if (subobj.DOMAIN_CONF == undefined) {
506                 subobj.DOMAIN_CONF = subobj.DOMAIN;
507         }
508         if (subobj.REALM_CONF == undefined) {
509                 subobj.REALM_CONF = subobj.REALM;
510         }
511         if (strlower(subobj.SERVERROLE) != strlower("domain controller")) {
512                 subobj.REALM = subobj.HOSTNAME;
513                 subobj.DOMAIN = subobj.HOSTNAME;
514         }
515
516         return true;
517 }
518
519 function provision_become_dc(subobj, message, erase, paths, session_info)
520 {
521         var lp = loadparm_init();
522         var sys = sys_init();
523         var info = new Object();
524
525         var ok = provision_fix_subobj(subobj, paths);
526         assert(ok);
527
528         info.subobj = subobj;
529         info.message = message;
530         info.session_info = session_info;
531
532         message("Setting up teplates into " + paths.templates + "\n");
533         setup_ldb("provision_templates.ldif", info, paths.templates);
534
535         /* Also wipes the database */
536         message("Setting up " + paths.samdb + " partitions\n");
537         setup_ldb("provision_partitions.ldif", info, paths.samdb);
538
539         var samdb = open_ldb(info, paths.samdb, false);
540
541         message("Setting up " + paths.samdb + " attributes\n");
542         setup_add_ldif("provision_init.ldif", info, samdb, false);
543
544         message("Setting up " + paths.samdb + " rootDSE\n");
545         setup_add_ldif("provision_rootdse_add.ldif", info, samdb, false);
546
547         if (erase) {
548                 message("Erasing data from partitions\n");
549                 ldb_erase_partitions(info, samdb, undefined);
550         }
551
552         message("Setting up " + paths.samdb + " indexes\n");
553         setup_add_ldif("provision_index.ldif", info, samdb, false);
554
555         ok = samdb.transaction_commit();
556         assert(ok);
557
558         message("Setting up " + paths.secrets + "\n");
559         setup_ldb("secrets_init.ldif", info, paths.secrets);
560
561         setup_ldb("secrets.ldif", info, paths.secrets, false);
562
563         setup_ldb("secrets_dc.ldif", info, paths.secrets, false);
564
565         return true;
566 }
567
568 /*
569   provision samba4 - caution, this wipes all existing data!
570 */
571 function provision(subobj, message, blank, paths, session_info, credentials, ldapbackend)
572 {
573         var lp = loadparm_init();
574         var sys = sys_init();
575         var info = new Object();
576
577         var ok = provision_fix_subobj(subobj, paths);
578         assert(ok);
579
580         if (subobj.DOMAINGUID != undefined) {
581                 subobj.DOMAINGUID_MOD = sprintf("replace: objectGUID\nobjectGUID: %s\n-", subobj.DOMAINGUID);
582         } else {
583                 subobj.DOMAINGUID_MOD = "";
584         }
585
586         if (subobj.HOSTGUID != undefined) {
587                 subobj.HOSTGUID_ADD = sprintf("objectGUID: %s", subobj.HOSTGUID);
588         } else {
589                 subobj.HOSTGUID_ADD = "";
590         }
591
592         info.subobj = subobj;
593         info.message = message;
594         info.credentials = credentials;
595         info.session_info = session_info;
596
597         /* only install a new smb.conf if there isn't one there already */
598         var st = sys.stat(paths.smbconf);
599         if (st == undefined) {
600                 var smbconfsuffix;
601                 if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
602                         smbconfsuffix = "dc";
603                 } else if (strlower(subobj.SERVERROLE) == strlower("member server")) {
604                         smbconfsuffix = "member";
605                 } else {
606                         smbconfsuffix = subobj.SERVERROLE;
607                 }
608                 message("Setting up " + paths.smbconf +"\n");
609                 setup_file("provision.smb.conf." + smbconfsuffix, info.message, paths.smbconf, subobj);
610                 lp.reload();
611         }
612         /* only install a new shares config db if there is none */
613         st = sys.stat(paths.shareconf);
614         if (st == undefined) {
615                 message("Setting up share.ldb\n");
616                 setup_ldb("share.ldif", info, paths.shareconf);
617         }
618
619         message("Setting up " + paths.secrets + "\n");
620         setup_ldb("secrets_init.ldif", info, paths.secrets);
621         setup_ldb("secrets.ldif", info, paths.secrets, false);
622
623         message("Setting up the registry\n");
624         var reg = reg_open();
625         reg.apply_patchfile(lp.get("setup directory") + "/provision.reg")
626
627         message("Setting up teplates into " + paths.templates + "\n");
628         setup_ldb("provision_templates.ldif", info, paths.templates);
629
630         message("Setting up sam.ldb partitions\n");
631         /* Also wipes the database */
632         setup_ldb("provision_partitions.ldif", info, paths.samdb);
633
634         var samdb = open_ldb(info, paths.samdb, false);
635
636         message("Setting up sam.ldb attributes\n");
637         setup_add_ldif("provision_init.ldif", info, samdb, false);
638
639         message("Setting up sam.ldb rootDSE\n");
640         setup_add_ldif("provision_rootdse_add.ldif", info, samdb, false);
641
642         message("Erasing data from partitions\n");
643         ldb_erase_partitions(info, samdb, ldapbackend);
644         
645         // (hack) Reload, now we have the partitions and rootdse loaded.  
646         var commit_ok = samdb.transaction_commit();
647         if (!commit_ok) {
648                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
649                 assert(commit_ok);
650         }
651         samdb.close();
652
653         samdb = open_ldb(info, paths.samdb, false);
654
655         message("Adding DomainDN: " + subobj.DOMAINDN + " (permitted to fail)\n");
656         var add_ok = setup_add_ldif("provision_basedn.ldif", info, samdb, true);
657         message("Modifying DomainDN: " + subobj.DOMAINDN + "\n");
658         var modify_ok = setup_ldb_modify("provision_basedn_modify.ldif", info, samdb);
659         if (!modify_ok) {
660                 if (!add_ok) {
661                         message("%s", "Failed to both add and modify " + subobj.DOMAINDN + " in target " + subobj.DOMAINDN_LDB + ": " + samdb.errstring() + "\n");
662                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
663                 };
664                 assert(modify_ok);
665         };
666
667         message("Adding configuration container (permitted to fail)\n");
668         var add_ok = setup_add_ldif("provision_configuration_basedn.ldif", info, samdb, true);
669         message("Modifying configuration container\n");
670         var modify_ok = setup_ldb_modify("provision_configuration_basedn_modify.ldif", info, samdb);
671         if (!modify_ok) {
672                 if (!add_ok) {
673                         message("%s", "Failed to both add and modify " + subobj.CONFIGDN + " in target " + subobj.CONFIGDN_LDB + ": " + samdb.errstring() + "\n");
674                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
675                         assert(modify_ok);
676                 }
677                 assert(modify_ok);
678         }
679
680         message("Adding schema container (permitted to fail)\n");
681         var add_ok = setup_add_ldif("provision_schema_basedn.ldif", info, samdb, true);
682         message("Modifying schema container\n");
683         var modify_ok = setup_ldb_modify("provision_schema_basedn_modify.ldif", info, samdb);
684         if (!modify_ok) {
685                 if (!add_ok) {
686                         message("%s", "Failed to both add and modify " + subobj.SCHEMADN + " in target " + subobj.SCHEMADN_LDB + ": " + samdb.errstring() + "\n");
687                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
688                         assert(modify_ok);
689                 }
690                 message("Failed to modify the schema container: " + samdb.errstring() + "\n");
691                 assert(modify_ok);
692         }
693
694         message("Setting up sam.ldb Samba4 schema\n");
695         setup_add_ldif("schema_samba4.ldif", info, samdb, false);
696         message("Setting up sam.ldb AD schema\n");
697         setup_add_ldif("schema.ldif", info, samdb, false);
698
699         // (hack) Reload, now we have the schema loaded.  
700         var commit_ok = samdb.transaction_commit();
701         if (!commit_ok) {
702                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
703                 assert(commit_ok);
704         }
705         samdb.close();
706
707         samdb = open_ldb(info, paths.samdb, false);
708
709         message("Setting up sam.ldb configuration data\n");
710         setup_add_ldif("provision_configuration.ldif", info, samdb, false);
711
712         message("Setting up display specifiers\n");
713         setup_add_ldif("display_specifiers.ldif", info, samdb, false);
714
715         message("Adding users container (permitted to fail)\n");
716         var add_ok = setup_add_ldif("provision_users_add.ldif", info, samdb, true);
717         message("Modifying users container\n");
718         var modify_ok = setup_ldb_modify("provision_users_modify.ldif", info, samdb);
719         if (!modify_ok) {
720                 if (!add_ok) {
721                         message("Failed to both add and modify the users container\n");
722                         assert(modify_ok);
723                 }
724                 assert(modify_ok);
725         }
726         message("Adding computers container (permitted to fail)\n");
727         var add_ok = setup_add_ldif("provision_computers_add.ldif", info, samdb, true);
728         message("Modifying computers container\n");
729         var modify_ok = setup_ldb_modify("provision_computers_modify.ldif", info, samdb);
730         if (!modify_ok) {
731                 if (!add_ok) {
732                         message("Failed to both add and modify the computers container\n");
733                         assert(modify_ok);
734                 }
735                 assert(modify_ok);
736         }
737
738         message("Setting up sam.ldb data\n");
739         setup_add_ldif("provision.ldif", info, samdb, false);
740
741         if (blank != false) {
742                 message("Setting up sam.ldb index\n");
743                 setup_add_ldif("provision_index.ldif", info, samdb, false);
744
745                 message("Setting up sam.ldb rootDSE marking as syncronized\n");
746                 setup_modify_ldif("provision_rootdse_modify.ldif", info, samdb, false);
747
748                 var commit_ok = samdb.transaction_commit();
749                 if (!commit_ok) {
750                         info.message("ldb commit failed: " + samdb.errstring() + "\n");
751                         assert(commit_ok);
752                 }
753                 return true;
754         }
755
756 //      message("Activate schema module");
757 //      setup_modify_ldif("schema_activation.ldif", info, samdb, false);
758 //
759 //      // (hack) Reload, now we have the schema loaded.  
760 //      var commit_ok = samdb.transaction_commit();
761 //      if (!commit_ok) {
762 //              info.message("samdb commit failed: " + samdb.errstring() + "\n");
763 //              assert(commit_ok);
764 //      }
765 //      samdb.close();
766 //
767 //      samdb = open_ldb(info, paths.samdb, false);
768 //
769         message("Setting up sam.ldb users and groups\n");
770         setup_add_ldif("provision_users.ldif", info, samdb, false);
771
772         if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
773                 message("Setting up self join\n");
774                 setup_add_ldif("provision_self_join.ldif", info, samdb, false);
775                 setup_add_ldif("provision_group_policy.ldif", info, samdb, false);
776
777                 sys.mkdir(paths.sysvol, 0755);
778                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN, 0755);
779                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies", 0755);
780                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}", 0755);
781                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}/Machine", 0755);
782                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}/User", 0755);
783
784                 sys.mkdir(paths.netlogon, 0755);
785
786                 setup_ldb("secrets_dc.ldif", info, paths.secrets, false);
787
788         }
789
790         if (setup_name_mappings(info, samdb) == false) {
791                 return false;
792         }
793
794         message("Setting up sam.ldb index\n");
795         setup_add_ldif("provision_index.ldif", info, samdb, false);
796
797         message("Setting up sam.ldb rootDSE marking as syncronized\n");
798         setup_modify_ldif("provision_rootdse_modify.ldif", info, samdb, false);
799
800         var commit_ok = samdb.transaction_commit();
801         if (!commit_ok) {
802                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
803                 assert(commit_ok);
804         }
805
806         message("Setting up phpLDAPadmin configuration\n");
807         setup_file("phpldapadmin-config.php", info.message, paths.phpldapadminconfig, subobj);
808         message("Please install the phpLDAPadmin configuration located at " + paths.phpldapadminconfig + " into /etc/phpldapadmin/config.php\n");
809
810         return true;
811 }
812
813 /*
814   provision just the schema into a temporary ldb, so we can run ad2oLschema on it
815 */
816 function provision_schema(subobj, message, tmp_schema_path, paths)
817 {
818         var lp = loadparm_init();
819         var sys = sys_init();
820         var info = new Object();
821
822         var ok = provision_fix_subobj(subobj, paths);
823         assert(ok);
824
825         info.subobj = subobj;
826         info.message = message;
827
828         message("Setting up sam.ldb partitions\n");
829
830         /* This will erase anything in the tmp db */
831         var samdb = open_ldb(info, tmp_schema_path, true);
832
833         message("Adding schema container (permitted to fail)\n");
834         var add_ok = setup_add_ldif("provision_schema_basedn.ldif", info, samdb, true);
835         message("Modifying schema container\n");
836         var modify_ok = setup_ldb_modify("provision_schema_basedn_modify.ldif", info, samdb);
837         if (!modify_ok) {
838                 if (!add_ok) {
839                         message("Failed to both add and modify schema dn: " + samdb.errstring() + "\n");
840                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
841                         assert(modify_ok);
842                 }
843                 message("Failed to modify the schema container: " + samdb.errstring() + "\n");
844                 assert(modify_ok);
845         }
846
847         message("Setting up sam.ldb Samba4 schema\n");
848         setup_add_ldif("schema_samba4.ldif", info, samdb, false);
849         message("Setting up sam.ldb AD schema\n");
850         setup_add_ldif("schema.ldif", info, samdb, false);
851
852         var commit_ok = samdb.transaction_commit();
853         if (!commit_ok) {
854                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
855                 assert(commit_ok);
856         }
857         samdb.close();
858 }
859
860 /* Write out a DNS zone file, from the info in the current database */
861 function provision_dns(subobj, message, paths, session_info, credentials)
862 {
863         var lp = loadparm_init();
864         if (strlower(subobj.SERVERROLE) != strlower("domain controller")) {
865                 message("No DNS zone required for role %s\n", subobj.SERVERROLE);
866                 return;
867         }
868         message("Setting up DNS zone: " + subobj.DNSDOMAIN + " \n");
869         var ldb = ldb_init();
870         ldb.session_info = session_info;
871         ldb.credentials = credentials;
872
873         /* connect to the sam */
874         var ok = ldb.connect(paths.samdb);
875         assert(ok);
876
877         /* These values may have changed, due to an incoming SamSync,
878            or may not have been specified, so fetch them from the database */
879
880         var attrs = new Array("objectGUID");
881         res = ldb.search("objectGUID=*", subobj.DOMAINDN, ldb.SCOPE_BASE, attrs);
882         assert(res.error == 0);
883         assert(res.msgs.length == 1);
884         assert(res.msgs[0].objectGUID != undefined);
885         subobj.DOMAINGUID = res.msgs[0].objectGUID;
886
887         subobj.HOSTGUID = searchone(ldb, subobj.DOMAINDN, "(&(objectClass=computer)(cn=" + subobj.NETBIOSNAME + "))", "objectGUID");
888         assert(subobj.HOSTGUID != undefined);
889
890         setup_file("provision.zone", 
891                    message, paths.dns, 
892                    subobj);
893
894         setup_file("named.conf", 
895                    message, paths.named_conf, 
896                    subobj);
897
898         message("Please install the zone located in " + paths.dns + " into your DNS server.  A sample BIND configuration snippit is at " + paths.named_conf + "\n");
899 }
900
901 /* Write out a DNS zone file, from the info in the current database */
902 function provision_ldapbase(subobj, message, paths)
903 {
904         var ok = provision_fix_subobj(subobj, paths);
905         assert(ok);
906
907         message("Setting up LDAP base entry: " + subobj.DOMAINDN + " \n");
908         var rdns = split(",", subobj.DOMAINDN);
909         subobj.EXTENSIBLEOBJECT = "objectClass: extensibleObject";
910
911         subobj.RDN_DC = substr(rdns[0], strlen("DC="));
912
913         sys.mkdir(paths.ldapdir, 0700);
914
915         setup_file("provision_basedn.ldif", 
916                    message, paths.ldap_basedn_ldif, 
917                    subobj);
918
919         setup_file("provision_configuration_basedn.ldif", 
920                    message, paths.ldap_config_basedn_ldif, 
921                    subobj);
922
923         setup_file("provision_schema_basedn.ldif", 
924                    message, paths.ldap_schema_basedn_ldif, 
925                    subobj);
926
927 }
928
929
930 /*
931   guess reasonably default options for provisioning
932 */
933 function provision_guess()
934 {
935         var subobj = new Object();
936         var nss = nss_init();
937         var lp = loadparm_init();
938         var rdn_list;
939         random_init(local);
940
941         subobj.SERVERROLE   = strlower(lp.get("server role"));
942         subobj.REALM        = strupper(lp.get("realm"));
943         subobj.DOMAIN       = lp.get("workgroup");
944         subobj.HOSTNAME     = hostname();
945
946         assert(subobj.REALM);
947         assert(subobj.DOMAIN);
948         assert(subobj.HOSTNAME);
949         
950         subobj.VERSION      = version();
951         subobj.HOSTIP       = hostip();
952         subobj.DOMAINSID    = randsid();
953         subobj.INVOCATIONID = randguid();
954         subobj.POLICYGUID   = randguid();
955         subobj.KRBTGTPASS   = randpass(12);
956         subobj.MACHINEPASS  = randpass(12);
957         subobj.DNSPASS  = randpass(12);
958         subobj.ADMINPASS    = randpass(12);
959         subobj.LDAPMANAGERPASS     = randpass(12);
960         subobj.DEFAULTSITE  = "Default-First-Site-Name";
961         subobj.NEWGUID      = randguid;
962         subobj.NTTIME       = nttime;
963         subobj.LDAPTIME     = ldaptime;
964         subobj.DATESTRING   = datestring;
965         subobj.ROOT         = findnss(nss.getpwnam, "root");
966         subobj.NOBODY       = findnss(nss.getpwnam, "nobody");
967         subobj.NOGROUP      = findnss(nss.getgrnam, "nogroup", "nobody");
968         subobj.WHEEL        = findnss(nss.getgrnam, "wheel", "root", "staff", "adm");
969         subobj.BACKUP       = findnss(nss.getgrnam, "backup", "wheel", "root", "staff");
970         subobj.USERS        = findnss(nss.getgrnam, "users", "guest", "other", "unknown", "usr");
971
972         //Add modules to the list to activate them by default
973         //beware often order is important
974         //
975         // Some Known ordering constraints:
976         // - rootdse must be first, as it makes redirects from "" -> cn=rootdse
977         // - objectclass must be before password_hash, because password_hash checks
978         //   that the objectclass is of type person (filled in by the objectclass 
979         //   module when expanding the objectclass list)
980         // - partition must be last
981         // - each partition has its own module list then
982         modules_list        = new Array("rootdse",
983                                         "paged_results",
984                                         "server_sort",
985                                         "extended_dn",
986                                         "asq",
987                                         "samldb",
988                                         "rdn_name",
989                                         "objectclass",
990                                         "kludge_acl",
991                                         "operational",
992                                         "subtree_rename",
993                                         "subtree_delete",
994                                         "linked_attributes",
995                                         "show_deleted",
996                                         "partition");
997         subobj.MODULES_LIST = join(",", modules_list);
998         subobj.DOMAINDN_LDB = "users.ldb";
999         subobj.CONFIGDN_LDB = "configuration.ldb";
1000         subobj.SCHEMADN_LDB = "schema.ldb";
1001         subobj.DOMAINDN_MOD = "pdc_fsmo,password_hash";
1002         subobj.CONFIGDN_MOD = "naming_fsmo";
1003         subobj.SCHEMADN_MOD = "schema_fsmo";
1004         subobj.DOMAINDN_MOD2 = ",objectguid";
1005         subobj.CONFIGDN_MOD2 = ",objectguid";
1006         subobj.SCHEMADN_MOD2 = ",objectguid";
1007
1008         subobj.EXTENSIBLEOBJECT = "# no objectClass: extensibleObject for local ldb";
1009         subobj.ACI              = "# no aci for local ldb";
1010
1011         return subobj;
1012 }
1013
1014 /*
1015   search for one attribute as a string
1016  */
1017 function searchone(ldb, basedn, expression, attribute)
1018 {
1019         var attrs = new Array(attribute);
1020         res = ldb.search(expression, basedn, ldb.SCOPE_SUBTREE, attrs);
1021         if (res.error != 0 ||
1022             res.msgs.length != 1 ||
1023             res.msgs[0][attribute] == undefined) {
1024                 return undefined;
1025         }
1026         return res.msgs[0][attribute];
1027 }
1028
1029 /*
1030   modify an account to remove the 
1031 */
1032 function enable_account(ldb, user_dn)
1033 {
1034         var attrs = new Array("userAccountControl");
1035         var res = ldb.search(NULL, user_dn, ldb.SCOPE_ONELEVEL, attrs);
1036         assert(res.error == 0);
1037         assert(res.msgs.length == 1);
1038         var userAccountControl = res.msgs[0].userAccountControl;
1039         userAccountControl = userAccountControl - 2; /* remove disabled bit */
1040         var mod = sprintf("
1041 dn: %s
1042 changetype: modify
1043 replace: userAccountControl
1044 userAccountControl: %u
1045 ", 
1046                           user_dn, userAccountControl);
1047         var ok = ldb.modify(mod);
1048         return (ok.error == 0); 
1049 }
1050
1051
1052 /*
1053   add a new user record
1054 */
1055 function newuser(username, unixname, password, message, session_info, credentials)
1056 {
1057         var lp = loadparm_init();
1058         var samdb = lp.get("sam database");
1059         var ldb = ldb_init();
1060         random_init(local);
1061         ldb.session_info = session_info;
1062         ldb.credentials = credentials;
1063
1064         /* connect to the sam */
1065         var ok = ldb.connect(samdb);
1066         assert(ok);
1067
1068         ldb.transaction_start();
1069
1070         /* find the DNs for the domain and the domain users group */
1071         var attrs = new Array("defaultNamingContext");
1072         res = ldb.search("defaultNamingContext=*", "", ldb.SCOPE_BASE, attrs);
1073         assert(res.error == 0);
1074         assert(res.msgs.length == 1 && res.msgs[0].defaultNamingContext != undefined);
1075         var domain_dn = res.msgs[0].defaultNamingContext;
1076         assert(domain_dn != undefined);
1077         var dom_users = searchone(ldb, domain_dn, "name=Domain Users", "dn");
1078         assert(dom_users != undefined);
1079
1080         var user_dn = sprintf("CN=%s,CN=Users,%s", username, domain_dn);
1081
1082
1083         /*
1084           the new user record. note the reliance on the samdb module to fill
1085           in a sid, guid etc
1086         */
1087         var ldif = sprintf("
1088 dn: %s
1089 sAMAccountName: %s
1090 unixName: %s
1091 sambaPassword: %s
1092 objectClass: user
1093 ",
1094                            user_dn, username, dom_users,
1095                            unixname, password);
1096         /*
1097           add the user to the users group as well
1098         */
1099         var modgroup = sprintf("
1100 dn: %s
1101 changetype: modify
1102 add: member
1103 member: %s
1104 ", 
1105                                dom_users, user_dn);
1106
1107
1108         /*
1109           now the real work
1110         */
1111         message("Adding user %s\n", user_dn);
1112         ok = ldb.add(ldif);
1113         if (ok.error != 0) {
1114                 message("Failed to add %s - %s\n", user_dn, ok.errstr);
1115                 return false;
1116         }
1117
1118         message("Modifying group %s\n", dom_users);
1119         ok = ldb.modify(modgroup);
1120         if (ok.error != 0) {
1121                 message("Failed to modify %s - %s\n", dom_users, ok.errstr);
1122                 return false;
1123         }
1124
1125         /*
1126           modify the userAccountControl to remove the disabled bit
1127         */
1128         ok = enable_account(ldb, user_dn);
1129         if (ok) {
1130                 ldb.transaction_commit();
1131         }
1132         return ok;
1133 }
1134
1135 // Check whether a name is valid as a NetBIOS name. 
1136 // FIXME: There are probably more constraints here. 
1137 // crh has a paragraph on this in his book (1.4.1.1)
1138 function valid_netbios_name(name)
1139 {
1140         if (strlen(name) > 13) return false;
1141         return true;
1142 }
1143
1144 function provision_validate(subobj, message)
1145 {
1146         var lp = loadparm_init();
1147
1148         if (!valid_netbios_name(subobj.DOMAIN)) {
1149                 message("Invalid NetBIOS name for domain\n");
1150                 return false;
1151         }
1152
1153         if (!valid_netbios_name(subobj.NETBIOSNAME)) {
1154                 message("Invalid NetBIOS name for host\n");
1155                 return false;
1156         }
1157
1158
1159         if (strupper(lp.get("workgroup")) != strupper(subobj.DOMAIN_CONF)) {
1160                 message("workgroup '%s' in smb.conf must match chosen domain '%s'\n",
1161                         lp.get("workgroup"), subobj.DOMAIN_CONF);
1162                 return false;
1163         }
1164
1165         if (strupper(lp.get("realm")) != strupper(subobj.REALM_CONF)) {
1166                 message("realm '%s' in smb.conf must match chosen realm '%s'\n",
1167                         lp.get("realm"), subobj.REALM_CONF);
1168                 return false;
1169         }
1170
1171         if (strlower(lp.get("server role")) != strlower(subobj.SERVERROLE)) {
1172                 message("server role '%s' in smb.conf must match chosen role '%s'\n",
1173                         lp.get("server role"), subobj.SERVERROLE);
1174                 return false;
1175         }
1176
1177         return true;
1178 }
1179
1180 function join_domain(domain, netbios_name, join_type, creds, message) 
1181 {
1182         var ctx = NetContext(creds);
1183         var joindom = new Object();
1184         joindom.domain = domain;
1185         joindom.join_type = join_type;
1186         joindom.netbios_name = netbios_name;
1187         if (!ctx.JoinDomain(joindom)) {
1188                 message("Domain Join failed: " + joindom.error_string);
1189                 return false;
1190         }
1191         return true;
1192 }
1193
1194 /* Vampire a remote domain.  Session info and credentials are required for for
1195  * access to our local database (might be remote ldap)
1196  */ 
1197
1198 function vampire(domain, session_info, credentials, message) {
1199         var ctx = NetContext(credentials);
1200         var vampire_ctx = new Object();
1201         var machine_creds = credentials_init();
1202         machine_creds.set_domain(form.DOMAIN);
1203         if (!machine_creds.set_machine_account()) {
1204                 message("Failed to access domain join information!");
1205                 return false;
1206         }
1207         vampire_ctx.machine_creds = machine_creds;
1208         vampire_ctx.session_info = session_info;
1209         if (!ctx.SamSyncLdb(vampire_ctx)) {
1210                 message("Migration of remote domain to Samba failed: " + vampire_ctx.error_string);
1211                 return false;
1212         }
1213
1214         return true;
1215 }
1216
1217 return 0;