Convert some more files to GPLv3.
[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 version 3 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=*)(distinguishedName=*))(!(distinguishedName=@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=*)(distinguishedName=*))(!(distinguishedName=@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         if (res.error != 0) {
202                 info.message("rootdse search failed: " + res.errstr + "\n");
203                 assert(res.error == 0);
204         }
205         assert(res.msgs.length == 1);
206         if (typeof(res.msgs[0].namingContexts) == "undefined") {
207                 return;
208         }       
209         for (j=0; j<res.msgs[0].namingContexts.length; j++) {
210                 var anything = "(|(objectclass=*)(distinguishedName=*))";
211                 var attrs = new Array("distinguishedName");
212                 var basedn = res.msgs[0].namingContexts[j];
213                 var k;
214                 var previous_remaining = 1;
215                 var current_remaining = 0;
216
217                 if (ldapbackend && (basedn == info.subobj.DOMAINDN)) {
218                         /* Only delete objects that were created by provision */
219                         anything = "(objectcategory=*)";
220                 }
221
222                 for (k=0; k < 10 && (previous_remaining != current_remaining); k++) {
223                         /* and the rest */
224                         var res2 = ldb.search(anything, basedn, ldb.SCOPE_SUBTREE, attrs);
225                         var i;
226                         if (res2.error != 0) {
227                                 if (res2.error == 32) {
228                                         break;
229                                 } else {
230                                         info.message("ldb search(2) failed: " + res2.errstr + "\n");
231                                         continue;
232                                 }
233                         }
234                         previous_remaining = current_remaining;
235                         current_remaining = res2.msgs.length;
236                         for (i=0;i<res2.msgs.length;i++) {
237                                 ldb.del(res2.msgs[i].dn);
238                         }
239                         
240                         var res3 = ldb.search(anything, basedn, ldb.SCOPE_SUBTREE, attrs);
241                         if (res3.error != 0) {
242                                 info.message("ldb search(3) failed: " + res3.errstr + "\n");
243                                 continue;
244                         }
245                         if (res3.msgs.length != 0) {
246                                 info.message("Failed to delete all records under " + basedn + ", " + res3.msgs.length + " records remaining\n");
247                         }
248                 }
249         }
250 }
251
252 function open_ldb(info, dbname, erase)
253 {
254         var ldb = ldb_init();
255         ldb.session_info = info.session_info;
256         ldb.credentials = info.credentials;
257         ldb.filename = dbname;
258
259         var connect_ok = ldb.connect(dbname);
260         if (!connect_ok) {
261                 var lp = loadparm_init();
262                 sys.unlink(sprintf("%s/%s", lp.get("private dir"), dbname));
263                 connect_ok = ldb.connect(dbname);
264                 assert(connect_ok);
265         }
266
267         ldb.transaction_start();
268
269         if (erase) {
270                 ldb_erase(info, ldb);   
271         }
272         return ldb;
273 }
274
275
276 /*
277   setup a ldb in the private dir
278  */
279 function setup_add_ldif(ldif, info, ldb, failok)
280 {
281         var lp = loadparm_init();
282         var src = lp.get("setup directory") + "/" + ldif;
283
284         var data = sys.file_load(src);
285         data = substitute_var(data, info.subobj);
286
287         var add_res = ldb.add(data);
288         if (add_res.error != 0) {
289                 info.message("ldb load failed: " + add_res.errstr + "\n");
290                 if (!failok) {
291                         assert(add_res.error == 0);
292                 }
293         }
294         return (add_res.error == 0);
295 }
296
297 function setup_modify_ldif(ldif, info, ldb, failok)
298 {
299         var lp = loadparm_init();
300         var src = lp.get("setup directory") + "/" + ldif;
301
302         var data = sys.file_load(src);
303         data = substitute_var(data, info.subobj);
304
305         var mod_res = ldb.modify(data);
306         if (mod_res.error != 0) {
307                 info.message("ldb load failed: " + mod_res.errstr + "\n");
308                 if (!failok) {
309                         assert(mod_res.error == 0);
310                 }
311         }
312         return (mod_res.error == 0);
313 }
314
315
316 function setup_ldb(ldif, info, dbname) 
317 {
318         var erase = true;
319         var failok = false;
320
321         if (arguments.length >= 4) {
322                 erase = arguments[3];
323         }
324         if (arguments.length == 5) {
325                 failok = arguments[4];
326         }
327         var ldb = open_ldb(info, dbname, erase);
328         if (setup_add_ldif(ldif, info, ldb, failok)) {
329                 var commit_ok = ldb.transaction_commit();
330                 if (!commit_ok) {
331                         info.message("ldb commit failed: " + ldb.errstring() + "\n");
332                         assert(commit_ok);
333                 }
334         }
335 }
336
337 /*
338   setup a ldb in the private dir
339  */
340 function setup_ldb_modify(ldif, info, ldb)
341 {
342         var lp = loadparm_init();
343
344         var src = lp.get("setup directory") + "/" + ldif;
345
346         var data = sys.file_load(src);
347         data = substitute_var(data, info.subobj);
348
349         var mod_res = ldb.modify(data);
350         if (mod_res.error != 0) {
351                 info.message("ldb load failed: " + mod_res.errstr + "\n");
352                 return (mod_res.error == 0);
353         }
354         return (mod_res.error == 0);
355 }
356
357 /*
358   setup a file in the private dir
359  */
360 function setup_file(template, message, fname, subobj)
361 {
362         var lp = loadparm_init();
363         var f = fname;
364         var src = lp.get("setup directory") + "/" + template;
365
366         if (! sys.stat(src)) {
367                 message("Template file not found: %s\n",src);
368                 assert(0);
369         }
370
371         sys.unlink(f);
372
373         var data = sys.file_load(src);
374         data = substitute_var(data, subobj);
375
376         ok = sys.file_save(f, data);
377         if (!ok) {
378                 message("failed to create file: " + f + "\n");
379                 assert(ok);
380         }
381 }
382
383 function provision_default_paths(subobj)
384 {
385         /* subobj.DNSDOMAIN isn't available at this point */
386         var dnsdomain = strlower(subobj.REALM);
387         var lp = loadparm_init();
388         var paths = new Object();
389         paths.smbconf = lp.filename()
390         paths.shareconf = lp.get("private dir") + "/" + "share.ldb";
391         paths.samdb = lp.get("sam database");
392         paths.idmapdb = lp.get("idmap database");
393         paths.secrets = lp.get("secrets database");
394         paths.templates = lp.get("private dir") + "/" + "templates.ldb";
395         paths.keytab = "secrets.keytab";
396         paths.dns_keytab = "dns.keytab";
397         paths.dns_keytab_abs = lp.get("private dir") + "/" + paths.dns_keytab;
398         paths.dns = lp.get("private dir") + "/" + dnsdomain + ".zone";
399         paths.named_conf = lp.get("private dir") + "/named.conf";
400         paths.winsdb = "wins.ldb";
401         paths.ldapdir = lp.get("private dir") + "/ldap";
402
403         paths.s4_ldapi_socket = lp.get("private dir") + "/ldapi";
404         paths.phpldapadminconfig = lp.get("private dir") + "/phpldapadmin-config.php";
405
406         paths.sysvol = lp.get("sysvol", "path");
407
408         if (paths.sysvol == undefined) {
409                 paths.sysvol = lp.get("lock dir") + "/sysvol";
410         }
411         
412         paths.netlogon = lp.get("netlogon", "path");
413         
414         if (paths.netlogon == undefined) {
415                 paths.netlogon = paths.sysvol + "/" + dnsdomain + "/scripts";
416         }
417
418         return paths;
419 }
420
421
422 /*
423   setup reasonable name mappings for sam names to unix names
424 */
425 function setup_name_mappings(info, ldb)
426 {
427         var lp = loadparm_init();
428         var attrs = new Array("objectSid");
429         var subobj = info.subobj;
430
431         res = ldb.search("objectSid=*", subobj.DOMAINDN, ldb.SCOPE_BASE, attrs);
432         assert(res.error == 0);
433         assert(res.msgs.length == 1 && res.msgs[0].objectSid != undefined);
434         var sid = res.msgs[0].objectSid;
435
436         /* add some foreign sids if they are not present already */
437         add_foreign(ldb, subobj, "S-1-5-7",  "Anonymous");
438         add_foreign(ldb, subobj, "S-1-1-0",  "World");
439         add_foreign(ldb, subobj, "S-1-5-2",  "Network");
440         add_foreign(ldb, subobj, "S-1-5-18", "System");
441         add_foreign(ldb, subobj, "S-1-5-11", "Authenticated Users");
442
443         /* some well known sids */
444         setup_name_mapping(info, ldb, "S-1-5-7",  subobj.NOBODY);
445         setup_name_mapping(info, ldb, "S-1-1-0",  subobj.NOGROUP);
446         setup_name_mapping(info, ldb, "S-1-5-2",  subobj.NOGROUP);
447         setup_name_mapping(info, ldb, "S-1-5-18", subobj.ROOT);
448         setup_name_mapping(info, ldb, "S-1-5-11", subobj.USERS);
449         setup_name_mapping(info, ldb, "S-1-5-32-544", subobj.WHEEL);
450         setup_name_mapping(info, ldb, "S-1-5-32-545", subobj.USERS);
451         setup_name_mapping(info, ldb, "S-1-5-32-546", subobj.NOGROUP);
452         setup_name_mapping(info, ldb, "S-1-5-32-551", subobj.BACKUP);
453
454         /* and some well known domain rids */
455         setup_name_mapping(info, ldb, sid + "-500", subobj.ROOT);
456         setup_name_mapping(info, ldb, sid + "-518", subobj.WHEEL);
457         setup_name_mapping(info, ldb, sid + "-519", subobj.WHEEL);
458         setup_name_mapping(info, ldb, sid + "-512", subobj.WHEEL);
459         setup_name_mapping(info, ldb, sid + "-513", subobj.USERS);
460         setup_name_mapping(info, ldb, sid + "-520", subobj.WHEEL);
461
462         return true;
463 }
464
465 function provision_fix_subobj(subobj, paths)
466 {
467         var ldb = ldb_init();
468         
469         subobj.REALM       = strupper(subobj.REALM);
470         subobj.HOSTNAME    = strlower(subobj.HOSTNAME);
471         subobj.DOMAIN      = strupper(subobj.DOMAIN);
472         subobj.NETBIOSNAME = strupper(subobj.HOSTNAME);
473         subobj.DNSDOMAIN    = strlower(subobj.REALM);
474         subobj.DNSNAME      = sprintf("%s.%s", 
475                                       strlower(subobj.HOSTNAME), 
476                                       subobj.DNSDOMAIN);
477         var rdn_list = split(".", subobj.DNSDOMAIN);
478         subobj.DOMAINDN     = "DC=" + join(",DC=", rdn_list);
479         subobj.ROOTDN       = subobj.DOMAINDN;
480         subobj.CONFIGDN     = "CN=Configuration," + subobj.ROOTDN;
481         subobj.SCHEMADN     = "CN=Schema," + subobj.CONFIGDN;
482
483         subobj.MACHINEPASS_B64 = ldb.encode(subobj.MACHINEPASS);
484         subobj.KRBTGTPASS_B64  = ldb.encode(subobj.KRBTGTPASS);
485         subobj.ADMINPASS_B64   = ldb.encode(subobj.ADMINPASS);
486         subobj.DNSPASS_B64     = ldb.encode(subobj.DNSPASS);
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         if (subobj.BACKEND_MOD == undefined) {
529                 subobj.BACKEND_MOD = "repl_meta_data";
530         }
531
532         info.subobj = subobj;
533         info.message = message;
534         info.session_info = session_info;
535
536         message("Setting up templates into " + paths.templates + "\n");
537         setup_ldb("provision_templates.ldif", info, paths.templates);
538
539         /* Also wipes the database */
540         message("Setting up " + paths.samdb + " partitions\n");
541         setup_ldb("provision_partitions.ldif", info, paths.samdb);
542
543         var samdb = open_ldb(info, paths.samdb, false);
544
545         message("Setting up " + paths.samdb + " attributes\n");
546         setup_add_ldif("provision_init.ldif", info, samdb, false);
547
548         message("Setting up " + paths.samdb + " rootDSE\n");
549         setup_add_ldif("provision_rootdse_add.ldif", info, samdb, false);
550
551         if (erase) {
552                 message("Erasing data from partitions\n");
553                 ldb_erase_partitions(info, samdb, undefined);
554         }
555
556         message("Setting up " + paths.samdb + " indexes\n");
557         setup_add_ldif("provision_index.ldif", info, samdb, false);
558
559         ok = samdb.transaction_commit();
560         assert(ok);
561
562         message("Setting up " + paths.secrets + "\n");
563         setup_ldb("secrets_init.ldif", info, paths.secrets);
564
565         setup_ldb("secrets.ldif", info, paths.secrets, false);
566
567         setup_ldb("secrets_dc.ldif", info, paths.secrets, false);
568
569         return true;
570 }
571
572 function load_schema(subobj, message, samdb)
573 {
574         var lp = loadparm_init();
575         var src = lp.get("setup directory") + "/" + "schema.ldif";
576
577         if (! sys.stat(src)) {
578                 message("Template file not found: %s\n",src);
579                 assert(0);
580         }
581
582         var schema_data = sys.file_load(src);
583
584         src = lp.get("setup directory") + "/" + "schema_samba4.ldif";
585
586         if (! sys.stat(src)) {
587                 message("Template file not found: %s\n",src);
588                 assert(0);
589         }
590
591         schema_data = schema_data + sys.file_load(src);
592
593         schema_data = substitute_var(schema_data, subobj);
594
595         src = lp.get("setup directory") + "/" + "provision_schema_basedn_modify.ldif";
596
597         if (! sys.stat(src)) {
598                 message("Template file not found: %s\n",src);
599                 assert(0);
600         }
601
602         var head_data = sys.file_load(src);
603         head_data = substitute_var(head_data, subobj);
604
605         var ok = samdb.attach_dsdb_schema_from_ldif(head_data, schema_data);
606         return ok;
607 }
608
609
610 /*
611   provision samba4 - caution, this wipes all existing data!
612 */
613 function provision(subobj, message, blank, paths, session_info, credentials, ldapbackend)
614 {
615         var lp = loadparm_init();
616         var sys = sys_init();
617         var info = new Object();
618         random_init(local);
619
620         var ok = provision_fix_subobj(subobj, paths);
621         assert(ok);
622
623         if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
624                 if (subobj.BACKEND_MOD == undefined) {
625                         subobj.BACKEND_MOD = "repl_meta_data";
626                 }
627         } else {
628                 if (subobj.BACKEND_MOD == undefined) {
629                         subobj.BACKEND_MOD = "objectguid";
630                 }
631         }
632
633         if (subobj.DOMAINGUID != undefined) {
634                 subobj.DOMAINGUID_MOD = sprintf("replace: objectGUID\nobjectGUID: %s\n-", subobj.DOMAINGUID);
635         } else {
636                 subobj.DOMAINGUID_MOD = "";
637         }
638
639         if (subobj.HOSTGUID != undefined) {
640                 subobj.HOSTGUID_ADD = sprintf("objectGUID: %s", subobj.HOSTGUID);
641         } else {
642                 subobj.HOSTGUID_ADD = "";
643         }
644
645         info.subobj = subobj;
646         info.message = message;
647         info.credentials = credentials;
648         info.session_info = session_info;
649
650         /* only install a new smb.conf if there isn't one there already */
651         var st = sys.stat(paths.smbconf);
652         if (st == undefined) {
653                 var smbconfsuffix;
654                 if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
655                         smbconfsuffix = "dc";
656                 } else if (strlower(subobj.SERVERROLE) == strlower("member server")) {
657                         smbconfsuffix = "member";
658                 } else {
659                         smbconfsuffix = subobj.SERVERROLE;
660                 }
661                 message("Setting up " + paths.smbconf +"\n");
662                 setup_file("provision.smb.conf." + smbconfsuffix, info.message, paths.smbconf, subobj);
663                 lp.reload();
664         }
665         /* only install a new shares config db if there is none */
666         st = sys.stat(paths.shareconf);
667         if (st == undefined) {
668                 message("Setting up share.ldb\n");
669                 setup_ldb("share.ldif", info, paths.shareconf);
670         }
671
672         message("Setting up " + paths.secrets + "\n");
673         setup_ldb("secrets_init.ldif", info, paths.secrets);
674         setup_ldb("secrets.ldif", info, paths.secrets, false);
675
676         message("Setting up the registry\n");
677         var reg = reg_open();
678         reg.apply_patchfile(lp.get("setup directory") + "/provision.reg")
679
680         message("Setting up templates into " + paths.templates + "\n");
681         setup_ldb("provision_templates.ldif", info, paths.templates);
682
683         message("Setting up " + paths.idmapdb +"\n");
684         setup_ldb("idmap_init.ldif", info, paths.idmapdb);
685
686         message("Setting up sam.ldb partitions\n");
687         /* Also wipes the database */
688         setup_ldb("provision_partitions.ldif", info, paths.samdb);
689
690         var samdb = open_ldb(info, paths.samdb, false);
691
692         message("Setting up sam.ldb attributes\n");
693         setup_add_ldif("provision_init.ldif", info, samdb, false);
694
695         message("Setting up sam.ldb rootDSE\n");
696         setup_add_ldif("provision_rootdse_add.ldif", info, samdb, false);
697
698         message("Erasing data from partitions\n");
699         ldb_erase_partitions(info, samdb, ldapbackend);
700         
701         // (hack) Reload, now we have the partitions and rootdse loaded.  
702         var commit_ok = samdb.transaction_commit();
703         if (!commit_ok) {
704                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
705                 assert(commit_ok);
706         }
707         samdb.close();
708
709         message("Pre-loading the Samba4 and AD schema\n");
710         
711         samdb = open_ldb(info, paths.samdb, false);
712
713         samdb.set_domain_sid(subobj.DOMAINSID);
714
715         if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
716                 if (subobj.INVOCATIONID == undefined) {
717                         subobj.INVOCATIONID = randguid();
718                 }
719                 samdb.set_ntds_invocationId(subobj.INVOCATIONID);
720                 if (subobj.BACKEND_MOD == undefined) {
721                         subobj.BACKEND_MOD = "repl_meta_data";
722                 }
723         } else {
724                 if (subobj.BACKEND_MOD == undefined) {
725                         subobj.BACKEND_MOD = "objectguid";
726                 }
727         }
728
729         var load_schema_ok = load_schema(subobj, message, samdb);
730         assert(load_schema_ok.is_ok);
731
732         message("Adding DomainDN: " + subobj.DOMAINDN + " (permitted to fail)\n");
733         var add_ok = setup_add_ldif("provision_basedn.ldif", info, samdb, true);
734         message("Modifying DomainDN: " + subobj.DOMAINDN + "\n");
735         var modify_basedn_ok = setup_ldb_modify("provision_basedn_modify.ldif", info, samdb);
736         if (!modify_basedn_ok) {
737                 if (!add_ok) {
738                         message("%s", "Failed to both add and modify " + subobj.DOMAINDN + " in target " + subobj.DOMAINDN_LDB + ": " + samdb.errstring() + "\n");
739                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
740                 };
741                 assert(modify_basedn_ok);
742         };
743
744         message("Adding configuration container (permitted to fail)\n");
745         var add_config_ok = setup_add_ldif("provision_configuration_basedn.ldif", info, samdb, true);
746         message("Modifying configuration container\n");
747         var modify_config_ok = setup_ldb_modify("provision_configuration_basedn_modify.ldif", info, samdb);
748         if (!modify_config_ok) {
749                 if (!add_config_ok) {
750                         message("%s", "Failed to both add and modify " + subobj.CONFIGDN + " in target " + subobj.CONFIGDN_LDB + ": " + samdb.errstring() + "\n");
751                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
752                 }
753                 assert(modify_config_ok);
754         }
755
756         message("Adding schema container (permitted to fail)\n");
757         var add_schema_ok = setup_add_ldif("provision_schema_basedn.ldif", info, samdb, true);
758         message("Modifying schema container\n");
759         var modify_schema_ok = setup_ldb_modify("provision_schema_basedn_modify.ldif", info, samdb);
760         if (!modify_schema_ok) {
761                 if (!add_schema_ok) {
762                         message("%s", "Failed to both add and modify " + subobj.SCHEMADN + " in target " + subobj.SCHEMADN_LDB + ": " + samdb.errstring() + "\n");
763                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
764                 }
765                 message("Failed to modify the schema container: " + samdb.errstring() + "\n");
766                 assert(modify_schema_ok);
767         }
768
769         message("Setting up sam.ldb Samba4 schema\n");
770         setup_add_ldif("schema_samba4.ldif", info, samdb, false);
771         message("Setting up sam.ldb AD schema\n");
772         setup_add_ldif("schema.ldif", info, samdb, false);
773
774         message("Setting up sam.ldb configuration data\n");
775         setup_add_ldif("provision_configuration.ldif", info, samdb, false);
776
777         message("Setting up display specifiers\n");
778         setup_add_ldif("display_specifiers.ldif", info, samdb, false);
779
780         message("Adding users container (permitted to fail)\n");
781         var add_users_ok = setup_add_ldif("provision_users_add.ldif", info, samdb, true);
782         message("Modifying users container\n");
783         var modify_users_ok = setup_ldb_modify("provision_users_modify.ldif", info, samdb);
784         if (!modify_users_ok) {
785                 if (!add_users_ok) {
786                         message("Failed to both add and modify the users container\n");
787                 }
788                 assert(modify_users_ok);
789         }
790         message("Adding computers container (permitted to fail)\n");
791         var add_computers_ok = setup_add_ldif("provision_computers_add.ldif", info, samdb, true);
792         message("Modifying computers container\n");
793         var modify_computers_ok = setup_ldb_modify("provision_computers_modify.ldif", info, samdb);
794         if (!modify_computers_ok) {
795                 if (!add_computers_ok) {
796                         message("Failed to both add and modify the computers container\n");
797                 }
798                 assert(modify_computers_ok);
799         }
800
801         message("Setting up sam.ldb data\n");
802         setup_add_ldif("provision.ldif", info, samdb, false);
803
804         if (blank != false) {
805                 message("Setting up sam.ldb index\n");
806                 setup_add_ldif("provision_index.ldif", info, samdb, false);
807
808                 message("Setting up sam.ldb rootDSE marking as syncronized\n");
809                 setup_modify_ldif("provision_rootdse_modify.ldif", info, samdb, false);
810
811                 var commit_ok = samdb.transaction_commit();
812                 if (!commit_ok) {
813                         info.message("ldb commit failed: " + samdb.errstring() + "\n");
814                         assert(commit_ok);
815                 }
816                 return true;
817         }
818
819 //      message("Activate schema module");
820 //      setup_modify_ldif("schema_activation.ldif", info, samdb, false);
821 //
822 //      // (hack) Reload, now we have the schema loaded.  
823 //      var commit_ok = samdb.transaction_commit();
824 //      if (!commit_ok) {
825 //              info.message("samdb commit failed: " + samdb.errstring() + "\n");
826 //              assert(commit_ok);
827 //      }
828 //      samdb.close();
829 //
830 //      samdb = open_ldb(info, paths.samdb, false);
831 //
832         message("Setting up sam.ldb users and groups\n");
833         setup_add_ldif("provision_users.ldif", info, samdb, false);
834
835         if (strlower(subobj.SERVERROLE) == strlower("domain controller")) {
836                 message("Setting up self join\n");
837                 setup_add_ldif("provision_self_join.ldif", info, samdb, false);
838                 setup_add_ldif("provision_group_policy.ldif", info, samdb, false);
839
840                 sys.mkdir(paths.sysvol, 0755);
841                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN, 0755);
842                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies", 0755);
843                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}", 0755);
844                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}/Machine", 0755);
845                 sys.mkdir(paths.sysvol + "/"+ subobj.DNSDOMAIN + "/Policies/{" + subobj.POLICYGUID + "}/User", 0755);
846
847                 sys.mkdir(paths.netlogon, 0755);
848
849                 setup_ldb("secrets_dc.ldif", info, paths.secrets, false);
850
851         }
852
853         if (setup_name_mappings(info, samdb) == false) {
854                 return false;
855         }
856
857         message("Setting up sam.ldb index\n");
858         setup_add_ldif("provision_index.ldif", info, samdb, false);
859
860         message("Setting up sam.ldb rootDSE marking as syncronized\n");
861         setup_modify_ldif("provision_rootdse_modify.ldif", info, samdb, false);
862
863         var commit_ok = samdb.transaction_commit();
864         if (!commit_ok) {
865                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
866                 assert(commit_ok);
867         }
868
869         message("Setting up phpLDAPadmin configuration\n");
870         setup_file("phpldapadmin-config.php", info.message, paths.phpldapadminconfig, subobj);
871         message("Please install the phpLDAPadmin configuration located at " + paths.phpldapadminconfig + " into /etc/phpldapadmin/config.php\n");
872
873         return true;
874 }
875
876 /*
877   provision just the schema into a temporary ldb, so we can run ad2oLschema on it
878 */
879 function provision_schema(subobj, message, tmp_schema_path, paths)
880 {
881         var lp = loadparm_init();
882         var sys = sys_init();
883         var info = new Object();
884
885         var ok = provision_fix_subobj(subobj, paths);
886         assert(ok);
887
888         info.subobj = subobj;
889         info.message = message;
890
891         message("Setting up sam.ldb partitions\n");
892
893         /* This will erase anything in the tmp db */
894         var samdb = open_ldb(info, tmp_schema_path, true);
895
896         message("Setting up sam.ldb attributes\n");
897         setup_add_ldif("provision_init.ldif", info, samdb, false);
898
899         message("Setting up sam.ldb rootDSE\n");
900         setup_add_ldif("provision_rootdse_add.ldif", info, samdb, false);
901
902         message("Adding schema container (permitted to fail)\n");
903         var add_ok = setup_add_ldif("provision_schema_basedn.ldif", info, samdb, true);
904         message("Modifying schema container\n");
905         var modify_ok = setup_ldb_modify("provision_schema_basedn_modify.ldif", info, samdb);
906         if (!modify_ok) {
907                 if (!add_ok) {
908                         message("Failed to both add and modify schema dn: " + samdb.errstring() + "\n");
909                         message("Perhaps you need to run the provision script with the --ldap-base-dn option, and add this record to the backend manually\n"); 
910                         assert(modify_ok);
911                 }
912                 message("Failed to modify the schema container: " + samdb.errstring() + "\n");
913                 assert(modify_ok);
914         }
915
916         message("Setting up sam.ldb Samba4 schema\n");
917         setup_add_ldif("schema_samba4.ldif", info, samdb, false);
918         message("Setting up sam.ldb AD schema\n");
919         setup_add_ldif("schema.ldif", info, samdb, false);
920
921         var commit_ok = samdb.transaction_commit();
922         if (!commit_ok) {
923                 info.message("samdb commit failed: " + samdb.errstring() + "\n");
924                 assert(commit_ok);
925         }
926         samdb.close();
927 }
928
929 /* Write out a DNS zone file, from the info in the current database */
930 function provision_dns(subobj, message, paths, session_info, credentials)
931 {
932         var lp = loadparm_init();
933         if (strlower(subobj.SERVERROLE) != strlower("domain controller")) {
934                 message("No DNS zone required for role %s\n", subobj.SERVERROLE);
935                 return;
936         }
937         message("Setting up DNS zone: " + subobj.DNSDOMAIN + " \n");
938         var ldb = ldb_init();
939         ldb.session_info = session_info;
940         ldb.credentials = credentials;
941
942         /* connect to the sam */
943         var ok = ldb.connect(paths.samdb);
944         assert(ok);
945
946         /* These values may have changed, due to an incoming SamSync,
947            or may not have been specified, so fetch them from the database */
948
949         var attrs = new Array("objectGUID");
950         res = ldb.search("objectGUID=*", subobj.DOMAINDN, ldb.SCOPE_BASE, attrs);
951         assert(res.error == 0);
952         assert(res.msgs.length == 1);
953         assert(res.msgs[0].objectGUID != undefined);
954         subobj.DOMAINGUID = res.msgs[0].objectGUID;
955
956         subobj.HOSTGUID = searchone(ldb, subobj.DOMAINDN, "(&(objectClass=computer)(cn=" + subobj.NETBIOSNAME + "))", "objectGUID");
957         assert(subobj.HOSTGUID != undefined);
958
959         setup_file("provision.zone", 
960                    message, paths.dns, 
961                    subobj);
962
963         setup_file("named.conf", 
964                    message, paths.named_conf, 
965                    subobj);
966
967         message("Please install the zone located in " + paths.dns + " into your DNS server.  A sample BIND configuration snippit is at " + paths.named_conf + "\n");
968 }
969
970
971 /*
972   guess reasonably default options for provisioning
973 */
974 function provision_guess()
975 {
976         var subobj = new Object();
977         var nss = nss_init();
978         var lp = loadparm_init();
979         var rdn_list;
980         random_init(local);
981
982         subobj.SERVERROLE   = strlower(lp.get("server role"));
983         subobj.REALM        = strupper(lp.get("realm"));
984         subobj.DOMAIN       = lp.get("workgroup");
985         subobj.HOSTNAME     = hostname();
986
987         assert(subobj.REALM);
988         assert(subobj.DOMAIN);
989         assert(subobj.HOSTNAME);
990         
991         subobj.VERSION      = version();
992         subobj.HOSTIP       = hostip();
993         subobj.DOMAINSID    = randsid();
994         subobj.POLICYGUID   = randguid();
995         subobj.KRBTGTPASS   = randpass(12);
996         subobj.MACHINEPASS  = randpass(12);
997         subobj.DNSPASS  = randpass(12);
998         subobj.ADMINPASS    = randpass(12);
999         subobj.LDAPMANAGERPASS     = randpass(12);
1000         subobj.DEFAULTSITE  = "Default-First-Site-Name";
1001         subobj.DATESTRING   = datestring;
1002         subobj.ROOT         = findnss(nss.getpwnam, "root");
1003         subobj.NOBODY       = findnss(nss.getpwnam, "nobody");
1004         subobj.NOGROUP      = findnss(nss.getgrnam, "nogroup", "nobody");
1005         subobj.WHEEL        = findnss(nss.getgrnam, "wheel", "root", "staff", "adm");
1006         subobj.BACKUP       = findnss(nss.getgrnam, "backup", "wheel", "root", "staff");
1007         subobj.USERS        = findnss(nss.getgrnam, "users", "guest", "other", "unknown", "usr");
1008
1009         //Add modules to the list to activate them by default
1010         //beware often order is important
1011         //
1012         // Some Known ordering constraints:
1013         // - rootdse must be first, as it makes redirects from "" -> cn=rootdse
1014         // - objectclass must be before password_hash, because password_hash checks
1015         //   that the objectclass is of type person (filled in by the objectclass 
1016         //   module when expanding the objectclass list)
1017         // - partition must be last
1018         // - each partition has its own module list then
1019         var modules_list     = new Array("rootdse",
1020                                          "paged_results",
1021                                          "ranged_results",
1022                                          "anr",
1023                                          "server_sort",
1024                                          "extended_dn",
1025                                          "asq",
1026                                          "samldb",
1027                                          "rdn_name",
1028                                          "objectclass",
1029                                          "kludge_acl",
1030                                          "operational");
1031         var tdb_modules_list = new Array("subtree_rename",
1032                                          "subtree_delete",
1033                                          "linked_attributes");
1034         var modules_list2    = new Array("show_deleted",
1035                                          "partition");
1036         subobj.MODULES_LIST = join(",", modules_list);
1037         subobj.TDB_MODULES_LIST = "," + join(",", tdb_modules_list);
1038         subobj.MODULES_LIST2 = join(",", modules_list2);
1039         subobj.DOMAINDN_LDB = "users.ldb";
1040         subobj.CONFIGDN_LDB = "configuration.ldb";
1041         subobj.SCHEMADN_LDB = "schema.ldb";
1042         subobj.DOMAINDN_MOD = "pdc_fsmo,password_hash,instancetype";
1043         subobj.CONFIGDN_MOD = "naming_fsmo,instancetype";
1044         subobj.SCHEMADN_MOD = "schema_fsmo,instancetype";
1045
1046         subobj.ACI              = "# no aci for local ldb";
1047
1048         return subobj;
1049 }
1050
1051 /*
1052   search for one attribute as a string
1053  */
1054 function searchone(ldb, basedn, expression, attribute)
1055 {
1056         var attrs = new Array(attribute);
1057         res = ldb.search(expression, basedn, ldb.SCOPE_SUBTREE, attrs);
1058         if (res.error != 0 ||
1059             res.msgs.length != 1 ||
1060             res.msgs[0][attribute] == undefined) {
1061                 return undefined;
1062         }
1063         return res.msgs[0][attribute];
1064 }
1065
1066 /*
1067   modify an account to remove the 
1068 */
1069 function enable_account(ldb, user_dn)
1070 {
1071         var attrs = new Array("userAccountControl");
1072         var res = ldb.search(NULL, user_dn, ldb.SCOPE_ONELEVEL, attrs);
1073         assert(res.error == 0);
1074         assert(res.msgs.length == 1);
1075         var userAccountControl = res.msgs[0].userAccountControl;
1076         userAccountControl = userAccountControl - 2; /* remove disabled bit */
1077         var mod = sprintf("
1078 dn: %s
1079 changetype: modify
1080 replace: userAccountControl
1081 userAccountControl: %u
1082 ", 
1083                           user_dn, userAccountControl);
1084         var ok = ldb.modify(mod);
1085         return (ok.error == 0); 
1086 }
1087
1088
1089 /*
1090   add a new user record
1091 */
1092 function newuser(username, unixname, password, message, session_info, credentials)
1093 {
1094         var lp = loadparm_init();
1095         var samdb = lp.get("sam database");
1096         var ldb = ldb_init();
1097         random_init(local);
1098         ldb.session_info = session_info;
1099         ldb.credentials = credentials;
1100
1101         /* connect to the sam */
1102         var ok = ldb.connect(samdb);
1103         assert(ok);
1104
1105         ldb.transaction_start();
1106
1107         /* find the DNs for the domain and the domain users group */
1108         var attrs = new Array("defaultNamingContext");
1109         res = ldb.search("defaultNamingContext=*", "", ldb.SCOPE_BASE, attrs);
1110         assert(res.error == 0);
1111         assert(res.msgs.length == 1 && res.msgs[0].defaultNamingContext != undefined);
1112         var domain_dn = res.msgs[0].defaultNamingContext;
1113         assert(domain_dn != undefined);
1114         var dom_users = searchone(ldb, domain_dn, "name=Domain Users", "dn");
1115         assert(dom_users != undefined);
1116
1117         var user_dn = sprintf("CN=%s,CN=Users,%s", username, domain_dn);
1118
1119
1120         /*
1121           the new user record. note the reliance on the samdb module to fill
1122           in a sid, guid etc
1123         */
1124         var ldif = sprintf("
1125 dn: %s
1126 sAMAccountName: %s
1127 unixName: %s
1128 sambaPassword: %s
1129 objectClass: user
1130 ",
1131                            user_dn, username,
1132                            unixname, password);
1133         /*
1134           add the user to the users group as well
1135         */
1136         var modgroup = sprintf("
1137 dn: %s
1138 changetype: modify
1139 add: member
1140 member: %s
1141 ",
1142                                dom_users, user_dn);
1143
1144
1145         /*
1146           now the real work
1147         */
1148         message("Adding user %s\n", user_dn);
1149         ok = ldb.add(ldif);
1150         if (ok.error != 0) {
1151                 message("Failed to add %s - %s\n", user_dn, ok.errstr);
1152                 return false;
1153         }
1154
1155         message("Modifying group %s\n", dom_users);
1156         ok = ldb.modify(modgroup);
1157         if (ok.error != 0) {
1158                 message("Failed to modify %s - %s\n", dom_users, ok.errstr);
1159                 return false;
1160         }
1161
1162         /*
1163           modify the userAccountControl to remove the disabled bit
1164         */
1165         ok = enable_account(ldb, user_dn);
1166         if (ok) {
1167                 ldb.transaction_commit();
1168         }
1169         return ok;
1170 }
1171
1172 // Check whether a name is valid as a NetBIOS name. 
1173 // FIXME: There are probably more constraints here. 
1174 // crh has a paragraph on this in his book (1.4.1.1)
1175 function valid_netbios_name(name)
1176 {
1177         if (strlen(name) > 15) return false;
1178         return true;
1179 }
1180
1181 function provision_validate(subobj, message)
1182 {
1183         var lp = loadparm_init();
1184
1185         if (!valid_netbios_name(subobj.DOMAIN)) {
1186                 message("Invalid NetBIOS name for domain\n");
1187                 return false;
1188         }
1189
1190         if (!valid_netbios_name(subobj.NETBIOSNAME)) {
1191                 message("Invalid NetBIOS name for host\n");
1192                 return false;
1193         }
1194
1195
1196         if (strupper(lp.get("workgroup")) != strupper(subobj.DOMAIN_CONF)) {
1197                 message("workgroup '%s' in smb.conf must match chosen domain '%s'\n",
1198                         lp.get("workgroup"), subobj.DOMAIN_CONF);
1199                 return false;
1200         }
1201
1202         if (strupper(lp.get("realm")) != strupper(subobj.REALM_CONF)) {
1203                 message("realm '%s' in smb.conf must match chosen realm '%s'\n",
1204                         lp.get("realm"), subobj.REALM_CONF);
1205                 return false;
1206         }
1207
1208         if (strlower(lp.get("server role")) != strlower(subobj.SERVERROLE)) {
1209                 message("server role '%s' in smb.conf must match chosen role '%s'\n",
1210                         lp.get("server role"), subobj.SERVERROLE);
1211                 return false;
1212         }
1213
1214         return true;
1215 }
1216
1217 function join_domain(domain, netbios_name, join_type, creds, message) 
1218 {
1219         var ctx = NetContext(creds);
1220         var joindom = new Object();
1221         joindom.domain = domain;
1222         joindom.join_type = join_type;
1223         joindom.netbios_name = netbios_name;
1224         if (!ctx.JoinDomain(joindom)) {
1225                 message("Domain Join failed: " + joindom.error_string);
1226                 return false;
1227         }
1228         return true;
1229 }
1230
1231 /* Vampire a remote domain.  Session info and credentials are required for for
1232  * access to our local database (might be remote ldap)
1233  */ 
1234
1235 function vampire(domain, session_info, credentials, message) {
1236         var ctx = NetContext(credentials);
1237         var vampire_ctx = new Object();
1238         var machine_creds = credentials_init();
1239         machine_creds.set_domain(form.DOMAIN);
1240         if (!machine_creds.set_machine_account()) {
1241                 message("Failed to access domain join information!");
1242                 return false;
1243         }
1244         vampire_ctx.machine_creds = machine_creds;
1245         vampire_ctx.session_info = session_info;
1246         if (!ctx.SamSyncLdb(vampire_ctx)) {
1247                 message("Migration of remote domain to Samba failed: " + vampire_ctx.error_string);
1248                 return false;
1249         }
1250
1251         return true;
1252 }
1253
1254 return 0;