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