s4-dsdb: Explain better what records are written during schema set
[Samba.git] / source4 / scripting / python / samba / provision / __init__.py
blob6834d40eb48000eb1e5df9f29899152cb28298e1
2 # Unix SMB/CIFS implementation.
3 # backend code for provisioning a Samba4 server
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2012
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008-2009
7 # Copyright (C) Oliver Liebel <oliver@itc.li> 2008-2009
9 # Based on the original in EJS:
10 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 """Functions for setting up a Samba configuration."""
28 __docformat__ = "restructuredText"
30 from base64 import b64encode
31 import os
32 import re
33 import pwd
34 import grp
35 import logging
36 import time
37 import uuid
38 import socket
39 import urllib
40 import string
41 import tempfile
43 import ldb
45 from samba.auth import system_session, admin_session
46 import samba
47 from samba.samba3 import smbd
48 from samba.dsdb import DS_DOMAIN_FUNCTION_2000
49 from samba import (
50 Ldb,
51 MAX_NETBIOS_NAME_LEN,
52 check_all_substituted,
53 is_valid_netbios_char,
54 setup_file,
55 substitute_var,
56 valid_netbios_name,
57 version,
59 from samba.dcerpc import security, misc
60 from samba.dcerpc.misc import (
61 SEC_CHAN_BDC,
62 SEC_CHAN_WKSTA,
64 from samba.dsdb import (
65 DS_DOMAIN_FUNCTION_2003,
66 DS_DOMAIN_FUNCTION_2008_R2,
67 ENC_ALL_TYPES,
69 from samba.idmap import IDmapDB
70 from samba.ms_display_specifiers import read_ms_ldif
71 from samba.ntacls import setntacl, dsacl2fsacl
72 from samba.ndr import ndr_pack, ndr_unpack
73 from samba.provision.backend import (
74 ExistingBackend,
75 FDSBackend,
76 LDBBackend,
77 OpenLDAPBackend,
79 from samba.provision.descriptor import (
80 get_config_descriptor,
81 get_domain_descriptor
83 from samba.provision.common import (
84 setup_path,
85 setup_add_ldif,
86 setup_modify_ldif,
88 from samba.provision.sambadns import (
89 setup_ad_dns,
90 create_dns_update_list
93 import samba.param
94 import samba.registry
95 from samba.schema import Schema
96 from samba.samdb import SamDB
97 from samba.dbchecker import dbcheck
100 DEFAULT_POLICY_GUID = "31B2F340-016D-11D2-945F-00C04FB984F9"
101 DEFAULT_DC_POLICY_GUID = "6AC1786C-016F-11D2-945F-00C04fB984F9"
102 DEFAULTSITE = "Default-First-Site-Name"
103 LAST_PROVISION_USN_ATTRIBUTE = "lastProvisionUSN"
106 class ProvisionPaths(object):
108 def __init__(self):
109 self.shareconf = None
110 self.hklm = None
111 self.hkcu = None
112 self.hkcr = None
113 self.hku = None
114 self.hkpd = None
115 self.hkpt = None
116 self.samdb = None
117 self.idmapdb = None
118 self.secrets = None
119 self.keytab = None
120 self.dns_keytab = None
121 self.dns = None
122 self.winsdb = None
123 self.private_dir = None
124 self.state_dir = None
125 self.phpldapadminconfig = None
128 class ProvisionNames(object):
130 def __init__(self):
131 self.rootdn = None
132 self.domaindn = None
133 self.configdn = None
134 self.schemadn = None
135 self.ldapmanagerdn = None
136 self.dnsdomain = None
137 self.realm = None
138 self.netbiosname = None
139 self.domain = None
140 self.hostname = None
141 self.sitename = None
142 self.smbconf = None
144 def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf, lp):
145 """Get key provision parameters (realm, domain, ...) from a given provision
147 :param samdb: An LDB object connected to the sam.ldb file
148 :param secretsdb: An LDB object connected to the secrets.ldb file
149 :param idmapdb: An LDB object connected to the idmap.ldb file
150 :param paths: A list of path to provision object
151 :param smbconf: Path to the smb.conf file
152 :param lp: A LoadParm object
153 :return: A list of key provision parameters
155 names = ProvisionNames()
156 names.adminpass = None
158 # NT domain, kerberos realm, root dn, domain dn, domain dns name
159 names.domain = string.upper(lp.get("workgroup"))
160 names.realm = lp.get("realm")
161 names.dnsdomain = names.realm.lower()
162 basedn = samba.dn_from_dns_name(names.dnsdomain)
163 names.realm = string.upper(names.realm)
164 # netbiosname
165 # Get the netbiosname first (could be obtained from smb.conf in theory)
166 res = secretsdb.search(expression="(flatname=%s)" %
167 names.domain,base="CN=Primary Domains",
168 scope=ldb.SCOPE_SUBTREE, attrs=["sAMAccountName"])
169 names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
171 names.smbconf = smbconf
173 # That's a bit simplistic but it's ok as long as we have only 3
174 # partitions
175 current = samdb.search(expression="(objectClass=*)",
176 base="", scope=ldb.SCOPE_BASE,
177 attrs=["defaultNamingContext", "schemaNamingContext",
178 "configurationNamingContext","rootDomainNamingContext"])
180 names.configdn = current[0]["configurationNamingContext"]
181 configdn = str(names.configdn)
182 names.schemadn = current[0]["schemaNamingContext"]
183 if not (ldb.Dn(samdb, basedn) == (ldb.Dn(samdb,
184 current[0]["defaultNamingContext"][0]))):
185 raise ProvisioningError(("basedn in %s (%s) and from %s (%s)"
186 "is not the same ..." % (paths.samdb,
187 str(current[0]["defaultNamingContext"][0]),
188 paths.smbconf, basedn)))
190 names.domaindn=current[0]["defaultNamingContext"]
191 names.rootdn=current[0]["rootDomainNamingContext"]
192 # default site name
193 res3 = samdb.search(expression="(objectClass=site)",
194 base="CN=Sites," + configdn, scope=ldb.SCOPE_ONELEVEL, attrs=["cn"])
195 names.sitename = str(res3[0]["cn"])
197 # dns hostname and server dn
198 res4 = samdb.search(expression="(CN=%s)" % names.netbiosname,
199 base="OU=Domain Controllers,%s" % basedn,
200 scope=ldb.SCOPE_ONELEVEL, attrs=["dNSHostName"])
201 names.hostname = str(res4[0]["dNSHostName"]).replace("." + names.dnsdomain,"")
203 server_res = samdb.search(expression="serverReference=%s" % res4[0].dn,
204 attrs=[], base=configdn)
205 names.serverdn = server_res[0].dn
207 # invocation id/objectguid
208 res5 = samdb.search(expression="(objectClass=*)",
209 base="CN=NTDS Settings,%s" % str(names.serverdn), scope=ldb.SCOPE_BASE,
210 attrs=["invocationID", "objectGUID"])
211 names.invocation = str(ndr_unpack(misc.GUID, res5[0]["invocationId"][0]))
212 names.ntdsguid = str(ndr_unpack(misc.GUID, res5[0]["objectGUID"][0]))
214 # domain guid/sid
215 res6 = samdb.search(expression="(objectClass=*)", base=basedn,
216 scope=ldb.SCOPE_BASE, attrs=["objectGUID",
217 "objectSid","msDS-Behavior-Version" ])
218 names.domainguid = str(ndr_unpack(misc.GUID, res6[0]["objectGUID"][0]))
219 names.domainsid = ndr_unpack( security.dom_sid, res6[0]["objectSid"][0])
220 if res6[0].get("msDS-Behavior-Version") is None or \
221 int(res6[0]["msDS-Behavior-Version"][0]) < DS_DOMAIN_FUNCTION_2000:
222 names.domainlevel = DS_DOMAIN_FUNCTION_2000
223 else:
224 names.domainlevel = int(res6[0]["msDS-Behavior-Version"][0])
226 # policy guid
227 res7 = samdb.search(expression="(displayName=Default Domain Policy)",
228 base="CN=Policies,CN=System," + basedn,
229 scope=ldb.SCOPE_ONELEVEL, attrs=["cn","displayName"])
230 names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
231 # dc policy guid
232 res8 = samdb.search(expression="(displayName=Default Domain Controllers"
233 " Policy)",
234 base="CN=Policies,CN=System," + basedn,
235 scope=ldb.SCOPE_ONELEVEL, attrs=["cn","displayName"])
236 if len(res8) == 1:
237 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
238 else:
239 names.policyid_dc = None
240 res9 = idmapdb.search(expression="(cn=%s)" %
241 (security.SID_BUILTIN_ADMINISTRATORS),
242 attrs=["xidNumber"])
243 if len(res9) == 1:
244 names.wheel_gid = res9[0]["xidNumber"]
245 else:
246 raise ProvisioningError("Unable to find uid/gid for Domain Admins rid")
247 return names
250 def update_provision_usn(samdb, low, high, id, replace=False):
251 """Update the field provisionUSN in sam.ldb
253 This field is used to track range of USN modified by provision and
254 upgradeprovision.
255 This value is used afterward by next provision to figure out if
256 the field have been modified since last provision.
258 :param samdb: An LDB object connect to sam.ldb
259 :param low: The lowest USN modified by this upgrade
260 :param high: The highest USN modified by this upgrade
261 :param id: The invocation id of the samba's dc
262 :param replace: A boolean indicating if the range should replace any
263 existing one or appended (default)
266 tab = []
267 if not replace:
268 entry = samdb.search(base="@PROVISION",
269 scope=ldb.SCOPE_BASE,
270 attrs=[LAST_PROVISION_USN_ATTRIBUTE, "dn"])
271 for e in entry[0][LAST_PROVISION_USN_ATTRIBUTE]:
272 if not re.search(';', e):
273 e = "%s;%s" % (e, id)
274 tab.append(str(e))
276 tab.append("%s-%s;%s" % (low, high, id))
277 delta = ldb.Message()
278 delta.dn = ldb.Dn(samdb, "@PROVISION")
279 delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab,
280 ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE)
281 entry = samdb.search(expression='provisionnerID=*',
282 base="@PROVISION", scope=ldb.SCOPE_BASE,
283 attrs=["provisionnerID"])
284 if len(entry) == 0 or len(entry[0]) == 0:
285 delta["provisionnerID"] = ldb.MessageElement(id, ldb.FLAG_MOD_ADD, "provisionnerID")
286 samdb.modify(delta)
289 def set_provision_usn(samdb, low, high, id):
290 """Set the field provisionUSN in sam.ldb
291 This field is used to track range of USN modified by provision and
292 upgradeprovision.
293 This value is used afterward by next provision to figure out if
294 the field have been modified since last provision.
296 :param samdb: An LDB object connect to sam.ldb
297 :param low: The lowest USN modified by this upgrade
298 :param high: The highest USN modified by this upgrade
299 :param id: The invocationId of the provision"""
301 tab = []
302 tab.append("%s-%s;%s" % (low, high, id))
304 delta = ldb.Message()
305 delta.dn = ldb.Dn(samdb, "@PROVISION")
306 delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab,
307 ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE)
308 samdb.add(delta)
311 def get_max_usn(samdb,basedn):
312 """ This function return the biggest USN present in the provision
314 :param samdb: A LDB object pointing to the sam.ldb
315 :param basedn: A string containing the base DN of the provision
316 (ie. DC=foo, DC=bar)
317 :return: The biggest USN in the provision"""
319 res = samdb.search(expression="objectClass=*",base=basedn,
320 scope=ldb.SCOPE_SUBTREE,attrs=["uSNChanged"],
321 controls=["search_options:1:2",
322 "server_sort:1:1:uSNChanged",
323 "paged_results:1:1"])
324 return res[0]["uSNChanged"]
327 def get_last_provision_usn(sam):
328 """Get USNs ranges modified by a provision or an upgradeprovision
330 :param sam: An LDB object pointing to the sam.ldb
331 :return: a dictionnary which keys are invocation id and values are an array
332 of integer representing the different ranges
334 try:
335 entry = sam.search(expression="%s=*" % LAST_PROVISION_USN_ATTRIBUTE,
336 base="@PROVISION", scope=ldb.SCOPE_BASE,
337 attrs=[LAST_PROVISION_USN_ATTRIBUTE, "provisionnerID"])
338 except ldb.LdbError, (ecode, emsg):
339 if ecode == ldb.ERR_NO_SUCH_OBJECT:
340 return None
341 raise
342 if len(entry):
343 myids = []
344 range = {}
345 p = re.compile(r'-')
346 if entry[0].get("provisionnerID"):
347 for e in entry[0]["provisionnerID"]:
348 myids.append(str(e))
349 for r in entry[0][LAST_PROVISION_USN_ATTRIBUTE]:
350 tab1 = str(r).split(';')
351 if len(tab1) == 2:
352 id = tab1[1]
353 else:
354 id = "default"
355 if (len(myids) > 0 and id not in myids):
356 continue
357 tab2 = p.split(tab1[0])
358 if range.get(id) == None:
359 range[id] = []
360 range[id].append(tab2[0])
361 range[id].append(tab2[1])
362 return range
363 else:
364 return None
367 class ProvisionResult(object):
368 """Result of a provision.
370 :ivar server_role: The server role
371 :ivar paths: ProvisionPaths instance
372 :ivar domaindn: The domain dn, as string
375 def __init__(self):
376 self.server_role = None
377 self.paths = None
378 self.domaindn = None
379 self.lp = None
380 self.samdb = None
381 self.idmap = None
382 self.names = None
383 self.domainsid = None
384 self.adminpass_generated = None
385 self.adminpass = None
386 self.backend_result = None
388 def report_logger(self, logger):
389 """Report this provision result to a logger."""
390 logger.info(
391 "Once the above files are installed, your Samba4 server will "
392 "be ready to use")
393 if self.adminpass_generated:
394 logger.info("Admin password: %s", self.adminpass)
395 logger.info("Server Role: %s", self.server_role)
396 logger.info("Hostname: %s", self.names.hostname)
397 logger.info("NetBIOS Domain: %s", self.names.domain)
398 logger.info("DNS Domain: %s", self.names.dnsdomain)
399 logger.info("DOMAIN SID: %s", self.domainsid)
401 if self.paths.phpldapadminconfig is not None:
402 logger.info(
403 "A phpLDAPadmin configuration file suitable for administering "
404 "the Samba 4 LDAP server has been created in %s.",
405 self.paths.phpldapadminconfig)
407 if self.backend_result:
408 self.backend_result.report_logger(logger)
411 def check_install(lp, session_info, credentials):
412 """Check whether the current install seems ok.
414 :param lp: Loadparm context
415 :param session_info: Session information
416 :param credentials: Credentials
418 if lp.get("realm") == "":
419 raise Exception("Realm empty")
420 samdb = Ldb(lp.samdb_url(), session_info=session_info,
421 credentials=credentials, lp=lp)
422 if len(samdb.search("(cn=Administrator)")) != 1:
423 raise ProvisioningError("No administrator account found")
426 def findnss(nssfn, names):
427 """Find a user or group from a list of possibilities.
429 :param nssfn: NSS Function to try (should raise KeyError if not found)
430 :param names: Names to check.
431 :return: Value return by first names list.
433 for name in names:
434 try:
435 return nssfn(name)
436 except KeyError:
437 pass
438 raise KeyError("Unable to find user/group in %r" % names)
441 findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2]
442 findnss_gid = lambda names: findnss(grp.getgrnam, names)[2]
445 def provision_paths_from_lp(lp, dnsdomain):
446 """Set the default paths for provisioning.
448 :param lp: Loadparm context.
449 :param dnsdomain: DNS Domain name
451 paths = ProvisionPaths()
452 paths.private_dir = lp.get("private dir")
453 paths.state_dir = lp.get("state directory")
455 # This is stored without path prefix for the "privateKeytab" attribute in
456 # "secrets_dns.ldif".
457 paths.dns_keytab = "dns.keytab"
458 paths.keytab = "secrets.keytab"
460 paths.shareconf = os.path.join(paths.private_dir, "share.ldb")
461 paths.samdb = os.path.join(paths.private_dir, "sam.ldb")
462 paths.idmapdb = os.path.join(paths.private_dir, "idmap.ldb")
463 paths.secrets = os.path.join(paths.private_dir, "secrets.ldb")
464 paths.privilege = os.path.join(paths.private_dir, "privilege.ldb")
465 paths.dns = os.path.join(paths.private_dir, "dns", dnsdomain + ".zone")
466 paths.dns_update_list = os.path.join(paths.private_dir, "dns_update_list")
467 paths.spn_update_list = os.path.join(paths.private_dir, "spn_update_list")
468 paths.namedconf = os.path.join(paths.private_dir, "named.conf")
469 paths.namedconf_update = os.path.join(paths.private_dir, "named.conf.update")
470 paths.namedtxt = os.path.join(paths.private_dir, "named.txt")
471 paths.krb5conf = os.path.join(paths.private_dir, "krb5.conf")
472 paths.winsdb = os.path.join(paths.private_dir, "wins.ldb")
473 paths.s4_ldapi_path = os.path.join(paths.private_dir, "ldapi")
474 paths.phpldapadminconfig = os.path.join(paths.private_dir,
475 "phpldapadmin-config.php")
476 paths.hklm = "hklm.ldb"
477 paths.hkcr = "hkcr.ldb"
478 paths.hkcu = "hkcu.ldb"
479 paths.hku = "hku.ldb"
480 paths.hkpd = "hkpd.ldb"
481 paths.hkpt = "hkpt.ldb"
482 paths.sysvol = lp.get("path", "sysvol")
483 paths.netlogon = lp.get("path", "netlogon")
484 paths.smbconf = lp.configfile
485 return paths
488 def determine_netbios_name(hostname):
489 """Determine a netbios name from a hostname."""
490 # remove forbidden chars and force the length to be <16
491 netbiosname = "".join([x for x in hostname if is_valid_netbios_char(x)])
492 return netbiosname[:MAX_NETBIOS_NAME_LEN].upper()
495 def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None,
496 serverrole=None, rootdn=None, domaindn=None, configdn=None,
497 schemadn=None, serverdn=None, sitename=None):
498 """Guess configuration settings to use."""
500 if hostname is None:
501 hostname = socket.gethostname().split(".")[0]
503 netbiosname = lp.get("netbios name")
504 if netbiosname is None:
505 netbiosname = determine_netbios_name(hostname)
506 netbiosname = netbiosname.upper()
507 if not valid_netbios_name(netbiosname):
508 raise InvalidNetbiosName(netbiosname)
510 if dnsdomain is None:
511 dnsdomain = lp.get("realm")
512 if dnsdomain is None or dnsdomain == "":
513 raise ProvisioningError("guess_names: 'realm' not specified in supplied %s!", lp.configfile)
515 dnsdomain = dnsdomain.lower()
517 if serverrole is None:
518 serverrole = lp.get("server role")
519 if serverrole is None:
520 raise ProvisioningError("guess_names: 'server role' not specified in supplied %s!" % lp.configfile)
522 serverrole = serverrole.lower()
524 realm = dnsdomain.upper()
526 if lp.get("realm") == "":
527 raise ProvisioningError("guess_names: 'realm =' was not specified in supplied %s. Please remove the smb.conf file and let provision generate it" % lp.configfile)
529 if lp.get("realm").upper() != realm:
530 raise ProvisioningError("guess_names: 'realm=%s' in %s must match chosen realm '%s'! Please remove the smb.conf file and let provision generate it" % (lp.get("realm").upper(), realm, lp.configfile))
532 if lp.get("server role").lower() != serverrole:
533 raise ProvisioningError("guess_names: 'server role=%s' in %s must match chosen server role '%s'! Please remove the smb.conf file and let provision generate it" % (lp.get("server role"), lp.configfile, serverrole))
535 if serverrole == "active directory domain controller":
536 if domain is None:
537 # This will, for better or worse, default to 'WORKGROUP'
538 domain = lp.get("workgroup")
539 domain = domain.upper()
541 if lp.get("workgroup").upper() != domain:
542 raise ProvisioningError("guess_names: Workgroup '%s' in smb.conf must match chosen domain '%s'! Please remove the %s file and let provision generate it" % (lp.get("workgroup").upper(), domain, lp.configfile))
544 if domaindn is None:
545 domaindn = samba.dn_from_dns_name(dnsdomain)
547 if domain == netbiosname:
548 raise ProvisioningError("guess_names: Domain '%s' must not be equal to short host name '%s'!" % (domain, netbiosname))
549 else:
550 domain = netbiosname
551 if domaindn is None:
552 domaindn = "DC=" + netbiosname
554 if not valid_netbios_name(domain):
555 raise InvalidNetbiosName(domain)
557 if hostname.upper() == realm:
558 raise ProvisioningError("guess_names: Realm '%s' must not be equal to hostname '%s'!" % (realm, hostname))
559 if netbiosname.upper() == realm:
560 raise ProvisioningError("guess_names: Realm '%s' must not be equal to netbios hostname '%s'!" % (realm, netbiosname))
561 if domain == realm:
562 raise ProvisioningError("guess_names: Realm '%s' must not be equal to short domain name '%s'!" % (realm, domain))
564 if rootdn is None:
565 rootdn = domaindn
567 if configdn is None:
568 configdn = "CN=Configuration," + rootdn
569 if schemadn is None:
570 schemadn = "CN=Schema," + configdn
572 if sitename is None:
573 sitename = DEFAULTSITE
575 names = ProvisionNames()
576 names.rootdn = rootdn
577 names.domaindn = domaindn
578 names.configdn = configdn
579 names.schemadn = schemadn
580 names.ldapmanagerdn = "CN=Manager," + rootdn
581 names.dnsdomain = dnsdomain
582 names.domain = domain
583 names.realm = realm
584 names.netbiosname = netbiosname
585 names.hostname = hostname
586 names.sitename = sitename
587 names.serverdn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (
588 netbiosname, sitename, configdn)
590 return names
593 def make_smbconf(smbconf, hostname, domain, realm, targetdir,
594 serverrole=None, eadb=False, use_ntvfs=False, lp=None,
595 global_param=None):
596 """Create a new smb.conf file based on a couple of basic settings.
598 assert smbconf is not None
600 if hostname is None:
601 hostname = socket.gethostname().split(".")[0]
603 netbiosname = determine_netbios_name(hostname)
605 if serverrole is None:
606 serverrole = "standalone server"
608 assert domain is not None
609 domain = domain.upper()
611 assert realm is not None
612 realm = realm.upper()
614 global_settings = {
615 "passdb backend": "samba4",
616 "netbios name": netbiosname,
617 "workgroup": domain,
618 "realm": realm,
619 "server role": serverrole,
622 if lp is None:
623 lp = samba.param.LoadParm()
624 #Load non-existent file
625 if os.path.exists(smbconf):
626 lp.load(smbconf)
628 if global_param is not None:
629 for ent in global_param:
630 if global_param[ent] is not None:
631 global_settings[ent] = " ".join(global_param[ent])
633 if targetdir is not None:
634 global_settings["private dir"] = os.path.abspath(os.path.join(targetdir, "private"))
635 global_settings["lock dir"] = os.path.abspath(targetdir)
636 global_settings["state directory"] = os.path.abspath(os.path.join(targetdir, "state"))
637 global_settings["cache directory"] = os.path.abspath(os.path.join(targetdir, "cache"))
639 lp.set("lock dir", os.path.abspath(targetdir))
640 lp.set("state directory", global_settings["state directory"])
641 lp.set("cache directory", global_settings["cache directory"])
643 if eadb:
644 if use_ntvfs and not lp.get("posix:eadb"):
645 if targetdir is not None:
646 privdir = os.path.join(targetdir, "private")
647 else:
648 privdir = lp.get("private dir")
649 lp.set("posix:eadb", os.path.abspath(os.path.join(privdir, "eadb.tdb")))
650 elif not use_ntvfs and not lp.get("xattr_tdb:file"):
651 if targetdir is not None:
652 statedir = os.path.join(targetdir, "state")
653 else:
654 statedir = lp.get("state directory")
655 lp.set("xattr_tdb:file", os.path.abspath(os.path.join(statedir, "xattr.tdb")))
657 shares = {}
658 if serverrole == "active directory domain controller":
659 shares["sysvol"] = os.path.join(lp.get("state directory"), "sysvol")
660 shares["netlogon"] = os.path.join(shares["sysvol"], realm.lower(),
661 "scripts")
663 f = open(smbconf, 'w')
664 try:
665 f.write("[globals]\n")
666 for key, val in global_settings.iteritems():
667 f.write("\t%s = %s\n" % (key, val))
668 f.write("\n")
670 for name, path in shares.iteritems():
671 f.write("[%s]\n" % name)
672 f.write("\tpath = %s\n" % path)
673 f.write("\tread only = no\n")
674 f.write("\n")
675 finally:
676 f.close()
677 # reload the smb.conf
678 lp.load(smbconf)
680 # and dump it without any values that are the default
681 # this ensures that any smb.conf parameters that were set
682 # on the provision/join command line are set in the resulting smb.conf
683 f = open(smbconf, mode='w')
684 try:
685 lp.dump(f, False)
686 finally:
687 f.close()
690 def setup_name_mappings(idmap, sid, root_uid, nobody_uid,
691 users_gid, wheel_gid):
692 """setup reasonable name mappings for sam names to unix names.
694 :param samdb: SamDB object.
695 :param idmap: IDmap db object.
696 :param sid: The domain sid.
697 :param domaindn: The domain DN.
698 :param root_uid: uid of the UNIX root user.
699 :param nobody_uid: uid of the UNIX nobody user.
700 :param users_gid: gid of the UNIX users group.
701 :param wheel_gid: gid of the UNIX wheel group.
703 idmap.setup_name_mapping("S-1-5-7", idmap.TYPE_UID, nobody_uid)
704 idmap.setup_name_mapping("S-1-5-32-544", idmap.TYPE_GID, wheel_gid)
706 idmap.setup_name_mapping(sid + "-500", idmap.TYPE_UID, root_uid)
707 idmap.setup_name_mapping(sid + "-513", idmap.TYPE_GID, users_gid)
710 def setup_samdb_partitions(samdb_path, logger, lp, session_info,
711 provision_backend, names, schema, serverrole,
712 erase=False):
713 """Setup the partitions for the SAM database.
715 Alternatively, provision() may call this, and then populate the database.
717 :note: This will wipe the Sam Database!
719 :note: This function always removes the local SAM LDB file. The erase
720 parameter controls whether to erase the existing data, which
721 may not be stored locally but in LDAP.
724 assert session_info is not None
726 # We use options=["modules:"] to stop the modules loading - we
727 # just want to wipe and re-initialise the database, not start it up
729 try:
730 os.unlink(samdb_path)
731 except OSError:
732 pass
734 samdb = Ldb(url=samdb_path, session_info=session_info,
735 lp=lp, options=["modules:"])
737 ldap_backend_line = "# No LDAP backend"
738 if provision_backend.type != "ldb":
739 ldap_backend_line = "ldapBackend: %s" % provision_backend.ldap_uri
741 samdb.transaction_start()
742 try:
743 logger.info("Setting up sam.ldb partitions and settings")
744 setup_add_ldif(samdb, setup_path("provision_partitions.ldif"), {
745 "LDAP_BACKEND_LINE": ldap_backend_line
749 setup_add_ldif(samdb, setup_path("provision_init.ldif"), {
750 "BACKEND_TYPE": provision_backend.type,
751 "SERVER_ROLE": serverrole
754 logger.info("Setting up sam.ldb rootDSE")
755 setup_samdb_rootdse(samdb, names)
756 except:
757 samdb.transaction_cancel()
758 raise
759 else:
760 samdb.transaction_commit()
763 def secretsdb_self_join(secretsdb, domain,
764 netbiosname, machinepass, domainsid=None,
765 realm=None, dnsdomain=None,
766 keytab_path=None,
767 key_version_number=1,
768 secure_channel_type=SEC_CHAN_WKSTA):
769 """Add domain join-specific bits to a secrets database.
771 :param secretsdb: Ldb Handle to the secrets database
772 :param machinepass: Machine password
774 attrs = ["whenChanged",
775 "secret",
776 "priorSecret",
777 "priorChanged",
778 "krb5Keytab",
779 "privateKeytab"]
781 if realm is not None:
782 if dnsdomain is None:
783 dnsdomain = realm.lower()
784 dnsname = '%s.%s' % (netbiosname.lower(), dnsdomain.lower())
785 else:
786 dnsname = None
787 shortname = netbiosname.lower()
789 # We don't need to set msg["flatname"] here, because rdn_name will handle
790 # it, and it causes problems for modifies anyway
791 msg = ldb.Message(ldb.Dn(secretsdb, "flatname=%s,cn=Primary Domains" % domain))
792 msg["secureChannelType"] = [str(secure_channel_type)]
793 msg["objectClass"] = ["top", "primaryDomain"]
794 if dnsname is not None:
795 msg["objectClass"] = ["top", "primaryDomain", "kerberosSecret"]
796 msg["realm"] = [realm]
797 msg["saltPrincipal"] = ["host/%s@%s" % (dnsname, realm.upper())]
798 msg["msDS-KeyVersionNumber"] = [str(key_version_number)]
799 msg["privateKeytab"] = ["secrets.keytab"]
801 msg["secret"] = [machinepass]
802 msg["samAccountName"] = ["%s$" % netbiosname]
803 msg["secureChannelType"] = [str(secure_channel_type)]
804 if domainsid is not None:
805 msg["objectSid"] = [ndr_pack(domainsid)]
807 # This complex expression tries to ensure that we don't have more
808 # than one record for this SID, realm or netbios domain at a time,
809 # but we don't delete the old record that we are about to modify,
810 # because that would delete the keytab and previous password.
811 res = secretsdb.search(base="cn=Primary Domains", attrs=attrs,
812 expression=("(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(distinguishedName=%s)))" % (domain, realm, str(domainsid), str(msg.dn))),
813 scope=ldb.SCOPE_ONELEVEL)
815 for del_msg in res:
816 secretsdb.delete(del_msg.dn)
818 res = secretsdb.search(base=msg.dn, attrs=attrs, scope=ldb.SCOPE_BASE)
820 if len(res) == 1:
821 msg["priorSecret"] = [res[0]["secret"][0]]
822 msg["priorWhenChanged"] = [res[0]["whenChanged"][0]]
824 try:
825 msg["privateKeytab"] = [res[0]["privateKeytab"][0]]
826 except KeyError:
827 pass
829 try:
830 msg["krb5Keytab"] = [res[0]["krb5Keytab"][0]]
831 except KeyError:
832 pass
834 for el in msg:
835 if el != 'dn':
836 msg[el].set_flags(ldb.FLAG_MOD_REPLACE)
837 secretsdb.modify(msg)
838 secretsdb.rename(res[0].dn, msg.dn)
839 else:
840 spn = [ 'HOST/%s' % shortname ]
841 if secure_channel_type == SEC_CHAN_BDC and dnsname is not None:
842 # we are a domain controller then we add servicePrincipalName
843 # entries for the keytab code to update.
844 spn.extend([ 'HOST/%s' % dnsname ])
845 msg["servicePrincipalName"] = spn
847 secretsdb.add(msg)
850 def setup_secretsdb(paths, session_info, backend_credentials, lp):
851 """Setup the secrets database.
853 :note: This function does not handle exceptions and transaction on purpose,
854 it's up to the caller to do this job.
856 :param path: Path to the secrets database.
857 :param session_info: Session info.
858 :param credentials: Credentials
859 :param lp: Loadparm context
860 :return: LDB handle for the created secrets database
862 if os.path.exists(paths.secrets):
863 os.unlink(paths.secrets)
865 keytab_path = os.path.join(paths.private_dir, paths.keytab)
866 if os.path.exists(keytab_path):
867 os.unlink(keytab_path)
869 dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab)
870 if os.path.exists(dns_keytab_path):
871 os.unlink(dns_keytab_path)
873 path = paths.secrets
875 secrets_ldb = Ldb(path, session_info=session_info, lp=lp)
876 secrets_ldb.erase()
877 secrets_ldb.load_ldif_file_add(setup_path("secrets_init.ldif"))
878 secrets_ldb = Ldb(path, session_info=session_info, lp=lp)
879 secrets_ldb.transaction_start()
880 try:
881 secrets_ldb.load_ldif_file_add(setup_path("secrets.ldif"))
883 if (backend_credentials is not None and
884 backend_credentials.authentication_requested()):
885 if backend_credentials.get_bind_dn() is not None:
886 setup_add_ldif(secrets_ldb,
887 setup_path("secrets_simple_ldap.ldif"), {
888 "LDAPMANAGERDN": backend_credentials.get_bind_dn(),
889 "LDAPMANAGERPASS_B64": b64encode(backend_credentials.get_password())
891 else:
892 setup_add_ldif(secrets_ldb,
893 setup_path("secrets_sasl_ldap.ldif"), {
894 "LDAPADMINUSER": backend_credentials.get_username(),
895 "LDAPADMINREALM": backend_credentials.get_realm(),
896 "LDAPADMINPASS_B64": b64encode(backend_credentials.get_password())
898 except:
899 secrets_ldb.transaction_cancel()
900 raise
901 return secrets_ldb
904 def setup_privileges(path, session_info, lp):
905 """Setup the privileges database.
907 :param path: Path to the privileges database.
908 :param session_info: Session info.
909 :param credentials: Credentials
910 :param lp: Loadparm context
911 :return: LDB handle for the created secrets database
913 if os.path.exists(path):
914 os.unlink(path)
915 privilege_ldb = Ldb(path, session_info=session_info, lp=lp)
916 privilege_ldb.erase()
917 privilege_ldb.load_ldif_file_add(setup_path("provision_privilege.ldif"))
920 def setup_registry(path, session_info, lp):
921 """Setup the registry.
923 :param path: Path to the registry database
924 :param session_info: Session information
925 :param credentials: Credentials
926 :param lp: Loadparm context
928 reg = samba.registry.Registry()
929 hive = samba.registry.open_ldb(path, session_info=session_info, lp_ctx=lp)
930 reg.mount_hive(hive, samba.registry.HKEY_LOCAL_MACHINE)
931 provision_reg = setup_path("provision.reg")
932 assert os.path.exists(provision_reg)
933 reg.diff_apply(provision_reg)
936 def setup_idmapdb(path, session_info, lp):
937 """Setup the idmap database.
939 :param path: path to the idmap database
940 :param session_info: Session information
941 :param credentials: Credentials
942 :param lp: Loadparm context
944 if os.path.exists(path):
945 os.unlink(path)
947 idmap_ldb = IDmapDB(path, session_info=session_info, lp=lp)
948 idmap_ldb.erase()
949 idmap_ldb.load_ldif_file_add(setup_path("idmap_init.ldif"))
950 return idmap_ldb
953 def setup_samdb_rootdse(samdb, names):
954 """Setup the SamDB rootdse.
956 :param samdb: Sam Database handle
958 setup_add_ldif(samdb, setup_path("provision_rootdse_add.ldif"), {
959 "SCHEMADN": names.schemadn,
960 "DOMAINDN": names.domaindn,
961 "ROOTDN" : names.rootdn,
962 "CONFIGDN": names.configdn,
963 "SERVERDN": names.serverdn,
967 def setup_self_join(samdb, admin_session_info, names, fill, machinepass,
968 dnspass, domainsid, next_rid, invocationid, policyguid, policyguid_dc,
969 domainControllerFunctionality, ntdsguid=None, dc_rid=None):
970 """Join a host to its own domain."""
971 assert isinstance(invocationid, str)
972 if ntdsguid is not None:
973 ntdsguid_line = "objectGUID: %s\n"%ntdsguid
974 else:
975 ntdsguid_line = ""
977 if dc_rid is None:
978 dc_rid = next_rid
980 setup_add_ldif(samdb, setup_path("provision_self_join.ldif"), {
981 "CONFIGDN": names.configdn,
982 "SCHEMADN": names.schemadn,
983 "DOMAINDN": names.domaindn,
984 "SERVERDN": names.serverdn,
985 "INVOCATIONID": invocationid,
986 "NETBIOSNAME": names.netbiosname,
987 "DNSNAME": "%s.%s" % (names.hostname, names.dnsdomain),
988 "MACHINEPASS_B64": b64encode(machinepass.encode('utf-16-le')),
989 "DOMAINSID": str(domainsid),
990 "DCRID": str(dc_rid),
991 "SAMBA_VERSION_STRING": version,
992 "NTDSGUID": ntdsguid_line,
993 "DOMAIN_CONTROLLER_FUNCTIONALITY": str(
994 domainControllerFunctionality),
995 "RIDALLOCATIONSTART": str(next_rid + 100),
996 "RIDALLOCATIONEND": str(next_rid + 100 + 499)})
998 setup_add_ldif(samdb, setup_path("provision_group_policy.ldif"), {
999 "POLICYGUID": policyguid,
1000 "POLICYGUID_DC": policyguid_dc,
1001 "DNSDOMAIN": names.dnsdomain,
1002 "DOMAINDN": names.domaindn})
1004 # If we are setting up a subdomain, then this has been replicated in, so we
1005 # don't need to add it
1006 if fill == FILL_FULL:
1007 setup_add_ldif(samdb, setup_path("provision_self_join_config.ldif"), {
1008 "CONFIGDN": names.configdn,
1009 "SCHEMADN": names.schemadn,
1010 "DOMAINDN": names.domaindn,
1011 "SERVERDN": names.serverdn,
1012 "INVOCATIONID": invocationid,
1013 "NETBIOSNAME": names.netbiosname,
1014 "DNSNAME": "%s.%s" % (names.hostname, names.dnsdomain),
1015 "MACHINEPASS_B64": b64encode(machinepass.encode('utf-16-le')),
1016 "DOMAINSID": str(domainsid),
1017 "DCRID": str(dc_rid),
1018 "SAMBA_VERSION_STRING": version,
1019 "NTDSGUID": ntdsguid_line,
1020 "DOMAIN_CONTROLLER_FUNCTIONALITY": str(
1021 domainControllerFunctionality)})
1023 # Setup fSMORoleOwner entries to point at the newly created DC entry
1024 setup_modify_ldif(samdb,
1025 setup_path("provision_self_join_modify_config.ldif"), {
1026 "CONFIGDN": names.configdn,
1027 "SCHEMADN": names.schemadn,
1028 "DEFAULTSITE": names.sitename,
1029 "NETBIOSNAME": names.netbiosname,
1030 "SERVERDN": names.serverdn,
1033 system_session_info = system_session()
1034 samdb.set_session_info(system_session_info)
1035 # Setup fSMORoleOwner entries to point at the newly created DC entry to
1036 # modify a serverReference under cn=config when we are a subdomain, we must
1037 # be system due to ACLs
1038 setup_modify_ldif(samdb, setup_path("provision_self_join_modify.ldif"), {
1039 "DOMAINDN": names.domaindn,
1040 "SERVERDN": names.serverdn,
1041 "NETBIOSNAME": names.netbiosname,
1044 samdb.set_session_info(admin_session_info)
1046 # This is Samba4 specific and should be replaced by the correct
1047 # DNS AD-style setup
1048 setup_add_ldif(samdb, setup_path("provision_dns_add_samba.ldif"), {
1049 "DNSDOMAIN": names.dnsdomain,
1050 "DOMAINDN": names.domaindn,
1051 "DNSPASS_B64": b64encode(dnspass.encode('utf-16-le')),
1052 "HOSTNAME" : names.hostname,
1053 "DNSNAME" : '%s.%s' % (
1054 names.netbiosname.lower(), names.dnsdomain.lower())
1058 def getpolicypath(sysvolpath, dnsdomain, guid):
1059 """Return the physical path of policy given its guid.
1061 :param sysvolpath: Path to the sysvol folder
1062 :param dnsdomain: DNS name of the AD domain
1063 :param guid: The GUID of the policy
1064 :return: A string with the complete path to the policy folder
1066 if guid[0] != "{":
1067 guid = "{%s}" % guid
1068 policy_path = os.path.join(sysvolpath, dnsdomain, "Policies", guid)
1069 return policy_path
1072 def create_gpo_struct(policy_path):
1073 if not os.path.exists(policy_path):
1074 os.makedirs(policy_path, 0775)
1075 f = open(os.path.join(policy_path, "GPT.INI"), 'w')
1076 try:
1077 f.write("[General]\r\nVersion=0")
1078 finally:
1079 f.close()
1080 p = os.path.join(policy_path, "MACHINE")
1081 if not os.path.exists(p):
1082 os.makedirs(p, 0775)
1083 p = os.path.join(policy_path, "USER")
1084 if not os.path.exists(p):
1085 os.makedirs(p, 0775)
1088 def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc):
1089 """Create the default GPO for a domain
1091 :param sysvolpath: Physical path for the sysvol folder
1092 :param dnsdomain: DNS domain name of the AD domain
1093 :param policyguid: GUID of the default domain policy
1094 :param policyguid_dc: GUID of the default domain controler policy
1096 policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid)
1097 create_gpo_struct(policy_path)
1099 policy_path = getpolicypath(sysvolpath,dnsdomain,policyguid_dc)
1100 create_gpo_struct(policy_path)
1103 def setup_samdb(path, session_info, provision_backend, lp, names,
1104 logger, fill, serverrole, schema, am_rodc=False):
1105 """Setup a complete SAM Database.
1107 :note: This will wipe the main SAM database file!
1110 # Also wipes the database
1111 setup_samdb_partitions(path, logger=logger, lp=lp,
1112 provision_backend=provision_backend, session_info=session_info,
1113 names=names, serverrole=serverrole, schema=schema)
1115 # Load the database, but don's load the global schema and don't connect
1116 # quite yet
1117 samdb = SamDB(session_info=session_info, url=None, auto_connect=False,
1118 credentials=provision_backend.credentials, lp=lp,
1119 global_schema=False, am_rodc=am_rodc)
1121 logger.info("Pre-loading the Samba 4 and AD schema")
1123 # Load the schema from the one we computed earlier
1124 samdb.set_schema(schema, write_indices_and_attributes=False)
1126 # Set the NTDS settings DN manually - in order to have it already around
1127 # before the provisioned tree exists and we connect
1128 samdb.set_ntds_settings_dn("CN=NTDS Settings,%s" % names.serverdn)
1130 # And now we can connect to the DB - the schema won't be loaded from the
1131 # DB
1132 samdb.connect(path)
1134 # But we have to give it one more kick to have it use the schema
1135 # during provision - it needs, now that it is connected, to write
1136 # the schema @ATTRIBUTES and @INDEXLIST records to the database.
1137 samdb.set_schema(schema, write_indices_and_attributes=True)
1139 return samdb
1142 def fill_samdb(samdb, lp, names,
1143 logger, domainsid, domainguid, policyguid, policyguid_dc, fill,
1144 adminpass, krbtgtpass, machinepass, invocationid, dnspass, ntdsguid,
1145 serverrole, am_rodc=False, dom_for_fun_level=None, schema=None,
1146 next_rid=None, dc_rid=None):
1148 if next_rid is None:
1149 next_rid = 1000
1151 # Provision does not make much sense values larger than 1000000000
1152 # as the upper range of the rIDAvailablePool is 1073741823 and
1153 # we don't want to create a domain that cannot allocate rids.
1154 if next_rid < 1000 or next_rid > 1000000000:
1155 error = "You want to run SAMBA 4 with a next_rid of %u, " % (next_rid)
1156 error += "the valid range is %u-%u. The default is %u." % (
1157 1000, 1000000000, 1000)
1158 raise ProvisioningError(error)
1160 # ATTENTION: Do NOT change these default values without discussion with the
1161 # team and/or release manager. They have a big impact on the whole program!
1162 domainControllerFunctionality = DS_DOMAIN_FUNCTION_2008_R2
1164 if dom_for_fun_level is None:
1165 dom_for_fun_level = DS_DOMAIN_FUNCTION_2003
1167 if dom_for_fun_level > domainControllerFunctionality:
1168 raise ProvisioningError("You want to run SAMBA 4 on a domain and forest function level which itself is higher than its actual DC function level (2008_R2). This won't work!")
1170 domainFunctionality = dom_for_fun_level
1171 forestFunctionality = dom_for_fun_level
1173 # Set the NTDS settings DN manually - in order to have it already around
1174 # before the provisioned tree exists and we connect
1175 samdb.set_ntds_settings_dn("CN=NTDS Settings,%s" % names.serverdn)
1177 samdb.transaction_start()
1178 try:
1179 # Set the domain functionality levels onto the database.
1180 # Various module (the password_hash module in particular) need
1181 # to know what level of AD we are emulating.
1183 # These will be fixed into the database via the database
1184 # modifictions below, but we need them set from the start.
1185 samdb.set_opaque_integer("domainFunctionality", domainFunctionality)
1186 samdb.set_opaque_integer("forestFunctionality", forestFunctionality)
1187 samdb.set_opaque_integer("domainControllerFunctionality",
1188 domainControllerFunctionality)
1190 samdb.set_domain_sid(str(domainsid))
1191 samdb.set_invocation_id(invocationid)
1193 logger.info("Adding DomainDN: %s" % names.domaindn)
1195 # impersonate domain admin
1196 admin_session_info = admin_session(lp, str(domainsid))
1197 samdb.set_session_info(admin_session_info)
1198 if domainguid is not None:
1199 domainguid_line = "objectGUID: %s\n-" % domainguid
1200 else:
1201 domainguid_line = ""
1203 descr = b64encode(get_domain_descriptor(domainsid))
1204 setup_add_ldif(samdb, setup_path("provision_basedn.ldif"), {
1205 "DOMAINDN": names.domaindn,
1206 "DOMAINSID": str(domainsid),
1207 "DESCRIPTOR": descr,
1208 "DOMAINGUID": domainguid_line
1211 setup_modify_ldif(samdb, setup_path("provision_basedn_modify.ldif"), {
1212 "DOMAINDN": names.domaindn,
1213 "CREATTIME": str(samba.unix2nttime(int(time.time()))),
1214 "NEXTRID": str(next_rid),
1215 "DEFAULTSITE": names.sitename,
1216 "CONFIGDN": names.configdn,
1217 "POLICYGUID": policyguid,
1218 "DOMAIN_FUNCTIONALITY": str(domainFunctionality),
1219 "SAMBA_VERSION_STRING": version
1222 # If we are setting up a subdomain, then this has been replicated in, so we don't need to add it
1223 if fill == FILL_FULL:
1224 logger.info("Adding configuration container")
1225 descr = b64encode(get_config_descriptor(domainsid))
1226 setup_add_ldif(samdb, setup_path("provision_configuration_basedn.ldif"), {
1227 "CONFIGDN": names.configdn,
1228 "DESCRIPTOR": descr,
1231 # The LDIF here was created when the Schema object was constructed
1232 logger.info("Setting up sam.ldb schema")
1233 samdb.add_ldif(schema.schema_dn_add, controls=["relax:0"])
1234 samdb.modify_ldif(schema.schema_dn_modify)
1235 samdb.write_prefixes_from_schema()
1236 samdb.add_ldif(schema.schema_data, controls=["relax:0"])
1237 setup_add_ldif(samdb, setup_path("aggregate_schema.ldif"),
1238 {"SCHEMADN": names.schemadn})
1240 # Now register this container in the root of the forest
1241 msg = ldb.Message(ldb.Dn(samdb, names.domaindn))
1242 msg["subRefs"] = ldb.MessageElement(names.configdn , ldb.FLAG_MOD_ADD,
1243 "subRefs")
1245 except:
1246 samdb.transaction_cancel()
1247 raise
1248 else:
1249 samdb.transaction_commit()
1251 samdb.transaction_start()
1252 try:
1253 samdb.invocation_id = invocationid
1255 # If we are setting up a subdomain, then this has been replicated in, so we don't need to add it
1256 if fill == FILL_FULL:
1257 logger.info("Setting up sam.ldb configuration data")
1258 setup_add_ldif(samdb, setup_path("provision_configuration.ldif"), {
1259 "CONFIGDN": names.configdn,
1260 "NETBIOSNAME": names.netbiosname,
1261 "DEFAULTSITE": names.sitename,
1262 "DNSDOMAIN": names.dnsdomain,
1263 "DOMAIN": names.domain,
1264 "SCHEMADN": names.schemadn,
1265 "DOMAINDN": names.domaindn,
1266 "SERVERDN": names.serverdn,
1267 "FOREST_FUNCTIONALITY": str(forestFunctionality),
1268 "DOMAIN_FUNCTIONALITY": str(domainFunctionality),
1271 logger.info("Setting up display specifiers")
1272 display_specifiers_ldif = read_ms_ldif(
1273 setup_path('display-specifiers/DisplaySpecifiers-Win2k8R2.txt'))
1274 display_specifiers_ldif = substitute_var(display_specifiers_ldif,
1275 {"CONFIGDN": names.configdn})
1276 check_all_substituted(display_specifiers_ldif)
1277 samdb.add_ldif(display_specifiers_ldif)
1279 logger.info("Adding users container")
1280 setup_add_ldif(samdb, setup_path("provision_users_add.ldif"), {
1281 "DOMAINDN": names.domaindn})
1282 logger.info("Modifying users container")
1283 setup_modify_ldif(samdb, setup_path("provision_users_modify.ldif"), {
1284 "DOMAINDN": names.domaindn})
1285 logger.info("Adding computers container")
1286 setup_add_ldif(samdb, setup_path("provision_computers_add.ldif"), {
1287 "DOMAINDN": names.domaindn})
1288 logger.info("Modifying computers container")
1289 setup_modify_ldif(samdb,
1290 setup_path("provision_computers_modify.ldif"), {
1291 "DOMAINDN": names.domaindn})
1292 logger.info("Setting up sam.ldb data")
1293 setup_add_ldif(samdb, setup_path("provision.ldif"), {
1294 "CREATTIME": str(samba.unix2nttime(int(time.time()))),
1295 "DOMAINDN": names.domaindn,
1296 "NETBIOSNAME": names.netbiosname,
1297 "DEFAULTSITE": names.sitename,
1298 "CONFIGDN": names.configdn,
1299 "SERVERDN": names.serverdn,
1300 "RIDAVAILABLESTART": str(next_rid + 600),
1301 "POLICYGUID_DC": policyguid_dc
1304 # If we are setting up a subdomain, then this has been replicated in, so we don't need to add it
1305 if fill == FILL_FULL:
1306 setup_modify_ldif(samdb,
1307 setup_path("provision_configuration_references.ldif"), {
1308 "CONFIGDN": names.configdn,
1309 "SCHEMADN": names.schemadn})
1311 logger.info("Setting up well known security principals")
1312 setup_add_ldif(samdb, setup_path("provision_well_known_sec_princ.ldif"), {
1313 "CONFIGDN": names.configdn,
1316 if fill == FILL_FULL or fill == FILL_SUBDOMAIN:
1317 setup_modify_ldif(samdb,
1318 setup_path("provision_basedn_references.ldif"),
1319 {"DOMAINDN": names.domaindn})
1321 logger.info("Setting up sam.ldb users and groups")
1322 setup_add_ldif(samdb, setup_path("provision_users.ldif"), {
1323 "DOMAINDN": names.domaindn,
1324 "DOMAINSID": str(domainsid),
1325 "ADMINPASS_B64": b64encode(adminpass.encode('utf-16-le')),
1326 "KRBTGTPASS_B64": b64encode(krbtgtpass.encode('utf-16-le'))
1329 logger.info("Setting up self join")
1330 setup_self_join(samdb, admin_session_info, names=names, fill=fill,
1331 invocationid=invocationid,
1332 dnspass=dnspass,
1333 machinepass=machinepass,
1334 domainsid=domainsid,
1335 next_rid=next_rid,
1336 dc_rid=dc_rid,
1337 policyguid=policyguid,
1338 policyguid_dc=policyguid_dc,
1339 domainControllerFunctionality=domainControllerFunctionality,
1340 ntdsguid=ntdsguid)
1342 ntds_dn = "CN=NTDS Settings,%s" % names.serverdn
1343 names.ntdsguid = samdb.searchone(basedn=ntds_dn,
1344 attribute="objectGUID", expression="", scope=ldb.SCOPE_BASE)
1345 assert isinstance(names.ntdsguid, str)
1346 except:
1347 samdb.transaction_cancel()
1348 raise
1349 else:
1350 samdb.transaction_commit()
1351 return samdb
1354 FILL_FULL = "FULL"
1355 FILL_SUBDOMAIN = "SUBDOMAIN"
1356 FILL_NT4SYNC = "NT4SYNC"
1357 FILL_DRS = "DRS"
1358 SYSVOL_ACL = "O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)"
1359 POLICIES_ACL = "O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)"
1362 def set_dir_acl(path, acl, lp, domsid):
1363 setntacl(lp, path, acl, domsid)
1364 for root, dirs, files in os.walk(path, topdown=False):
1365 for name in files:
1366 setntacl(lp, os.path.join(root, name), acl, domsid)
1367 for name in dirs:
1368 setntacl(lp, os.path.join(root, name), acl, domsid)
1371 def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp):
1372 """Set ACL on the sysvol/<dnsname>/Policies folder and the policy
1373 folders beneath.
1375 :param sysvol: Physical path for the sysvol folder
1376 :param dnsdomain: The DNS name of the domain
1377 :param domainsid: The SID of the domain
1378 :param domaindn: The DN of the domain (ie. DC=...)
1379 :param samdb: An LDB object on the SAM db
1380 :param lp: an LP object
1383 # Set ACL for GPO root folder
1384 root_policy_path = os.path.join(sysvol, dnsdomain, "Policies")
1385 setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid))
1387 res = samdb.search(base="CN=Policies,CN=System,%s"%(domaindn),
1388 attrs=["cn", "nTSecurityDescriptor"],
1389 expression="", scope=ldb.SCOPE_ONELEVEL)
1391 for policy in res:
1392 acl = ndr_unpack(security.descriptor,
1393 str(policy["nTSecurityDescriptor"])).as_sddl()
1394 policy_path = getpolicypath(sysvol, dnsdomain, str(policy["cn"]))
1395 set_dir_acl(policy_path, dsacl2fsacl(acl, str(domainsid)), lp,
1396 str(domainsid))
1399 def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn,
1400 lp):
1401 """Set the ACL for the sysvol share and the subfolders
1403 :param samdb: An LDB object on the SAM db
1404 :param netlogon: Physical path for the netlogon folder
1405 :param sysvol: Physical path for the sysvol folder
1406 :param gid: The GID of the "Domain adminstrators" group
1407 :param domainsid: The SID of the domain
1408 :param dnsdomain: The DNS name of the domain
1409 :param domaindn: The DN of the domain (ie. DC=...)
1412 try:
1413 os.chown(sysvol, -1, gid)
1414 except OSError:
1415 canchown = False
1416 else:
1417 canchown = True
1419 # Set the SYSVOL_ACL on the sysvol folder and subfolder (first level)
1420 setntacl(lp,sysvol, SYSVOL_ACL, str(domainsid))
1421 for root, dirs, files in os.walk(sysvol, topdown=False):
1422 for name in files:
1423 if canchown:
1424 os.chown(os.path.join(root, name), -1, gid)
1425 setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid))
1426 for name in dirs:
1427 if canchown:
1428 os.chown(os.path.join(root, name), -1, gid)
1429 setntacl(lp, os.path.join(root, name), SYSVOL_ACL, str(domainsid))
1431 # Set acls on Policy folder and policies folders
1432 set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp)
1435 def interface_ips_v4(lp):
1436 '''return only IPv4 IPs'''
1437 ips = samba.interface_ips(lp, False)
1438 ret = []
1439 for i in ips:
1440 if i.find(':') == -1:
1441 ret.append(i)
1442 return ret
1444 def interface_ips_v6(lp, linklocal=False):
1445 '''return only IPv6 IPs'''
1446 ips = samba.interface_ips(lp, False)
1447 ret = []
1448 for i in ips:
1449 if i.find(':') != -1 and (linklocal or i.find('%') == -1):
1450 ret.append(i)
1451 return ret
1454 def provision_fill(samdb, secrets_ldb, logger, names, paths,
1455 domainsid, schema=None,
1456 targetdir=None, samdb_fill=FILL_FULL,
1457 hostip=None, hostip6=None,
1458 next_rid=1000, dc_rid=None, adminpass=None, krbtgtpass=None,
1459 domainguid=None, policyguid=None, policyguid_dc=None,
1460 invocationid=None, machinepass=None, ntdsguid=None,
1461 dns_backend=None, dnspass=None,
1462 serverrole=None, dom_for_fun_level=None,
1463 am_rodc=False, lp=None):
1464 # create/adapt the group policy GUIDs
1465 # Default GUID for default policy are described at
1466 # "How Core Group Policy Works"
1467 # http://technet.microsoft.com/en-us/library/cc784268%28WS.10%29.aspx
1468 if policyguid is None:
1469 policyguid = DEFAULT_POLICY_GUID
1470 policyguid = policyguid.upper()
1471 if policyguid_dc is None:
1472 policyguid_dc = DEFAULT_DC_POLICY_GUID
1473 policyguid_dc = policyguid_dc.upper()
1475 if invocationid is None:
1476 invocationid = str(uuid.uuid4())
1478 if krbtgtpass is None:
1479 krbtgtpass = samba.generate_random_password(128, 255)
1480 if machinepass is None:
1481 machinepass = samba.generate_random_password(128, 255)
1482 if dnspass is None:
1483 dnspass = samba.generate_random_password(128, 255)
1485 samdb = fill_samdb(samdb, lp, names, logger=logger,
1486 domainsid=domainsid, schema=schema, domainguid=domainguid,
1487 policyguid=policyguid, policyguid_dc=policyguid_dc,
1488 fill=samdb_fill, adminpass=adminpass, krbtgtpass=krbtgtpass,
1489 invocationid=invocationid, machinepass=machinepass,
1490 dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole,
1491 dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,
1492 next_rid=next_rid, dc_rid=dc_rid)
1494 if serverrole == "active directory domain controller":
1495 # Set up group policies (domain policy and domain controller
1496 # policy)
1497 create_default_gpo(paths.sysvol, names.dnsdomain, policyguid,
1498 policyguid_dc)
1499 setsysvolacl(samdb, paths.netlogon, paths.sysvol, paths.wheel_gid,
1500 domainsid, names.dnsdomain, names.domaindn, lp)
1502 secretsdb_self_join(secrets_ldb, domain=names.domain,
1503 realm=names.realm, dnsdomain=names.dnsdomain,
1504 netbiosname=names.netbiosname, domainsid=domainsid,
1505 machinepass=machinepass, secure_channel_type=SEC_CHAN_BDC)
1507 # Now set up the right msDS-SupportedEncryptionTypes into the DB
1508 # In future, this might be determined from some configuration
1509 kerberos_enctypes = str(ENC_ALL_TYPES)
1511 try:
1512 msg = ldb.Message(ldb.Dn(samdb,
1513 samdb.searchone("distinguishedName",
1514 expression="samAccountName=%s$" % names.netbiosname,
1515 scope=ldb.SCOPE_SUBTREE)))
1516 msg["msDS-SupportedEncryptionTypes"] = ldb.MessageElement(
1517 elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE,
1518 name="msDS-SupportedEncryptionTypes")
1519 samdb.modify(msg)
1520 except ldb.LdbError, (enum, estr):
1521 if enum != ldb.ERR_NO_SUCH_ATTRIBUTE:
1522 # It might be that this attribute does not exist in this schema
1523 raise
1525 setup_ad_dns(samdb, secrets_ldb, domainsid, names, paths, lp, logger,
1526 hostip=hostip, hostip6=hostip6, dns_backend=dns_backend,
1527 dnspass=dnspass, os_level=dom_for_fun_level,
1528 targetdir=targetdir, site=DEFAULTSITE)
1530 domainguid = samdb.searchone(basedn=samdb.get_default_basedn(),
1531 attribute="objectGUID")
1532 assert isinstance(domainguid, str)
1534 lastProvisionUSNs = get_last_provision_usn(samdb)
1535 maxUSN = get_max_usn(samdb, str(names.rootdn))
1536 if lastProvisionUSNs is not None:
1537 update_provision_usn(samdb, 0, maxUSN, invocationid, 1)
1538 else:
1539 set_provision_usn(samdb, 0, maxUSN, invocationid)
1541 logger.info("Setting up sam.ldb rootDSE marking as synchronized")
1542 setup_modify_ldif(samdb, setup_path("provision_rootdse_modify.ldif"),
1543 { 'NTDSGUID' : names.ntdsguid })
1545 # fix any dangling GUIDs from the provision
1546 logger.info("Fixing provision GUIDs")
1547 chk = dbcheck(samdb, samdb_schema=samdb, verbose=False, fix=True, yes=True,
1548 quiet=True)
1549 samdb.transaction_start()
1550 try:
1551 # a small number of GUIDs are missing because of ordering issues in the
1552 # provision code
1553 for schema_obj in ['CN=Domain', 'CN=Organizational-Person', 'CN=Contact', 'CN=inetOrgPerson']:
1554 chk.check_database(DN="%s,%s" % (schema_obj, names.schemadn),
1555 scope=ldb.SCOPE_BASE, attrs=['defaultObjectCategory'])
1556 chk.check_database(DN="CN=IP Security,CN=System,%s" % names.domaindn,
1557 scope=ldb.SCOPE_ONELEVEL,
1558 attrs=['ipsecOwnersReference',
1559 'ipsecFilterReference',
1560 'ipsecISAKMPReference',
1561 'ipsecNegotiationPolicyReference',
1562 'ipsecNFAReference'])
1563 except:
1564 samdb.transaction_cancel()
1565 raise
1566 else:
1567 samdb.transaction_commit()
1570 _ROLES_MAP = {
1571 "ROLE_STANDALONE": "standalone server",
1572 "ROLE_DOMAIN_MEMBER": "member server",
1573 "ROLE_DOMAIN_BDC": "active directory domain controller",
1574 "ROLE_DOMAIN_PDC": "active directory domain controller",
1575 "dc": "active directory domain controller",
1576 "member": "member server",
1577 "domain controller": "active directory domain controller",
1578 "active directory domain controller": "active directory domain controller",
1579 "member server": "member server",
1580 "standalone": "standalone server",
1581 "standalone server": "standalone server",
1585 def sanitize_server_role(role):
1586 """Sanitize a server role name.
1588 :param role: Server role
1589 :raise ValueError: If the role can not be interpreted
1590 :return: Sanitized server role (one of "member server",
1591 "active directory domain controller", "standalone server")
1593 try:
1594 return _ROLES_MAP[role]
1595 except KeyError:
1596 raise ValueError(role)
1598 def provision_fake_ypserver(logger, samdb, domaindn, netbiosname, nisdomain, maxuid, maxgid):
1599 """Creates AD entries for the fake ypserver
1600 needed for being able to manipulate posix attrs via ADUC
1602 samdb.transaction_start()
1603 try:
1604 logger.info("Setting up fake yp server settings")
1605 setup_add_ldif(samdb, setup_path("ypServ30.ldif"), {
1606 "DOMAINDN": domaindn,
1607 "NETBIOSNAME": netbiosname,
1608 "NISDOMAIN": nisdomain,
1610 except Exception:
1611 samdb.transaction_cancel()
1612 raise
1613 else:
1614 samdb.transaction_commit()
1615 if maxuid != None:
1616 pass
1617 if maxgid != None:
1618 pass
1620 def provision(logger, session_info, credentials, smbconf=None,
1621 targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None,
1622 domaindn=None, schemadn=None, configdn=None, serverdn=None,
1623 domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None,
1624 next_rid=1000, dc_rid=None, adminpass=None, ldapadminpass=None, krbtgtpass=None,
1625 domainguid=None, policyguid=None, policyguid_dc=None,
1626 dns_backend=None, dnspass=None,
1627 invocationid=None, machinepass=None, ntdsguid=None,
1628 root=None, nobody=None, users=None, wheel=None, backup=None, aci=None,
1629 serverrole=None, dom_for_fun_level=None,
1630 backend_type=None, sitename=None,
1631 ol_mmr_urls=None, ol_olc=None, slapd_path="/bin/false",
1632 useeadb=False, am_rodc=False,
1633 lp=None, use_ntvfs=False,
1634 use_rfc2307=False, maxuid=None, maxgid=None):
1635 """Provision samba4
1637 :note: caution, this wipes all existing data!
1640 try:
1641 serverrole = sanitize_server_role(serverrole)
1642 except ValueError:
1643 raise ProvisioningError('server role (%s) should be one of "active directory domain controller", "member server", "standalone server"' % serverrole)
1645 if ldapadminpass is None:
1646 # Make a new, random password between Samba and it's LDAP server
1647 ldapadminpass = samba.generate_random_password(128, 255)
1649 if backend_type is None:
1650 backend_type = "ldb"
1652 if domainsid is None:
1653 domainsid = security.random_sid()
1654 else:
1655 domainsid = security.dom_sid(domainsid)
1657 root_uid = findnss_uid([root or "root"])
1658 nobody_uid = findnss_uid([nobody or "nobody"])
1659 users_gid = findnss_gid([users or "users", 'users', 'other', 'staff'])
1660 if wheel is None:
1661 wheel_gid = findnss_gid(["wheel", "adm"])
1662 else:
1663 wheel_gid = findnss_gid([wheel])
1664 try:
1665 bind_gid = findnss_gid(["bind", "named"])
1666 except KeyError:
1667 bind_gid = None
1669 if targetdir is not None:
1670 smbconf = os.path.join(targetdir, "etc", "smb.conf")
1671 elif smbconf is None:
1672 smbconf = samba.param.default_path()
1673 if not os.path.exists(os.path.dirname(smbconf)):
1674 os.makedirs(os.path.dirname(smbconf))
1676 server_services = []
1677 global_param = {}
1678 if use_rfc2307:
1679 global_param["idmap_ldb:use rfc2307"] = ["yes"]
1681 if dns_backend == "SAMBA_INTERNAL":
1682 server_services.append("+dns")
1684 if use_ntvfs:
1685 server_services.append("+smb")
1686 server_services.append("-s3fs")
1687 global_param["dcerpc endpoint servers"] = ["+winreg", "+srvsvc"]
1689 if len(server_services) > 0:
1690 global_param["server services"] = server_services
1692 # only install a new smb.conf if there isn't one there already
1693 if os.path.exists(smbconf):
1694 # if Samba Team members can't figure out the weird errors
1695 # loading an empty smb.conf gives, then we need to be smarter.
1696 # Pretend it just didn't exist --abartlet
1697 f = open(smbconf, 'r')
1698 try:
1699 data = f.read().lstrip()
1700 finally:
1701 f.close()
1702 if data is None or data == "":
1703 make_smbconf(smbconf, hostname, domain, realm,
1704 targetdir, serverrole=serverrole,
1705 eadb=useeadb, use_ntvfs=use_ntvfs,
1706 lp=lp, global_param=global_param)
1707 else:
1708 make_smbconf(smbconf, hostname, domain, realm, targetdir,
1709 serverrole=serverrole,
1710 eadb=useeadb, use_ntvfs=use_ntvfs, lp=lp, global_param=global_param)
1712 if lp is None:
1713 lp = samba.param.LoadParm()
1714 lp.load(smbconf)
1715 names = guess_names(lp=lp, hostname=hostname, domain=domain,
1716 dnsdomain=realm, serverrole=serverrole, domaindn=domaindn,
1717 configdn=configdn, schemadn=schemadn, serverdn=serverdn,
1718 sitename=sitename, rootdn=rootdn)
1719 paths = provision_paths_from_lp(lp, names.dnsdomain)
1721 paths.bind_gid = bind_gid
1722 paths.wheel_gid = wheel_gid
1724 if hostip is None:
1725 logger.info("Looking up IPv4 addresses")
1726 hostips = interface_ips_v4(lp)
1727 if len(hostips) > 0:
1728 hostip = hostips[0]
1729 if len(hostips) > 1:
1730 logger.warning("More than one IPv4 address found. Using %s",
1731 hostip)
1732 if hostip == "127.0.0.1":
1733 hostip = None
1734 if hostip is None:
1735 logger.warning("No IPv4 address will be assigned")
1737 if hostip6 is None:
1738 logger.info("Looking up IPv6 addresses")
1739 hostips = interface_ips_v6(lp, linklocal=False)
1740 if hostips:
1741 hostip6 = hostips[0]
1742 if len(hostips) > 1:
1743 logger.warning("More than one IPv6 address found. Using %s", hostip6)
1744 if hostip6 is None:
1745 logger.warning("No IPv6 address will be assigned")
1747 names.hostip = hostip
1748 names.hostip6 = hostip6
1750 if serverrole is None:
1751 serverrole = lp.get("server role")
1753 if not os.path.exists(paths.private_dir):
1754 os.mkdir(paths.private_dir)
1755 if not os.path.exists(os.path.join(paths.private_dir, "tls")):
1756 os.mkdir(os.path.join(paths.private_dir, "tls"))
1757 if not os.path.exists(paths.state_dir):
1758 os.mkdir(paths.state_dir)
1760 if paths.sysvol and not os.path.exists(paths.sysvol):
1761 os.makedirs(paths.sysvol, 0775)
1763 if not use_ntvfs and serverrole == "active directory domain controller":
1764 if paths.sysvol is None:
1765 raise MissingShareError("sysvol", paths.smbconf)
1767 if not smbd.have_posix_acls():
1768 # This clue is only strictly correct for RPM and
1769 # Debian-like Linux systems, but hopefully other users
1770 # will get enough clue from it.
1771 raise ProvisioningError("Samba was compiled without the posix ACL support that s3fs requires. Try installing libacl1-dev or libacl-devel, then re-run configure and make.")
1773 file = tempfile.NamedTemporaryFile(dir=os.path.abspath(paths.sysvol))
1774 try:
1775 try:
1776 smbd.set_simple_acl(file.name, root_uid, wheel_gid)
1777 except Exception:
1778 raise ProvisioningError("Your filesystem or build does not support posix ACLs, which s3fs requires. Try the mounting the filesystem with the 'acl' option.")
1779 finally:
1780 file.close()
1782 ldapi_url = "ldapi://%s" % urllib.quote(paths.s4_ldapi_path, safe="")
1784 schema = Schema(domainsid, invocationid=invocationid,
1785 schemadn=names.schemadn)
1787 if backend_type == "ldb":
1788 provision_backend = LDBBackend(backend_type, paths=paths,
1789 lp=lp, credentials=credentials,
1790 names=names, logger=logger)
1791 elif backend_type == "existing":
1792 # If support for this is ever added back, then the URI will need to be specified again
1793 provision_backend = ExistingBackend(backend_type, paths=paths,
1794 lp=lp, credentials=credentials,
1795 names=names, logger=logger,
1796 ldap_backend_forced_uri=None)
1797 elif backend_type == "fedora-ds":
1798 provision_backend = FDSBackend(backend_type, paths=paths,
1799 lp=lp, credentials=credentials,
1800 names=names, logger=logger, domainsid=domainsid,
1801 schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
1802 slapd_path=slapd_path,
1803 root=root)
1804 elif backend_type == "openldap":
1805 provision_backend = OpenLDAPBackend(backend_type, paths=paths,
1806 lp=lp, credentials=credentials,
1807 names=names, logger=logger, domainsid=domainsid,
1808 schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
1809 slapd_path=slapd_path, ol_mmr_urls=ol_mmr_urls)
1810 else:
1811 raise ValueError("Unknown LDAP backend type selected")
1813 provision_backend.init()
1814 provision_backend.start()
1816 # only install a new shares config db if there is none
1817 if not os.path.exists(paths.shareconf):
1818 logger.info("Setting up share.ldb")
1819 share_ldb = Ldb(paths.shareconf, session_info=session_info, lp=lp)
1820 share_ldb.load_ldif_file_add(setup_path("share.ldif"))
1822 logger.info("Setting up secrets.ldb")
1823 secrets_ldb = setup_secretsdb(paths,
1824 session_info=session_info,
1825 backend_credentials=provision_backend.secrets_credentials, lp=lp)
1827 try:
1828 logger.info("Setting up the registry")
1829 setup_registry(paths.hklm, session_info, lp=lp)
1831 logger.info("Setting up the privileges database")
1832 setup_privileges(paths.privilege, session_info, lp=lp)
1834 logger.info("Setting up idmap db")
1835 idmap = setup_idmapdb(paths.idmapdb, session_info=session_info, lp=lp)
1837 setup_name_mappings(idmap, sid=str(domainsid),
1838 root_uid=root_uid, nobody_uid=nobody_uid,
1839 users_gid=users_gid, wheel_gid=wheel_gid)
1841 logger.info("Setting up SAM db")
1842 samdb = setup_samdb(paths.samdb, session_info,
1843 provision_backend, lp, names, logger=logger,
1844 serverrole=serverrole,
1845 schema=schema, fill=samdb_fill, am_rodc=am_rodc)
1847 if serverrole == "active directory domain controller":
1848 if paths.netlogon is None:
1849 raise MissingShareError("netlogon", paths.smbconf)
1851 if paths.sysvol is None:
1852 raise MissingShareError("sysvol", paths.smbconf)
1854 if not os.path.isdir(paths.netlogon):
1855 os.makedirs(paths.netlogon, 0755)
1857 if adminpass is None:
1858 adminpass = samba.generate_random_password(12, 32)
1859 adminpass_generated = True
1860 else:
1861 adminpass_generated = False
1863 if samdb_fill == FILL_FULL:
1864 provision_fill(samdb, secrets_ldb, logger, names, paths,
1865 schema=schema, targetdir=targetdir, samdb_fill=samdb_fill,
1866 hostip=hostip, hostip6=hostip6, domainsid=domainsid,
1867 next_rid=next_rid, dc_rid=dc_rid, adminpass=adminpass,
1868 krbtgtpass=krbtgtpass, domainguid=domainguid,
1869 policyguid=policyguid, policyguid_dc=policyguid_dc,
1870 invocationid=invocationid, machinepass=machinepass,
1871 ntdsguid=ntdsguid, dns_backend=dns_backend,
1872 dnspass=dnspass, serverrole=serverrole,
1873 dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,
1874 lp=lp)
1876 create_krb5_conf(paths.krb5conf,
1877 dnsdomain=names.dnsdomain, hostname=names.hostname,
1878 realm=names.realm)
1879 logger.info("A Kerberos configuration suitable for Samba 4 has been "
1880 "generated at %s", paths.krb5conf)
1882 if serverrole == "active directory domain controller":
1883 create_dns_update_list(lp, logger, paths)
1885 backend_result = provision_backend.post_setup()
1886 provision_backend.shutdown()
1888 create_phpldapadmin_config(paths.phpldapadminconfig,
1889 ldapi_url)
1890 except:
1891 secrets_ldb.transaction_cancel()
1892 raise
1894 # Now commit the secrets.ldb to disk
1895 secrets_ldb.transaction_commit()
1897 # the commit creates the dns.keytab, now chown it
1898 dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab)
1899 if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None:
1900 try:
1901 os.chmod(dns_keytab_path, 0640)
1902 os.chown(dns_keytab_path, -1, paths.bind_gid)
1903 except OSError:
1904 if not os.environ.has_key('SAMBA_SELFTEST'):
1905 logger.info("Failed to chown %s to bind gid %u",
1906 dns_keytab_path, paths.bind_gid)
1908 result = ProvisionResult()
1909 result.server_role = serverrole
1910 result.domaindn = domaindn
1911 result.paths = paths
1912 result.names = names
1913 result.lp = lp
1914 result.samdb = samdb
1915 result.idmap = idmap
1916 result.domainsid = str(domainsid)
1918 if samdb_fill == FILL_FULL:
1919 result.adminpass_generated = adminpass_generated
1920 result.adminpass = adminpass
1921 else:
1922 result.adminpass_generated = False
1923 result.adminpass = None
1925 result.backend_result = backend_result
1927 if use_rfc2307:
1928 provision_fake_ypserver(logger=logger, samdb=samdb, domaindn=names.domaindn, netbiosname=names.netbiosname,
1929 nisdomain=(names.domain).lower(), maxuid=maxuid, maxgid=maxgid)
1931 return result
1934 def provision_become_dc(smbconf=None, targetdir=None,
1935 realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None,
1936 serverdn=None, domain=None, hostname=None, domainsid=None,
1937 adminpass=None, krbtgtpass=None, domainguid=None, policyguid=None,
1938 policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None,
1939 dns_backend=None, root=None, nobody=None, users=None, wheel=None,
1940 backup=None, serverrole=None, ldap_backend=None,
1941 ldap_backend_type=None, sitename=None, debuglevel=1):
1943 logger = logging.getLogger("provision")
1944 samba.set_debug_level(debuglevel)
1946 res = provision(logger, system_session(), None,
1947 smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,
1948 realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn,
1949 configdn=configdn, serverdn=serverdn, domain=domain,
1950 hostname=hostname, hostip=None, domainsid=domainsid,
1951 machinepass=machinepass, serverrole="active directory domain controller",
1952 sitename=sitename, dns_backend=dns_backend, dnspass=dnspass)
1953 res.lp.set("debuglevel", str(debuglevel))
1954 return res
1957 def create_phpldapadmin_config(path, ldapi_uri):
1958 """Create a PHP LDAP admin configuration file.
1960 :param path: Path to write the configuration to.
1962 setup_file(setup_path("phpldapadmin-config.php"), path,
1963 {"S4_LDAPI_URI": ldapi_uri})
1966 def create_krb5_conf(path, dnsdomain, hostname, realm):
1967 """Write out a file containing zone statements suitable for inclusion in a
1968 named.conf file (including GSS-TSIG configuration).
1970 :param path: Path of the new named.conf file.
1971 :param dnsdomain: DNS Domain name
1972 :param hostname: Local hostname
1973 :param realm: Realm name
1975 setup_file(setup_path("krb5.conf"), path, {
1976 "DNSDOMAIN": dnsdomain,
1977 "HOSTNAME": hostname,
1978 "REALM": realm,
1982 class ProvisioningError(Exception):
1983 """A generic provision error."""
1985 def __init__(self, value):
1986 self.value = value
1988 def __str__(self):
1989 return "ProvisioningError: " + self.value
1992 class InvalidNetbiosName(Exception):
1993 """A specified name was not a valid NetBIOS name."""
1995 def __init__(self, name):
1996 super(InvalidNetbiosName, self).__init__(
1997 "The name '%r' is not a valid NetBIOS name" % name)
2000 class MissingShareError(ProvisioningError):
2002 def __init__(self, name, smbconf):
2003 super(MissingShareError, self).__init__(
2004 "Existing smb.conf does not have a [%s] share, but you are "
2005 "configuring a DC. Please remove %s or add the share manually." %
2006 (name, smbconf))