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