3 # Helpers for provision stuff
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2009-2010
6 # Based on provision a Samba4 server by
7 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
8 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program. If not, see <http://www.gnu.org/licenses/>.
30 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE
34 from samba.dcerpc import misc, security
35 from samba.dsdb import DS_DOMAIN_FUNCTION_2000
36 from samba.provision import (ProvisionNames, provision_paths_from_lp,
37 FILL_FULL, provision, ProvisioningError)
38 from samba.ndr import ndr_unpack
41 def get_paths(param, targetdir=None, smbconf=None):
42 """Get paths to important provision objects (smb.conf, ldb files, ...)
44 :param param: Param object
45 :param targetdir: Directory where the provision is (or will be) stored
46 :param smbconf: Path to the smb.conf file
47 :return: A list with the path of important provision objects"""
48 if targetdir is not None:
49 etcdir = os.path.join(targetdir, "etc")
50 if not os.path.exists(etcdir):
52 smbconf = os.path.join(etcdir, "smb.conf")
54 smbconf = param.default_path()
56 if not os.path.exists(smbconf):
57 raise ProvisioningError("Unable to find smb.conf ...")
61 paths = provision_paths_from_lp(lp,lp.get("realm"))
65 def find_provision_key_parameters(param, credentials, session_info, paths,
67 """Get key provision parameters (realm, domain, ...) from a given provision
69 :param param: Param object
70 :param credentials: Credentials for the authentification
71 :param session_info: Session object
72 :param paths: A list of path to provision object
73 :param smbconf: Path to the smb.conf file
74 :return: A list of key provision parameters"""
77 lp.load(paths.smbconf)
78 names = ProvisionNames()
79 names.adminpass = None
80 # NT domain, kerberos realm, root dn, domain dn, domain dns name
81 names.domain = string.upper(lp.get("workgroup"))
82 names.realm = lp.get("realm")
83 basedn = "DC=" + names.realm.replace(".",",DC=")
84 names.dnsdomain = names.realm
85 names.realm = string.upper(names.realm)
87 secrets_ldb = Ldb(paths.secrets, session_info=session_info,
88 credentials=credentials,lp=lp, options=["modules:samba_secrets"])
89 # Get the netbiosname first (could be obtained from smb.conf in theory)
90 res = secrets_ldb.search(expression="(flatname=%s)"%names.domain,base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=["sAMAccountName"])
91 names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
93 names.smbconf = smbconf
94 # It's important here to let ldb load with the old module or it's quite
95 # certain that the LDB won't load ...
96 samdb = Ldb(paths.samdb, session_info=session_info,
97 credentials=credentials, lp=lp, options=["modules:samba_dsdb"])
99 # That's a bit simplistic but it's ok as long as we have only 3
101 current = samdb.search(expression="(objectClass=*)",
102 base="", scope=SCOPE_BASE,
103 attrs=["defaultNamingContext", "schemaNamingContext",
104 "configurationNamingContext","rootDomainNamingContext"])
106 names.configdn = current[0]["configurationNamingContext"]
107 configdn = str(names.configdn)
108 names.schemadn = current[0]["schemaNamingContext"]
109 if ldb.Dn(samdb, basedn) != ldb.Dn(samdb, current[0]["defaultNamingContext"][0]):
110 raise ProvisioningError("basedn in %s (%s) and from %s (%s) is not the same ..." % (paths.samdb, str(current[0]["defaultNamingContext"][0]), paths.smbconf, basedn))
112 names.domaindn=current[0]["defaultNamingContext"]
113 names.rootdn=current[0]["rootDomainNamingContext"]
115 res3 = samdb.search(expression="(objectClass=*)",
116 base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=["cn"])
117 names.sitename = str(res3[0]["cn"])
119 # dns hostname and server dn
120 res4 = samdb.search(expression="(CN=%s)" % names.netbiosname,
121 base="OU=Domain Controllers,"+basedn, scope=SCOPE_ONELEVEL, attrs=["dNSHostName"])
122 names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
124 server_res = samdb.search(expression="serverReference=%s" % res4[0].dn,
125 attrs=[], base=configdn)
126 names.serverdn = server_res[0].dn
128 # invocation id/objectguid
129 res5 = samdb.search(expression="(objectClass=*)",
130 base="CN=NTDS Settings,%s" % str(names.serverdn), scope=SCOPE_BASE,
131 attrs=["invocationID", "objectGUID"])
132 names.invocation = str(ndr_unpack(misc.GUID, res5[0]["invocationId"][0]))
133 names.ntdsguid = str(ndr_unpack(misc.GUID, res5[0]["objectGUID"][0]))
136 res6 = samdb.search(expression="(objectClass=*)",base=basedn,
137 scope=SCOPE_BASE, attrs=["objectGUID",
138 "objectSid","msDS-Behavior-Version" ])
139 names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
140 names.domainsid = ndr_unpack( security.dom_sid,res6[0]["objectSid"][0])
141 if (res6[0].get("msDS-Behavior-Version") is None or
142 int(res6[0]["msDS-Behavior-Version"][0]) < DS_DOMAIN_FUNCTION_2000):
143 names.domainlevel = DS_DOMAIN_FUNCTION_2000
145 names.domainlevel = int(res6[0]["msDS-Behavior-Version"][0])
148 res7 = samdb.search(expression="(displayName=Default Domain Policy)",
149 base="CN=Policies,CN=System,"+basedn, scope=SCOPE_ONELEVEL,
150 attrs=["cn","displayName"])
151 names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
153 res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",
154 base="CN=Policies,CN=System,"+basedn, scope=SCOPE_ONELEVEL,
155 attrs=["cn","displayName"])
157 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
159 names.policyid_dc = None
164 def newprovision(names, setup_dir, creds, session, smbconf, provdir, logger):
165 """Create a new provision.
167 This provision will be the reference for knowing what has changed in the
168 since the latest upgrade in the current provision
170 :param names: List of provision parameters
171 :param setup_dis: Directory where the setup files are stored
172 :param creds: Credentials for the authentification
173 :param session: Session object
174 :param smbconf: Path to the smb.conf file
175 :param provdir: Directory where the provision will be stored
176 :param logger: A `Logger`
178 if os.path.isdir(provdir):
179 shutil.rmtree(provdir)
180 os.chdir(os.path.join(setup_dir,".."))
182 logger.info("Provision stored in %s", provdir)
183 provision(setup_dir, logger, session, creds, smbconf=smbconf,
184 targetdir=provdir, samdb_fill=FILL_FULL, realm=names.realm,
185 domain=names.domain, domainguid=names.domainguid,
186 domainsid=str(names.domainsid), ntdsguid=names.ntdsguid,
187 policyguid=names.policyid, policyguid_dc=names.policyid_dc,
188 hostname=names.netbiosname, hostip=None, hostip6=None,
189 invocationid=names.invocation, adminpass=names.adminpass,
190 krbtgtpass=None, machinepass=None, dnspass=None, root=None,
191 nobody=None, wheel=None, users=None,
192 serverrole="domain controller", ldap_backend_extra_port=None,
193 backend_type=None, ldapadminpass=None, ol_mmr_urls=None,
194 slapd_path=None, setup_ds_path=None, nosync=None,
195 dom_for_fun_level=names.domainlevel,
196 ldap_dryrun_mode=None, useeadb=True)
200 """Sorts two DNs in the lexicographical order it and put higher level DN
203 So given the dns cn=bar,cn=foo and cn=foo the later will be return as
206 :param x: First object to compare
207 :param y: Second object to compare
209 p = re.compile(r'(?<!\\),')
210 tab1 = p.split(str(x))
211 tab2 = p.split(str(y))
212 minimum = min(len(tab1), len(tab2))
215 # Note: python range go up to upper limit but do not include it
216 for i in range(0, minimum):
217 ret = cmp(tab1[len1-i], tab2[len2-i])
222 assert len1 != len2, "PB PB PB"+" ".join(tab1)+" / "+" ".join(tab2)