3 # Copyright (C) Matthieu Patou <mat@matws.net> 2009
5 # Based on provision a Samba4 server by
6 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
7 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
34 # Find right directory when running from source tree
35 sys.path.insert(0, "bin/python")
37 from base64 import b64encode
40 from samba.credentials import DONT_USE_KERBEROS
41 from samba.auth import system_session, admin_session
42 from samba import Ldb, DS_DOMAIN_FUNCTION_2000, DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008, DS_DC_FUNCTION_2008_R2
43 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError
45 import samba.getopt as options
46 from samba.samdb import SamDB
47 from samba import param
48 from samba import glue
49 from samba.provision import ProvisionNames,provision_paths_from_lp,find_setup_dir,FILL_FULL,provision, get_domain_descriptor, get_config_descriptor, secretsdb_self_join
50 from samba.provisionexceptions import ProvisioningError
51 from samba.schema import get_dnsyntax_attributes, get_linked_attributes, Schema, get_schema_descriptor
52 from samba.dcerpc import misc, security
53 from samba.ndr import ndr_pack, ndr_unpack
54 from samba.dcerpc.misc import SEC_CHAN_BDC
56 replace=2^ldb.FLAG_MOD_REPLACE
57 add=2^ldb.FLAG_MOD_ADD
58 delete=2^ldb.FLAG_MOD_DELETE
60 #Errors are always logged
69 # Attributes that not copied from the reference provision even if they do not exists in the destination object
70 # This is most probably because they are populated automatcally when object is created
71 hashAttrNotCopied = { "dn": 1,"whenCreated": 1,"whenChanged": 1,"objectGUID": 1,"replPropertyMetaData": 1,"uSNChanged": 1,\
72 "uSNCreated": 1,"parentGUID": 1,"objectCategory": 1,"distinguishedName": 1,\
73 "showInAdvancedViewOnly": 1,"instanceType": 1, "cn": 1, "msDS-Behavior-Version":1, "nextRid":1,\
74 "nTMixedDomain": 1,"versionNumber":1, "lmPwdHistory":1, "pwdLastSet": 1, "ntPwdHistory":1, "unicodePwd":1,\
75 "dBCSPwd":1,"supplementalCredentials":1,"gPCUserExtensionNames":1, "gPCMachineExtensionNames":1,\
76 "maxPwdAge":1, "mail":1, "secret":1,"possibleInferiors":1}
78 # Usually for an object that already exists we do not overwrite attributes as they might have been changed for good
79 # reasons. Anyway for a few of thems it's mandatory to replace them otherwise the provision will be broken somehow.
80 hashOverwrittenAtt = { "prefixMap": replace, "systemMayContain": replace,"systemOnly":replace, "searchFlags":replace,\
81 "mayContain":replace, "systemFlags":replace,
82 "oEMInformation":replace, "operatingSystemVersion":replace, "adminPropertyPages":replace,
83 "defaultSecurityDescriptor": replace}
86 def define_what_to_log(opts):
90 if opts.debugchangesd:
91 what = what | CHANGESD
94 if opts.debugprovision:
95 what = what | PROVISION
97 what = what | CHANGEALL
101 parser = optparse.OptionParser("provision [options]")
102 sambaopts = options.SambaOptions(parser)
103 parser.add_option_group(sambaopts)
104 parser.add_option_group(options.VersionOptions(parser))
105 credopts = options.CredentialsOptions(parser)
106 parser.add_option_group(credopts)
107 parser.add_option("--setupdir", type="string", metavar="DIR",
108 help="directory with setup files")
109 parser.add_option("--debugprovision", help="Debug provision", action="store_true")
110 parser.add_option("--debugguess", help="Print information on what is different but won't be changed", action="store_true")
111 parser.add_option("--debugchange", help="Print information on what is different but won't be changed", action="store_true")
112 parser.add_option("--debugchangesd", help="Print information security descriptors differences", action="store_true")
113 parser.add_option("--debugall", help="Print all available information (very verbose)", action="store_true")
114 parser.add_option("--full", help="Perform full upgrade of the samdb (schema, configuration, new objects, ...", action="store_true")
115 parser.add_option("--targetdir", type="string", metavar="DIR",
116 help="Set target directory")
118 opts = parser.parse_args()[0]
120 whatToLog = define_what_to_log(opts)
122 def messageprovision(text):
123 """print a message if quiet is not set."""
124 if opts.debugprovision or opts.debugall:
127 def message(what,text):
128 """print a message if quiet is not set."""
129 if (whatToLog & what) or (what <= 0 ):
132 if len(sys.argv) == 1:
133 opts.interactive = True
134 lp = sambaopts.get_loadparm()
135 smbconf = lp.configfile
137 creds = credopts.get_credentials(lp)
138 creds.set_kerberos_state(DONT_USE_KERBEROS)
139 setup_dir = opts.setupdir
140 if setup_dir is None:
141 setup_dir = find_setup_dir()
143 session = system_session()
145 # Create an array of backlinked attributes
146 def populate_backlink(newpaths,creds,session,schemadn):
147 newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
148 backlinked.extend(get_linked_attributes(ldb.Dn(newsam_ldb,str(schemadn)),newsam_ldb).values())
150 # Get Paths for important objects (ldb, keytabs ...)
151 def get_paths(targetdir=None,smbconf=None):
152 if targetdir is not None:
153 if (not os.path.exists(os.path.join(targetdir, "etc"))):
154 os.makedirs(os.path.join(targetdir, "etc"))
155 smbconf = os.path.join(targetdir, "etc", "smb.conf")
157 smbconf = param.default_path()
159 if not os.path.exists(smbconf):
160 message(ERROR,"Unable to find smb.conf ..")
164 lp = param.LoadParm()
166 # Normaly we need the domain name for this function but for our needs it's pointless
167 paths = provision_paths_from_lp(lp,"foo")
170 # This function guess(fetch) informations needed to make a fresh provision from the current provision
171 # It includes: realm, workgroup, partitions, netbiosname, domain guid, ...
172 def guess_names_from_current_provision(credentials,session_info,paths):
173 lp = param.LoadParm()
174 lp.load(paths.smbconf)
175 names = ProvisionNames()
176 # NT domain, kerberos realm, root dn, domain dn, domain dns name
177 names.domain = string.upper(lp.get("workgroup"))
178 names.realm = lp.get("realm")
179 basedn = "DC=" + names.realm.replace(".",",DC=")
180 names.dnsdomain = names.realm
181 names.realm = string.upper(names.realm)
183 secrets_ldb = Ldb(paths.secrets, session_info=session_info, credentials=credentials,lp=lp, options=["modules:samba_secrets"])
184 # Get the netbiosname first (could be obtained from smb.conf in theory)
185 attrs = ["sAMAccountName"]
186 res = secrets_ldb.search(expression="(flatname=%s)"%names.domain,base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=attrs)
187 names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
189 names.smbconf = smbconf
190 #It's important here to let ldb load with the old module or it's quite certain that the LDB won't load ...
191 samdb = Ldb(paths.samdb, session_info=session_info,
192 credentials=credentials, lp=lp, options=["modules:samba_dsdb"])
194 # That's a bit simplistic but it's ok as long as we have only 3 partitions
195 attrs2 = ["defaultNamingContext", "schemaNamingContext","configurationNamingContext","rootDomainNamingContext"]
196 res2 = samdb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
198 names.configdn = res2[0]["configurationNamingContext"]
199 configdn = str(names.configdn)
200 names.schemadn = res2[0]["schemaNamingContext"]
201 if not (ldb.Dn(samdb, basedn) == (ldb.Dn(samdb, res2[0]["defaultNamingContext"][0]))):
202 raise ProvisioningError(("basedn in %s (%s) and from %s (%s) is not the same ..." % (paths.samdb, str(res2[0]["defaultNamingContext"][0]), paths.smbconf, basedn)))
204 names.domaindn=res2[0]["defaultNamingContext"]
205 names.rootdn=res2[0]["rootDomainNamingContext"]
208 res3= samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=attrs3)
209 names.sitename = str(res3[0]["cn"])
211 # dns hostname and server dn
212 attrs4 = ["dNSHostName"]
213 res4= samdb.search(expression="(CN=%s)"%names.netbiosname,base="OU=Domain Controllers,"+basedn, \
214 scope=SCOPE_ONELEVEL, attrs=attrs4)
215 names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
217 server_res = samdb.search(expression="serverReference=%s"%res4[0].dn, attrs=[], base=configdn)
218 names.serverdn = server_res[0].dn
220 # invocation id/objectguid
221 res5 = samdb.search(expression="(objectClass=*)",base="CN=NTDS Settings,%s" % str(names.serverdn), scope=SCOPE_BASE, attrs=["invocationID","objectGUID"])
222 names.invocation = str(ndr_unpack( misc.GUID,res5[0]["invocationId"][0]))
223 names.ntdsguid = str(ndr_unpack( misc.GUID,res5[0]["objectGUID"][0]))
226 attrs6 = ["objectGUID", "objectSid","msDS-Behavior-Version" ]
227 res6 = samdb.search(expression="(objectClass=*)",base=basedn, scope=SCOPE_BASE, attrs=attrs6)
228 names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
229 names.domainsid = ndr_unpack( security.dom_sid,res6[0]["objectSid"][0])
230 if res6[0].get("msDS-Behavior-Version") == None or int(res6[0]["msDS-Behavior-Version"][0]) < DS_DOMAIN_FUNCTION_2000:
231 names.domainlevel = DS_DOMAIN_FUNCTION_2000
233 names.domainlevel = int(res6[0]["msDS-Behavior-Version"][0])
236 attrs7 = ["cn","displayName"]
237 res7 = samdb.search(expression="(displayName=Default Domain Policy)",base="CN=Policies,CN=System,"+basedn, \
238 scope=SCOPE_ONELEVEL, attrs=attrs7)
239 names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
241 attrs8 = ["cn","displayName"]
242 res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",base="CN=Policies,CN=System,"+basedn, \
243 scope=SCOPE_ONELEVEL, attrs=attrs7)
245 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
247 names.policyid_dc = None
253 def print_names(names):
254 message(GUESS, "rootdn :"+str(names.rootdn))
255 message(GUESS, "configdn :"+str(names.configdn))
256 message(GUESS, "schemadn :"+str(names.schemadn))
257 message(GUESS, "serverdn :"+str(names.serverdn))
258 message(GUESS, "netbiosname :"+names.netbiosname)
259 message(GUESS, "defaultsite :"+names.sitename)
260 message(GUESS, "dnsdomain :"+names.dnsdomain)
261 message(GUESS, "hostname :"+names.hostname)
262 message(GUESS, "domain :"+names.domain)
263 message(GUESS, "realm :"+names.realm)
264 message(GUESS, "invocationid:"+names.invocation)
265 message(GUESS, "policyguid :"+names.policyid)
266 message(GUESS, "policyguiddc:"+str(names.policyid_dc))
267 message(GUESS, "domainsid :"+str(names.domainsid))
268 message(GUESS, "domainguid :"+names.domainguid)
269 message(GUESS, "ntdsguid :"+names.ntdsguid)
270 message(GUESS, "domainlevel :"+str(names.domainlevel))
272 # Create a fresh new reference provision
273 # This provision will be the reference for knowing what has changed in the
274 # since the latest upgrade in the current provision
275 def newprovision(names,setup_dir,creds,session,smbconf):
276 message(SIMPLE, "Creating a reference provision")
277 provdir=tempfile.mkdtemp(dir=paths.private_dir, prefix="referenceprovision")
278 if os.path.isdir(provdir):
280 logstd=os.path.join(provdir,"log.std")
281 os.chdir(os.path.join(setup_dir,".."))
284 sys.stderr = open("%s/provision.log"%provdir, "w")
285 message(PROVISION, "Reference provision stored in %s"%provdir)
286 message(PROVISION, "STDERR message of provision will be logged in %s/provision.log"%provdir)
287 sys.stderr = open("/dev/stdout", "w")
288 provision(setup_dir, messageprovision,
289 session, creds, smbconf=smbconf, targetdir=provdir,
290 samdb_fill=FILL_FULL, realm=names.realm, domain=names.domain,
291 domainguid=names.domainguid, domainsid=str(names.domainsid),ntdsguid=names.ntdsguid,
292 policyguid=names.policyid,policyguid_dc=names.policyid_dc,hostname=names.netbiosname,
293 hostip=None, hostip6=None,
294 invocationid=names.invocation, adminpass=None,
295 krbtgtpass=None, machinepass=None,
296 dnspass=None, root=None, nobody=None,
297 wheel=None, users=None,
298 serverrole="domain controller",
299 ldap_backend_extra_port=None,
306 dom_for_fun_level=names.domainlevel,
307 ldap_dryrun_mode=None)
310 # This function sorts two dn in the lexicographical order and put higher level DN before
311 # So given the dns cn=bar,cn=foo and cn=foo the later will be return as smaller (-1) as it has less
314 p = re.compile(r'(?<!\\),')
315 tab1 = p.split(str(x))
316 tab2 = p.split(str(y))
318 if (len(tab1) > len(tab2)):
320 elif (len(tab1) < len(tab2)):
327 # Note: python range go up to upper limit but do not include it
328 for i in range(0,min):
329 ret=cmp(tab1[len1-i],tab2[len2-i])
335 message(ERROR,"PB PB PB"+space.join(tab1)+" / "+space.join(tab2))
342 # check from security descriptors modifications return 1 if it is 0 otherwise
343 # it also populate hash structure for later use in the upgrade process
344 def handle_security_desc(ischema,att,msgElt,hashallSD,old,new):
345 if ischema == 1 and att == "defaultSecurityDescriptor" and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
347 hashSD["oldSD"] = old[0][att]
348 hashSD["newSD"] = new[0][att]
349 hashallSD[str(old[0].dn)] = hashSD
351 if att == "nTSecurityDescriptor" and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
354 hashSD["oldSD"] = ndr_unpack(security.descriptor,str(old[0][att]))
355 hashSD["newSD"] = ndr_unpack(security.descriptor,str(new[0][att]))
356 hashallSD[str(old[0].dn)] = hashSD
360 # Hangle special cases ... That's when we want to update an attribute only
361 # if it has a certain value or if it's for a certain object or
363 # It can be also if we want to do a merge of value instead of a simple replace
364 def handle_special_case(att,delta,new,old,ischema):
365 flag = delta.get(att).flags()
366 if (att == "gPLink" or att == "gPCFileSysPath") and flag == ldb.FLAG_MOD_REPLACE and str(new[0].dn).lower() == str(old[0].dn).lower():
369 if att == "forceLogoff":
370 ref=0x8000000000000000
371 oldval=int(old[0][att][0])
372 newval=int(new[0][att][0])
373 ref == old and ref == abs(new)
375 if (att == "adminDisplayName" or att == "adminDescription") and ischema:
377 if (str(old[0].dn) == "CN=Samba4-Local-Domain,%s"%(str(names.schemadn)) and att == "defaultObjectCategory" and flag == ldb.FLAG_MOD_REPLACE):
379 if (str(old[0].dn) == "CN=S-1-5-11,CN=ForeignSecurityPrincipals,%s"%(str(names.rootdn)) and att == "description" and flag == ldb.FLAG_MOD_DELETE):
381 if (str(old[0].dn) == "CN=Title,%s"%(str(names.schemadn)) and att == "rangeUpper" and flag == ldb.FLAG_MOD_REPLACE):
383 if ( (att == "member" or att == "servicePrincipalName") and flag == ldb.FLAG_MOD_REPLACE):
388 for elem in old[0][att]:
390 newval.append(str(elem))
392 for elem in new[0][att]:
393 if not hash.has_key(str(elem)):
395 newval.append(str(elem))
397 delta[att] = ldb.MessageElement(newval, ldb.FLAG_MOD_REPLACE, att)
401 if (str(old[0].dn) == "%s"%(str(names.rootdn)) and att == "subRefs" and flag == ldb.FLAG_MOD_REPLACE):
403 if str(delta.dn).endswith("CN=DisplaySpecifiers,%s"%names.configdn):
407 def update_secrets(newpaths,paths,creds,session):
408 message(SIMPLE,"update secrets.ldb")
409 newsecrets_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
410 secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp, options=["modules:samba_secrets"])
411 res = newsecrets_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
412 res2 = secrets_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
413 delta = secrets_ldb.msg_diff(res2[0],res[0])
414 delta.dn = res2[0].dn
415 secrets_ldb.modify(delta)
417 newsecrets_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
418 secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
419 res = newsecrets_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
420 res2 = secrets_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
426 empty = ldb.Message()
427 for i in range(0,len(res)):
428 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
430 # Create a hash for speeding the search of existing object in the current provision
431 for i in range(0,len(res2)):
432 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
434 for k in hash_new.keys():
435 if not hash.has_key(k):
436 listMissing.append(hash_new[k])
438 listPresent.append(hash_new[k])
439 for entry in listMissing:
440 res = newsecrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
441 res2 = secrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
442 delta = secrets_ldb.msg_diff(empty,res[0])
443 for att in hashAttrNotCopied.keys():
445 message(CHANGE,"Entry %s is missing from secrets.ldb"%res[0].dn)
447 message(CHANGE," Adding attribute %s"%att)
449 secrets_ldb.add(delta)
451 for entry in listPresent:
452 res = newsecrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
453 res2 = secrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
454 delta = secrets_ldb.msg_diff(res2[0],res[0])
456 for att in hashAttrNotCopied.keys():
461 message(CHANGE," Adding/Changing attribute %s to %s"%(att,res2[0].dn))
463 delta.dn = res2[0].dn
464 secrets_ldb.modify(delta)
466 # Check difference between the current provision and the reference provision.
467 # It looks for all object which base DN is name if ischema is false then scan is done in
468 # cross partition mode.
469 # If ischema is true, then special handling is done for dealing with schema
470 def check_diff_name(newpaths,paths,creds,session,basedn,names,ischema):
478 # Connect to the reference provision and get all the attribute in the partition referred by name
479 newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
480 sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp, options=["modules:samba_dsdb"])
482 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
483 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
485 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
486 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
488 # Create a hash for speeding the search of new object
489 for i in range(0,len(res)):
490 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
492 # Create a hash for speeding the search of existing object in the current provision
493 for i in range(0,len(res2)):
494 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
496 for k in hash_new.keys():
497 if not hash.has_key(k):
498 listMissing.append(hash_new[k])
500 listPresent.append(hash_new[k])
502 # Sort the missing object in order to have object of the lowest level first (which can be
503 # containers for higher level objects)
504 listMissing.sort(dn_sort)
505 listPresent.sort(dn_sort)
508 # The following lines (up to the for loop) is to load the up to date schema into our current LDB
509 # a complete schema is needed as the insertion of attributes and class is done against it
510 # and the schema is self validated
511 # The double ldb open and schema validation is taken from the initial provision script
512 # it's not certain that it is really needed ....
513 sam_ldb = Ldb(session_info=session, credentials=creds, lp=lp)
514 schema = Schema(setup_path, names.domainsid, schemadn=basedn, serverdn=str(names.serverdn))
515 # Load the schema from the one we computed earlier
516 sam_ldb.set_schema_from_ldb(schema.ldb)
517 # And now we can connect to the DB - the schema won't be loaded from the DB
518 sam_ldb.connect(paths.samdb)
519 sam_ldb.transaction_start()
521 sam_ldb.transaction_start()
523 empty = ldb.Message()
524 message(SIMPLE,"There are %d missing objects"%(len(listMissing)))
525 for dn in listMissing:
526 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
527 delta = sam_ldb.msg_diff(empty,res[0])
528 for att in hashAttrNotCopied.keys():
530 for att in backlinked:
534 sam_ldb.add(delta,["relax:0"])
537 for dn in listPresent:
538 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
539 res2 = sam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
540 delta = sam_ldb.msg_diff(res2[0],res[0])
541 for att in hashAttrNotCopied.keys():
543 for att in backlinked:
545 delta.remove("parentGUID")
548 msgElt = delta.get(att)
551 if handle_security_desc(ischema,att,msgElt,hashallSD,res2,res):
554 if (not hashOverwrittenAtt.has_key(att) or not (hashOverwrittenAtt.get(att)&2^msgElt.flags())):
555 if handle_special_case(att,delta,res,res2,ischema)==0 and msgElt.flags()!=ldb.FLAG_MOD_ADD:
558 message(CHANGE, "dn= "+str(dn)+ " "+att + " with flag "+str(msgElt.flags())+ " is not allowed to be changed/removed, I discard this change ...")
559 for e in range(0,len(res2[0][att])):
560 message(CHANGE,"old %d : %s"%(i,str(res2[0][att][e])))
561 if msgElt.flags() == 2:
563 for e in range(0,len(res[0][att])):
564 message(CHANGE,"new %d : %s"%(i,str(res[0][att][e])))
567 if len(delta.items()) >1:
568 attributes=",".join(delta.keys())
569 message(CHANGE,"%s is different from the reference one, changed attributes: %s"%(dn,attributes))
570 changed = changed + 1
571 sam_ldb.modify(delta)
573 sam_ldb.transaction_commit()
574 message(SIMPLE,"There are %d changed objects"%(changed))
577 # Check that SD are correct
578 def check_updated_sd(newpaths,paths,creds,session,names):
579 newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
580 sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
581 res = newsam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
582 res2 = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
584 for i in range(0,len(res)):
585 hash_new[str(res[i]["dn"]).lower()] = ndr_unpack(security.descriptor,str(res[i]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
587 for i in range(0,len(res2)):
588 key = str(res2[i]["dn"]).lower()
589 if hash_new.has_key(key):
590 sddl = ndr_unpack(security.descriptor,str(res2[i]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
591 if sddl != hash_new[key]:
592 print "%s new sddl/sddl in ref"%key
593 print "%s\n%s"%(sddl,hash_new[key])
595 # Simple update method for updating the SD that rely on the fact that nobody should have modified the SD
596 # This assumption is safe right now (alpha9) but should be removed asap
597 def update_sd(newpaths,paths,creds,session,names):
598 sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
599 sam_ldb.transaction_start()
600 # First update the SD for the rootdn
601 sam_ldb.set_session_info(session)
602 res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
603 delta = ldb.Message()
604 delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
605 descr = get_domain_descriptor(names.domainsid)
606 delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
607 sam_ldb.modify(delta,["recalculate_sd:0"])
609 res = sam_ldb.search(expression="objectClass=*",base=str(names.configdn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
610 delta = ldb.Message()
611 delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
612 descr = get_config_descriptor(names.domainsid)
613 delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
614 sam_ldb.modify(delta,["recalculate_sd:0"])
616 res = sam_ldb.search(expression="objectClass=*",base=str(names.schemadn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
617 delta = ldb.Message()
618 delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
619 descr = get_schema_descriptor(names.domainsid)
620 delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
621 sam_ldb.modify(delta,["recalculate_sd:0"])
625 res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
627 if not (str(obj["dn"]) == str(names.rootdn) or
628 str(obj["dn"]) == str(names.configdn) or \
629 str(obj["dn"]) == str(names.schemadn)):
630 hash[str(obj["dn"])] = obj["whenCreated"]
632 listkeys = hash.keys()
633 listkeys.sort(dn_sort)
637 delta = ldb.Message()
638 delta.dn = ldb.Dn(sam_ldb,key)
639 delta["whenCreated"] = ldb.MessageElement( hash[key],ldb.FLAG_MOD_REPLACE,"whenCreated" )
640 sam_ldb.modify(delta,["recalculate_sd:0"])
642 sam_ldb.transaction_cancel()
643 res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
644 print "bad stuff" +ndr_unpack(security.descriptor,str(res[0]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
646 sam_ldb.transaction_commit()
649 for root, dirs, files in os.walk(topdir, topdown=False):
651 os.remove(os.path.join(root, name))
653 os.rmdir(os.path.join(root, name))
657 def update_basesamdb(newpaths,paths,names):
658 message(SIMPLE,"Copy samdb")
659 shutil.copy(newpaths.samdb,paths.samdb)
661 message(SIMPLE,"Update partitions filename if needed")
662 schemaldb=os.path.join(paths.private_dir,"schema.ldb")
663 configldb=os.path.join(paths.private_dir,"configuration.ldb")
664 usersldb=os.path.join(paths.private_dir,"users.ldb")
665 samldbdir=os.path.join(paths.private_dir,"sam.ldb.d")
667 if not os.path.isdir(samldbdir):
669 os.chmod(samldbdir,0700)
670 if os.path.isfile(schemaldb):
671 shutil.copy(schemaldb,os.path.join(samldbdir,"%s.ldb"%str(names.schemadn).upper()))
673 if os.path.isfile(usersldb):
674 shutil.copy(usersldb,os.path.join(samldbdir,"%s.ldb"%str(names.rootdn).upper()))
676 if os.path.isfile(configldb):
677 shutil.copy(configldb,os.path.join(samldbdir,"%s.ldb"%str(names.configdn).upper()))
680 def update_privilege(newpaths,paths):
681 message(SIMPLE,"Copy privilege")
682 shutil.copy(os.path.join(newpaths.private_dir,"privilege.ldb"),os.path.join(paths.private_dir,"privilege.ldb"))
684 # For each partition check the differences
685 def update_samdb(newpaths,paths,creds,session,names):
687 message(SIMPLE, "Doing schema update")
688 hashdef = check_diff_name(newpaths,paths,creds,session,str(names.schemadn),names,1)
689 message(SIMPLE,"Done with schema update")
690 message(SIMPLE,"Scanning whole provision for updates and additions")
691 hashSD = check_diff_name(newpaths,paths,creds,session,str(names.rootdn),names,0)
692 message(SIMPLE,"Done with scanning")
694 def update_machine_account_password(paths,creds,session,names):
696 secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
697 secrets_ldb.transaction_start()
698 secrets_msg = secrets_ldb.search(expression=("samAccountName=%s$" % names.netbiosname), attrs=["secureChannelType"])
699 sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
700 sam_ldb.transaction_start()
701 if int(secrets_msg[0]["secureChannelType"][0]) == SEC_CHAN_BDC:
702 res = sam_ldb.search(expression=("samAccountName=%s$" % names.netbiosname), attrs=[])
703 assert(len(res) == 1)
705 msg = ldb.Message(res[0].dn)
706 machinepass = glue.generate_random_str(12)
707 msg["userPassword"] = ldb.MessageElement(machinepass, ldb.FLAG_MOD_REPLACE, "userPassword")
710 res = sam_ldb.search(expression=("samAccountName=%s$" % names.netbiosname),
711 attrs=["msDs-keyVersionNumber"])
712 assert(len(res) == 1)
713 kvno = int(str(res[0]["msDs-keyVersionNumber"]))
715 secretsdb_self_join(secrets_ldb, domain=names.domain,
717 domainsid=names.domainsid,
718 dnsdomain=names.dnsdomain,
719 netbiosname=names.netbiosname,
720 machinepass=machinepass,
721 key_version_number=kvno,
722 secure_channel_type=int(secrets_msg[0]["secureChannelType"][0]))
723 sam_ldb.transaction_prepare_commit()
724 secrets_ldb.transaction_prepare_commit()
725 sam_ldb.transaction_commit()
726 secrets_ldb.transaction_commit()
728 secrets_ldb.transaction_cancel()
730 # From here start the big steps of the program
731 # First get files paths
732 paths=get_paths(targetdir=opts.targetdir,smbconf=smbconf)
733 paths.setup = setup_dir
734 def setup_path(file):
735 return os.path.join(setup_dir, file)
736 # Guess all the needed names (variables in fact) from the current
738 names = guess_names_from_current_provision(creds,session,paths)
741 # With all this information let's create a fresh new provision used as reference
742 provisiondir = newprovision(names,setup_dir,creds,session,smbconf)
743 # Get file paths of this new provision
744 newpaths = get_paths(targetdir=provisiondir)
745 populate_backlink(newpaths,creds,session,names.schemadn)
746 # Check the difference
747 update_basesamdb(newpaths,paths,names)
748 update_secrets(newpaths,paths,creds,session)
749 update_privilege(newpaths,paths)
750 update_machine_account_password(paths,creds,session,names)
753 update_samdb(newpaths,paths,creds,session,names)
754 # SD should be created with admin but as some previous acl were so wrong that admin can't modify them we have first
755 # to recreate them with the good form but with system account and then give the ownership to admin ...
756 admin_session_info = admin_session(lp, str(names.domainsid))
757 update_sd(newpaths,paths,creds,session,names)
758 update_sd(newpaths,paths,creds,admin_session_info,names)
759 check_updated_sd(newpaths,paths,creds,session,names)
760 message(SIMPLE,"Upgrade finished !")
761 # remove reference provision now that everything is done !