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/>.
33 # Allow to run from s4 source directory (without installing samba)
34 sys.path.insert(0, "bin/python")
38 import samba.getopt as options
39 from samba.credentials import DONT_USE_KERBEROS
40 from samba.auth import system_session, admin_session
41 from ldb import (SCOPE_SUBTREE, SCOPE_BASE,
42 FLAG_MOD_REPLACE, FLAG_MOD_ADD, FLAG_MOD_DELETE,
43 MessageElement, Message, Dn)
44 from samba import param
45 from samba.provision import (find_setup_dir, get_domain_descriptor,
46 get_config_descriptor, secretsdb_self_join,
47 ProvisioningError, get_last_provision_usn,
48 get_max_usn, update_provision_usn)
49 from samba.schema import get_linked_attributes, Schema, get_schema_descriptor
50 from samba.dcerpc import security, drsblobs
51 from samba.ndr import ndr_unpack
52 from samba.dcerpc.misc import SEC_CHAN_BDC
53 from samba.upgradehelpers import (dn_sort, get_paths, newprovision,
54 find_provision_key_parameters, get_ldbs,
55 usn_in_range, identic_rename, get_diff_sddls,
56 update_secrets, CHANGE, ERROR, SIMPLE,
57 CHANGEALL, GUESS, CHANGESD, PROVISION,
58 updateOEMInfo, getOEMInfo, update_gpo,
59 delta_update_basesamdb, update_policyids)
61 replace=2**FLAG_MOD_REPLACE
63 delete=2**FLAG_MOD_DELETE
67 # Will be modified during provision to tell if default sd has been modified
70 #Errors are always logged
72 __docformat__ = "restructuredText"
74 # Attributes that are never copied from the reference provision (even if they
75 # do not exist in the destination object).
76 # This is most probably because they are populated automatcally when object is
78 # This also apply to imported object from reference provision
79 hashAttrNotCopied = { "dn": 1, "whenCreated": 1, "whenChanged": 1,
80 "objectGUID": 1, "uSNCreated": 1,
81 "replPropertyMetaData": 1, "uSNChanged": 1,
82 "parentGUID": 1, "objectCategory": 1,
83 "distinguishedName": 1, "nTMixedDomain": 1,
84 "showInAdvancedViewOnly": 1, "instanceType": 1,
85 "msDS-Behavior-Version":1, "nextRid":1, "cn": 1,
86 "versionNumber":1, "lmPwdHistory":1, "pwdLastSet": 1,
87 "ntPwdHistory":1, "unicodePwd":1,"dBCSPwd":1,
88 "supplementalCredentials":1, "gPCUserExtensionNames":1,
89 "gPCMachineExtensionNames":1,"maxPwdAge":1, "secret":1,
90 "possibleInferiors":1, "privilege":1,
93 # Usually for an object that already exists we do not overwrite attributes as
94 # they might have been changed for good reasons. Anyway for a few of them it's
95 # mandatory to replace them otherwise the provision will be broken somehow.
96 # But for attribute that are just missing we do not have to specify them as the default
97 # behavior is to add missing attribute
98 hashOverwrittenAtt = { "prefixMap": replace, "systemMayContain": replace,
99 "systemOnly":replace, "searchFlags":replace,
100 "mayContain":replace, "systemFlags":replace+add,
101 "description":replace, "operatingSystemVersion":replace,
102 "adminPropertyPages":replace, "groupType":replace,
103 "wellKnownObjects":replace, "privilege":never,
104 "defaultSecurityDescriptor": replace,
105 "rIDAvailablePool": never,
106 "defaultSecurityDescriptor": replace + add }
110 forwardlinked = set()
112 def define_what_to_log(opts):
116 if opts.debugchangesd:
117 what = what | CHANGESD
120 if opts.debugprovision:
121 what = what | PROVISION
123 what = what | CHANGEALL
127 parser = optparse.OptionParser("provision [options]")
128 sambaopts = options.SambaOptions(parser)
129 parser.add_option_group(sambaopts)
130 parser.add_option_group(options.VersionOptions(parser))
131 credopts = options.CredentialsOptions(parser)
132 parser.add_option_group(credopts)
133 parser.add_option("--setupdir", type="string", metavar="DIR",
134 help="directory with setup files")
135 parser.add_option("--debugprovision", help="Debug provision", action="store_true")
136 parser.add_option("--debugguess", action="store_true",
137 help="Print information on what is different but won't be changed")
138 parser.add_option("--debugchange", action="store_true",
139 help="Print information on what is different but won't be changed")
140 parser.add_option("--debugchangesd", action="store_true",
141 help="Print information security descriptors differences")
142 parser.add_option("--debugall", action="store_true",
143 help="Print all available information (very verbose)")
144 parser.add_option("--resetfileacl", action="store_true",
145 help="Force a reset on filesystem acls in sysvol / netlogon share")
146 parser.add_option("--full", action="store_true",
147 help="Perform full upgrade of the samdb (schema, configuration, new objects, ...")
149 opts = parser.parse_args()[0]
151 handler = logging.StreamHandler(sys.stdout)
152 upgrade_logger = logging.getLogger("upgradeprovision")
153 upgrade_logger.setLevel(logging.INFO)
155 upgrade_logger.addHandler(handler)
157 provision_logger = logging.getLogger("provision")
158 provision_logger.addHandler(handler)
160 whatToLog = define_what_to_log(opts)
162 def message(what, text):
163 """Print a message if this message type has been selected to be printed
165 :param what: Category of the message
166 :param text: Message to print """
167 if (whatToLog & what) or what <= 0:
168 upgrade_logger.info("%s", text)
170 if len(sys.argv) == 1:
171 opts.interactive = True
172 lp = sambaopts.get_loadparm()
173 smbconf = lp.configfile
175 creds = credopts.get_credentials(lp)
176 creds.set_kerberos_state(DONT_USE_KERBEROS)
177 setup_dir = opts.setupdir
178 if setup_dir is None:
179 setup_dir = find_setup_dir()
183 def check_for_DNS(refprivate, private):
184 """Check if the provision has already the requirement for dynamic dns
186 :param refprivate: The path to the private directory of the reference
188 :param private: The path to the private directory of the upgraded
191 spnfile = "%s/spn_update_list" % private
192 namedfile = lp.get("dnsupdate:path")
195 namedfile = "%s/named.conf.update" % private
197 if not os.path.exists(spnfile):
198 shutil.copy("%s/spn_update_list" % refprivate, "%s" % spnfile)
200 destdir = "%s/new_dns" % private
201 dnsdir = "%s/dns" % private
203 if not os.path.exists(namedfile):
204 if not os.path.exists(destdir):
206 if not os.path.exists(dnsdir):
208 shutil.copy("%s/named.conf" % refprivate, "%s/named.conf" % destdir)
209 shutil.copy("%s/named.txt" % refprivate, "%s/named.txt" % destdir)
210 message(SIMPLE, "It seems that you provision didn't integrate new rules "
211 "for dynamic dns update of domain related entries")
212 message(SIMPLE, "A copy of the new bind configuration files and "
213 "template as been put in %s, you should read them and configure dynamic "
214 " dns update" % destdir)
217 def populate_links(samdb, schemadn):
218 """Populate an array with all the back linked attributes
220 This attributes that are modified automaticaly when
221 front attibutes are changed
223 :param samdb: A LDB object for sam.ldb file
224 :param schemadn: DN of the schema for the partition"""
225 linkedAttHash = get_linked_attributes(Dn(samdb, str(schemadn)), samdb)
226 backlinked.extend(linkedAttHash.values())
227 for t in linkedAttHash.keys():
231 def populate_dnsyntax(samdb, schemadn):
232 """Populate an array with all the attributes that have DN synthax
235 :param samdb: A LDB object for sam.ldb file
236 :param schemadn: DN of the schema for the partition"""
237 res = samdb.search(expression="(attributeSyntax=2.5.5.1)", base=Dn(samdb,
238 str(schemadn)), scope=SCOPE_SUBTREE,
239 attrs=["lDAPDisplayName"])
241 dn_syntax_att.append(elem["lDAPDisplayName"])
244 def sanitychecks(samdb, names):
245 """Make some checks before trying to update
247 :param samdb: An LDB object opened on sam.ldb
248 :param names: list of key provision parameters
249 :return: Status of check (1 for Ok, 0 for not Ok) """
250 res = samdb.search(expression="objectClass=ntdsdsa", base=str(names.configdn),
251 scope=SCOPE_SUBTREE, attrs=["dn"],
252 controls=["search_options:1:2"])
254 print "No DC found, your provision is most probably hardly broken !"
257 print "Found %d domain controllers, for the moment upgradeprovision" \
258 "is not able to handle upgrade on domain with more than one DC, please demote" \
259 " the other(s) DC(s) before upgrading" % len(res)
265 def print_provision_key_parameters(names):
266 """Do a a pretty print of provision parameters
268 :param names: list of key provision parameters """
269 message(GUESS, "rootdn :" + str(names.rootdn))
270 message(GUESS, "configdn :" + str(names.configdn))
271 message(GUESS, "schemadn :" + str(names.schemadn))
272 message(GUESS, "serverdn :" + str(names.serverdn))
273 message(GUESS, "netbiosname :" + names.netbiosname)
274 message(GUESS, "defaultsite :" + names.sitename)
275 message(GUESS, "dnsdomain :" + names.dnsdomain)
276 message(GUESS, "hostname :" + names.hostname)
277 message(GUESS, "domain :" + names.domain)
278 message(GUESS, "realm :" + names.realm)
279 message(GUESS, "invocationid:" + names.invocation)
280 message(GUESS, "policyguid :" + names.policyid)
281 message(GUESS, "policyguiddc:" + str(names.policyid_dc))
282 message(GUESS, "domainsid :" + str(names.domainsid))
283 message(GUESS, "domainguid :" + names.domainguid)
284 message(GUESS, "ntdsguid :" + names.ntdsguid)
285 message(GUESS, "domainlevel :" + str(names.domainlevel))
288 def handle_special_case(att, delta, new, old, usn):
289 """Define more complicate update rules for some attributes
291 :param att: The attribute to be updated
292 :param delta: A messageElement object that correspond to the difference
293 between the updated object and the reference one
294 :param new: The reference object
295 :param old: The Updated object
296 :param usn: The highest usn modified by a previous (upgrade)provision
297 :return: True to indicate that the attribute should be kept, False for
300 flag = delta.get(att).flags()
301 # We do most of the special case handle if we do not have the
302 # highest usn as otherwise the replPropertyMetaData will guide us more
305 if (att == "member" and flag == FLAG_MOD_REPLACE):
309 for elem in old[0][att]:
310 hash[str(elem).lower()]=1
311 newval.append(str(elem))
313 for elem in new[0][att]:
314 if not hash.has_key(str(elem).lower()):
316 newval.append(str(elem))
318 delta[att] = MessageElement(newval, FLAG_MOD_REPLACE, att)
323 if (att in ("gPLink", "gPCFileSysPath") and
324 flag == FLAG_MOD_REPLACE and
325 str(new[0].dn).lower() == str(old[0].dn).lower()):
329 if att == "forceLogoff":
330 ref=0x8000000000000000
331 oldval=int(old[0][att][0])
332 newval=int(new[0][att][0])
333 ref == old and ref == abs(new)
336 if att in ("adminDisplayName", "adminDescription"):
339 if (str(old[0].dn) == "CN=Samba4-Local-Domain, %s" % (names.schemadn)
340 and att == "defaultObjectCategory" and flag == FLAG_MOD_REPLACE):
343 if (str(old[0].dn) == "CN=Title, %s" % (str(names.schemadn)) and
344 att == "rangeUpper" and flag == FLAG_MOD_REPLACE):
347 if (str(old[0].dn) == "%s" % (str(names.rootdn))
348 and att == "subRefs" and flag == FLAG_MOD_REPLACE):
351 if str(delta.dn).endswith("CN=DisplaySpecifiers, %s" % names.configdn):
354 # This is a bit of special animal as we might have added
355 # already SPN entries to the list that has to be modified
356 # So we go in detail to try to find out what has to be added ...
357 if (att == "servicePrincipalName" and flag == FLAG_MOD_REPLACE):
361 for elem in old[0][att]:
363 newval.append(str(elem))
365 for elem in new[0][att]:
366 if not hash.has_key(str(elem)):
368 newval.append(str(elem))
370 delta[att] = MessageElement(newval, FLAG_MOD_REPLACE, att)
377 def dump_denied_change(dn, att, flagtxt, current, reference):
378 """Print detailed information about why a changed is denied
380 :param dn: DN of the object which attribute is denied
381 :param att: Attribute that was supposed to be upgraded
382 :param flagtxt: Type of the update that should be performed
383 (add, change, remove, ...)
384 :param current: Value(s) of the current attribute
385 :param reference: Value(s) of the reference attribute"""
387 message(CHANGE, "dn= " + str(dn)+" " + att+" with flag " + flagtxt
388 +" is not allowed to be changed/removed, I discard this change")
389 if att != "objectSid" :
391 for e in range(0, len(current)):
392 message(CHANGE, "old %d : %s" % (i, str(current[e])))
394 if reference is not None:
396 for e in range(0, len(reference)):
397 message(CHANGE, "new %d : %s" % (i, str(reference[e])))
400 message(CHANGE, "old : %s" % ndr_unpack(security.dom_sid, current[0]))
401 message(CHANGE, "new : %s" % ndr_unpack(security.dom_sid, reference[0]))
404 def handle_special_add(samdb, dn, names):
405 """Handle special operation (like remove) on some object needed during
408 This is mostly due to wrong creation of the object in previous provision.
409 :param samdb: An Ldb object representing the SAM database
410 :param dn: DN of the object to inspect
411 :param names: list of key provision parameters
415 objDn = Dn(samdb, "CN=IIS_IUSRS, CN=Builtin, %s" % names.rootdn)
417 #This entry was misplaced lets remove it if it exists
418 dntoremove = "CN=IIS_IUSRS, CN=Users, %s" % names.rootdn
421 "CN=Certificate Service DCOM Access, CN=Builtin, %s" % names.rootdn)
423 #This entry was misplaced lets remove it if it exists
424 dntoremove = "CN=Certificate Service DCOM Access,"\
425 "CN=Users, %s" % names.rootdn
428 objDn = Dn(samdb, "CN=Cryptographic Operators, CN=Builtin, %s" % names.rootdn)
430 #This entry was misplaced lets remove it if it exists
431 dntoremove = "CN=Cryptographic Operators, CN=Users, %s" % names.rootdn
433 objDn = Dn(samdb, "CN=Event Log Readers, CN=Builtin, %s" % names.rootdn)
435 #This entry was misplaced lets remove it if it exists
436 dntoremove = "CN=Event Log Readers, CN=Users, %s" % names.rootdn
438 objDn = Dn(samdb,"CN=System,CN=WellKnown Security Principals,"
439 "CN=Configuration,%s" % names.rootdn)
441 oldDn = Dn(samdb,"CN=Well-Known-Security-Id-System,"
442 "CN=WellKnown Security Principals,"
443 "CN=Configuration,%s" % names.rootdn)
445 res = samdb.search(expression="(dn=%s)" % oldDn,
446 base=str(names.rootdn),
447 scope=SCOPE_SUBTREE, attrs=["dn"],
448 controls=["search_options:1:2"])
450 message(CHANGE, "Existing object %s must be replaced by %s,"
451 "Renaming old object" % (str(oldDn), str(dn)))
452 samdb.rename(oldDn, objDn)
456 if dntoremove is not None:
457 res = samdb.search(expression="(dn=%s)" % dntoremove,
458 base=str(names.rootdn),
459 scope=SCOPE_SUBTREE, attrs=["dn"],
460 controls=["search_options:1:2"])
462 message(CHANGE, "Existing object %s must be replaced by %s,"
463 "removing old object" % (dntoremove, str(dn)))
464 samdb.delete(res[0]["dn"])
468 def check_dn_nottobecreated(hash, index, listdn):
469 """Check if one of the DN present in the list has a creation order
470 greater than the current.
472 Hash is indexed by dn to be created, with each key
473 is associated the creation order.
475 First dn to be created has the creation order 0, second has 1, ...
476 Index contain the current creation order
478 :param hash: Hash holding the different DN of the object to be
480 :param index: Current creation order
481 :param listdn: List of DNs on which the current DN depends on
482 :return: None if the current object do not depend on other
483 object or if all object have been created before."""
487 key = str(dn).lower()
488 if hash.has_key(key) and hash[key] > index:
494 def add_missing_object(ref_samdb, samdb, dn, names, basedn, hash, index):
495 """Add a new object if the dependencies are satisfied
497 The function add the object if the object on which it depends are already
500 :param ref_samdb: Ldb object representing the SAM db of the reference
502 :param samdb: Ldb object representing the SAM db of the upgraded
504 :param dn: DN of the object to be added
505 :param names: List of key provision parameters
506 :param basedn: DN of the partition to be updated
507 :param hash: Hash holding the different DN of the object to be
509 :param index: Current creation order
510 :return: True if the object was created False otherwise"""
512 if handle_special_add(samdb, dn, names):
514 reference = ref_samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
515 scope=SCOPE_SUBTREE, controls=["search_options:1:2"])
517 delta = samdb.msg_diff(empty, reference[0])
519 if delta.get("objectSid"):
520 sid = str(ndr_unpack(security.dom_sid, str(reference[0]["objectSid"])))
521 m = re.match(r".*-(\d+)$", sid)
522 if m and int(m.group(1))>999:
523 delta.remove("objectSid")
524 for att in hashAttrNotCopied.keys():
526 for att in backlinked:
528 depend_on_yettobecreated = None
529 for att in dn_syntax_att:
530 depend_on_yet_tobecreated = check_dn_nottobecreated(hash, index,
532 if depend_on_yet_tobecreated is not None:
533 message(CHANGE, "Object %s depends on %s in attribute %s,"
534 "delaying the creation" % (dn,
535 depend_on_yet_tobecreated, att))
539 message(CHANGE,"Object %s will be added" % dn)
540 samdb.add(delta, ["relax:0"])
544 def gen_dn_index_hash(listMissing):
545 """Generate a hash associating the DN to its creation order
547 :param listMissing: List of DN
548 :return: Hash with DN as keys and creation order as values"""
550 for i in range(0, len(listMissing)):
551 hash[str(listMissing[i]).lower()] = i
554 def add_deletedobj_containers(ref_samdb, samdb, names):
555 """Add the object containter: CN=Deleted Objects
557 This function create the container for each partition that need one and
558 then reference the object into the root of the partition
560 :param ref_samdb: Ldb object representing the SAM db of the reference
562 :param samdb: Ldb object representing the SAM db of the upgraded provision
563 :param names: List of key provision parameters"""
566 wkoPrefix = "B:32:18E2EA80684F11D2B9AA00C04F79F805"
567 partitions = [str(names.rootdn), str(names.configdn)]
568 for part in partitions:
569 ref_delObjCnt = ref_samdb.search(expression="(cn=Deleted Objects)",
570 base=part, scope=SCOPE_SUBTREE,
572 controls=["show_deleted:0"])
573 delObjCnt = samdb.search(expression="(cn=Deleted Objects)",
574 base=part, scope=SCOPE_SUBTREE,
576 controls=["show_deleted:0"])
577 if len(ref_delObjCnt) > len(delObjCnt):
578 reference = ref_samdb.search(expression="cn=Deleted Objects",
579 base=part, scope=SCOPE_SUBTREE,
580 controls=["show_deleted:0"])
582 delta = samdb.msg_diff(empty, reference[0])
584 delta.dn = Dn(samdb, str(reference[0]["dn"]))
585 for att in hashAttrNotCopied.keys():
590 res = samdb.search(expression="(objectClass=*)", base=part,
592 attrs=["dn", "wellKnownObjects"])
594 targetWKO = "%s:%s" % (wkoPrefix, str(reference[0]["dn"]))
598 wko = res[0]["wellKnownObjects"]
600 # The wellKnownObject that we want to add.
602 if str(o) == targetWKO:
604 listwko.append(str(o))
607 listwko.append(targetWKO)
610 delta.dn = Dn(samdb, str(res[0]["dn"]))
611 delta["wellKnownObjects"] = MessageElement(listwko,
616 def add_missing_entries(ref_samdb, samdb, names, basedn, list):
617 """Add the missing object whose DN is the list
619 The function add the object if the objects on which it depends are
622 :param ref_samdb: Ldb object representing the SAM db of the reference
624 :param samdb: Ldb object representing the SAM db of the upgraded
626 :param dn: DN of the object to be added
627 :param names: List of key provision parameters
628 :param basedn: DN of the partition to be updated
629 :param list: List of DN to be added in the upgraded provision"""
634 while(len(listDefered) != len(listMissing) and len(listDefered) > 0):
636 listMissing = listDefered
638 hashMissing = gen_dn_index_hash(listMissing)
639 for dn in listMissing:
640 ret = add_missing_object(ref_samdb, samdb, dn, names, basedn,
644 # DN can't be created because it depends on some
645 # other DN in the list
646 listDefered.append(dn)
647 if len(listDefered) != 0:
648 raise ProvisioningError("Unable to insert missing elements:" \
649 "circular references")
651 def handle_links(samdb, att, basedn, dn, value, ref_value, delta):
652 """This function handle updates on links
654 :param samdb: An LDB object pointing to the updated provision
655 :param att: Attribute to update
656 :param basedn: The root DN of the provision
657 :param dn: The DN of the inspected object
658 :param value: The value of the attribute
659 :param ref_value: The value of this attribute in the reference provision
660 :param delta: The MessageElement object that will be applied for
661 transforming the current provision"""
663 res = samdb.search(expression="dn=%s" % dn, base=basedn,
664 controls=["search_options:1:2", "reveal:1"],
672 newlinklist.extend(value)
676 # for w2k domain level the reveal won't reveal anything ...
677 # it means that we can readd links that were removed on purpose ...
678 # Also this function in fact just accept add not removal
680 for e in res[0][att]:
681 if not hash.has_key(e):
682 # We put in the blacklist all the element that are in the "revealed"
683 # result and not in the "standard" result
684 # This element are links that were removed before and so that
685 # we don't wan't to readd
689 if not blacklist.has_key(e) and not hash.has_key(e):
690 newlinklist.append(str(e))
693 delta[att] = MessageElement(newlinklist, FLAG_MOD_REPLACE, att)
698 msg_elt_flag_strs = {
699 ldb.FLAG_MOD_ADD: "MOD_ADD",
700 ldb.FLAG_MOD_REPLACE: "MOD_REPLACE",
701 ldb.FLAG_MOD_DELETE: "MOD_DELETE" }
704 def update_present(ref_samdb, samdb, basedn, listPresent, usns, invocationid):
705 """ This function updates the object that are already present in the
708 :param ref_samdb: An LDB object pointing to the reference provision
709 :param samdb: An LDB object pointing to the updated provision
710 :param basedn: A string with the value of the base DN for the provision
712 :param listPresent: A list of object that is present in the provision
713 :param usns: A list of USN range modified by previous provision and
715 :param invocationid: The value of the invocationid for the current DC"""
718 # This hash is meant to speedup lookup of attribute name from an oid,
719 # it's for the replPropertyMetaData handling
721 res = samdb.search(expression="objectClass=attributeSchema", base=basedn,
722 controls=["search_options:1:2"], attrs=["attributeID",
726 strDisplay = str(e.get("lDAPDisplayName"))
727 hash_oid_name[str(e.get("attributeID"))] = strDisplay
729 msg = "Unable to insert missing elements: circular references"
730 raise ProvisioningError(msg)
733 controls = ["search_options:1:2", "sd_flags:1:2"]
734 for dn in listPresent:
735 reference = ref_samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
738 current = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
739 scope=SCOPE_SUBTREE, controls=controls)
742 (str(current[0].dn) != str(reference[0].dn)) and
743 (str(current[0].dn).upper() == str(reference[0].dn).upper())
745 message(CHANGE, "Name are the same but case change,"\
746 "let's rename %s to %s" % (str(current[0].dn),
747 str(reference[0].dn)))
748 identic_rename(samdb, reference[0].dn)
749 current = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
751 controls=["search_options:1:2"])
753 delta = samdb.msg_diff(current[0], reference[0])
755 for att in hashAttrNotCopied.keys():
758 for att in backlinked:
763 if len(delta.items()) > 1 and usns is not None:
764 # Fetch the replPropertyMetaData
765 res = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
766 scope=SCOPE_SUBTREE, controls=controls,
767 attrs=["replPropertyMetaData"])
768 ctr = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
769 str(res[0]["replPropertyMetaData"])).ctr
773 # We put in this hash only modification
774 # made on the current host
775 att = hash_oid_name[samdb.get_oid_from_attid(o.attid)]
776 if str(o.originating_invocation_id) == str(invocationid):
777 # Note we could just use 1 here
778 hash_attr_usn[att] = o.originating_usn
780 hash_attr_usn[att] = -1
787 # We have updated by provision usn information so let's exploit
788 # replMetadataProperties
789 if att in forwardlinked:
790 handle_links(samdb, att, basedn, current[0]["dn"],
791 current[0][att], reference[0][att], delta)
793 if isFirst == 0 and len(delta.items())>1:
795 txt = "%s\n" % (str(dn))
797 # There is always a dn attribute after a msg_diff
799 if att == "rIDAvailablePool":
802 if att == "objectSid":
805 if att == "creationTime":
808 if att == "oEMInformation":
811 if att == "msDs-KeyVersionNumber":
812 # This is the kvno of the computer/user it's a very bad
816 if handle_special_case(att, delta, reference, current, usns):
817 # This attribute is "complicated" to handle and handling
818 # was done in handle_special_case
820 attrUSN = hash_attr_usn.get(att)
821 if att == "forceLogoff" and attrUSN is None:
828 # This attribute was last modified by another DC forget
830 message(CHANGE, "%sAttribute: %s has been"
831 "created/modified/deleted by another DC,"
832 " do nothing" % (txt, att ))
836 elif not usn_in_range(int(attrUSN), usns):
837 message(CHANGE, "%sAttribute: %s has been"
838 "created/modified/deleted not during a"
839 " provision or upgradeprovision: current"
840 " usn %d , do nothing" % (txt, att, attrUSN))
845 if att == "defaultSecurityDescriptor":
848 message(CHANGE, "%sAttribute: %s will be modified"
849 "/deleted it was last modified"
850 "during a provision, current usn:"
851 "%d" % (txt, att, attrUSN))
854 message(CHANGE, "%sAttribute: %s will be added because"
855 " it hasn't existed before " % (txt, att))
860 # Old school way of handling things for pre alpha12 upgrade
862 msgElt = delta.get(att)
864 if att == "nTSecurityDescriptor":
871 if not hashOverwrittenAtt.has_key(att):
872 if msgElt.flags() != FLAG_MOD_ADD:
873 if not handle_special_case(att, delta, reference, current,
875 if opts.debugchange or opts.debugall:
877 dump_denied_change(dn, att,
878 msg_elt_flag_strs[msgElt.flags()],
879 current[0][att], reference[0][att])
881 dump_denied_change(dn, att,
882 msg_elt_flag_strs[msgElt.flags()],
883 current[0][att], None)
887 if hashOverwrittenAtt.get(att)&2**msgElt.flags() :
889 elif hashOverwrittenAtt.get(att)==never:
894 if len(delta.items()) >1:
895 attributes=", ".join(delta.keys())
896 message(CHANGE, "%s is different from the reference one, changed"
897 " attributes: %s\n" % (dn, attributes))
903 def update_partition(ref_samdb, samdb, basedn, names, schema, provisionUSNs):
904 """Check differences between the reference provision and the upgraded one.
906 It looks for all objects which base DN is name.
908 This function will also add the missing object and update existing object
909 to add or remove attributes that were missing.
911 :param ref_sambdb: An LDB object conntected to the sam.ldb of the
913 :param samdb: An LDB object connected to the sam.ldb of the update
915 :param basedn: String value of the DN of the partition
916 :param names: List of key provision parameters
917 :param schema: A Schema object
918 :param provisionUSNs: The USNs modified by provision/upgradeprovision
928 # Connect to the reference provision and get all the attribute in the
929 # partition referred by name
930 reference = ref_samdb.search(expression="objectClass=*", base=basedn,
931 scope=SCOPE_SUBTREE, attrs=["dn"],
932 controls=["search_options:1:2"])
934 current = samdb.search(expression="objectClass=*", base=basedn,
935 scope=SCOPE_SUBTREE, attrs=["dn"],
936 controls=["search_options:1:2"])
937 # Create a hash for speeding the search of new object
938 for i in range(0, len(reference)):
939 hash_new[str(reference[i]["dn"]).lower()] = reference[i]["dn"]
941 # Create a hash for speeding the search of existing object in the
943 for i in range(0, len(current)):
944 hash[str(current[i]["dn"]).lower()] = current[i]["dn"]
947 for k in hash_new.keys():
948 if not hash.has_key(k):
949 if not str(hash_new[k]) == "CN=Deleted Objects, %s" % names.rootdn:
950 listMissing.append(hash_new[k])
952 listPresent.append(hash_new[k])
954 # Sort the missing object in order to have object of the lowest level
955 # first (which can be containers for higher level objects)
956 listMissing.sort(dn_sort)
957 listPresent.sort(dn_sort)
959 # The following lines is to load the up to
960 # date schema into our current LDB
961 # a complete schema is needed as the insertion of attributes
962 # and class is done against it
963 # and the schema is self validated
964 samdb.set_schema(schema)
966 message(SIMPLE, "There are %d missing objects" % (len(listMissing)))
967 add_deletedobj_containers(ref_samdb, samdb, names)
969 add_missing_entries(ref_samdb, samdb, names, basedn, listMissing)
970 changed = update_present(ref_samdb, samdb, basedn, listPresent,
971 provisionUSNs, names.invocation)
972 message(SIMPLE, "There are %d changed objects" % (changed))
975 except StandardError, err:
976 message(ERROR, "Exception during upgrade of samdb:")
977 (typ, val, tb) = sys.exc_info()
978 traceback.print_exception(typ, val, tb)
982 def check_updated_sd(ref_sam, cur_sam, names):
983 """Check if the security descriptor in the upgraded provision are the same
986 :param ref_sam: A LDB object connected to the sam.ldb file used as
987 the reference provision
988 :param cur_sam: A LDB object connected to the sam.ldb file used as
990 :param names: List of key provision parameters"""
991 reference = ref_sam.search(expression="objectClass=*", base=str(names.rootdn),
993 attrs=["dn", "nTSecurityDescriptor"],
994 controls=["search_options:1:2"])
995 current = cur_sam.search(expression="objectClass=*", base=str(names.rootdn),
997 attrs=["dn", "nTSecurityDescriptor"],
998 controls=["search_options:1:2"])
1000 for i in range(0, len(reference)):
1001 refsd = ndr_unpack(security.descriptor,
1002 str(reference[i]["nTSecurityDescriptor"]))
1003 hash[str(reference[i]["dn"]).lower()] = refsd.as_sddl(names.domainsid)
1005 for i in range(0, len(current)):
1006 key = str(current[i]["dn"]).lower()
1007 if hash.has_key(key):
1008 cursd = ndr_unpack(security.descriptor,
1009 str(current[i]["nTSecurityDescriptor"]))
1010 sddl = cursd.as_sddl(names.domainsid)
1011 if sddl != hash[key]:
1012 txt = get_diff_sddls(hash[key], sddl)
1014 message(CHANGESD, "On object %s ACL is different"
1015 " \n%s" % (current[i]["dn"], txt))
1019 def fix_partition_sd(samdb, names):
1020 """This function fix the SD for partition containers (basedn, configdn, ...)
1021 This is needed because some provision use to have broken SD on containers
1023 :param samdb: An LDB object pointing to the sam of the current provision
1024 :param names: A list of key provision parameters
1026 # First update the SD for the rootdn
1027 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1028 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1029 controls=["search_options:1:2"])
1031 delta.dn = Dn(samdb, str(res[0]["dn"]))
1032 descr = get_domain_descriptor(names.domainsid)
1033 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1034 "nTSecurityDescriptor")
1035 samdb.modify(delta, ["recalculate_sd:0"])
1036 # Then the config dn
1037 res = samdb.search(expression="objectClass=*", base=str(names.configdn),
1038 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1039 controls=["search_options:1:2"])
1041 delta.dn = Dn(samdb, str(res[0]["dn"]))
1042 descr = get_config_descriptor(names.domainsid)
1043 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1044 "nTSecurityDescriptor" )
1045 samdb.modify(delta, ["recalculate_sd:0"])
1046 # Then the schema dn
1047 res = samdb.search(expression="objectClass=*", base=str(names.schemadn),
1048 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1049 controls=["search_options:1:2"])
1052 delta.dn = Dn(samdb, str(res[0]["dn"]))
1053 descr = get_schema_descriptor(names.domainsid)
1054 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1055 "nTSecurityDescriptor" )
1056 samdb.modify(delta, ["recalculate_sd:0"])
1058 def rebuild_sd(samdb, names):
1059 """Rebuild security descriptor of the current provision from scratch
1061 During the different pre release of samba4 security descriptors (SD)
1062 were notarly broken (up to alpha11 included)
1063 This function allow to get them back in order, this function make the
1064 assumption that nobody has modified manualy an SD
1065 and so SD can be safely recalculated from scratch to get them right.
1067 :param names: List of key provision parameters"""
1071 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1072 scope=SCOPE_SUBTREE, attrs=["dn", "whenCreated"],
1073 controls=["search_options:1:2"])
1075 if not (str(obj["dn"]) == str(names.rootdn) or
1076 str(obj["dn"]) == str(names.configdn) or
1077 str(obj["dn"]) == str(names.schemadn)):
1078 hash[str(obj["dn"])] = obj["whenCreated"]
1080 listkeys = hash.keys()
1081 listkeys.sort(dn_sort)
1083 for key in listkeys:
1086 delta.dn = Dn(samdb, key)
1087 delta["whenCreated"] = MessageElement(hash[key], FLAG_MOD_REPLACE,
1089 samdb.modify(delta, ["recalculate_sd:0"])
1091 # XXX: We should always catch an explicit exception.
1092 # What could go wrong here?
1093 samdb.transaction_cancel()
1094 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1095 scope=SCOPE_SUBTREE,
1096 attrs=["dn", "nTSecurityDescriptor"],
1097 controls=["search_options:1:2"])
1098 badsd = ndr_unpack(security.descriptor,
1099 str(res[0]["nTSecurityDescriptor"]))
1100 print "bad stuff %s" % badsd.as_sddl(names.domainsid)
1103 def removeProvisionUSN(samdb):
1104 attrs = [samba.provision.LAST_PROVISION_USN_ATTRIBUTE, "dn"]
1105 entry = samdb.search(expression="dn=@PROVISION", base = "",
1106 scope=SCOPE_SUBTREE,
1107 controls=["search_options:1:2"],
1110 empty.dn = entry[0].dn
1111 delta = samdb.msg_diff(entry[0], empty)
1113 delta.dn = entry[0].dn
1117 def simple_update_basesamdb(newpaths, paths, names):
1118 """Update the provision container db: sam.ldb
1119 This function is aimed at very old provision (before alpha9)
1121 :param newpaths: List of paths for different provision objects
1122 from the reference provision
1123 :param paths: List of paths for different provision objects
1124 from the upgraded provision
1125 :param names: List of key provision parameters"""
1127 message(SIMPLE, "Copy samdb")
1128 shutil.copy(newpaths.samdb, paths.samdb)
1130 message(SIMPLE, "Update partitions filename if needed")
1131 schemaldb = os.path.join(paths.private_dir, "schema.ldb")
1132 configldb = os.path.join(paths.private_dir, "configuration.ldb")
1133 usersldb = os.path.join(paths.private_dir, "users.ldb")
1134 samldbdir = os.path.join(paths.private_dir, "sam.ldb.d")
1136 if not os.path.isdir(samldbdir):
1138 os.chmod(samldbdir, 0700)
1139 if os.path.isfile(schemaldb):
1140 shutil.copy(schemaldb, os.path.join(samldbdir,
1141 "%s.ldb"%str(names.schemadn).upper()))
1142 os.remove(schemaldb)
1143 if os.path.isfile(usersldb):
1144 shutil.copy(usersldb, os.path.join(samldbdir,
1145 "%s.ldb"%str(names.rootdn).upper()))
1147 if os.path.isfile(configldb):
1148 shutil.copy(configldb, os.path.join(samldbdir,
1149 "%s.ldb"%str(names.configdn).upper()))
1150 os.remove(configldb)
1153 def update_privilege(ref_private_path, cur_private_path):
1154 """Update the privilege database
1156 :param ref_private_path: Path to the private directory of the reference
1158 :param cur_private_path: Path to the private directory of the current
1159 (and to be updated) provision."""
1160 message(SIMPLE, "Copy privilege")
1161 shutil.copy(os.path.join(ref_private_path, "privilege.ldb"),
1162 os.path.join(cur_private_path, "privilege.ldb"))
1165 def update_samdb(ref_samdb, samdb, names, highestUSN, schema):
1166 """Upgrade the SAM DB contents for all the provision partitions
1168 :param ref_sambdb: An LDB object conntected to the sam.ldb of the reference
1170 :param samdb: An LDB object connected to the sam.ldb of the update
1172 :param names: List of key provision parameters
1173 :param highestUSN: The highest USN modified by provision/upgradeprovision
1175 :param schema: A Schema object that represent the schema of the provision"""
1177 message(SIMPLE, "Starting update of samdb")
1178 ret = update_partition(ref_samdb, samdb, str(names.rootdn), names,
1181 message(SIMPLE, "Update of samdb finished")
1184 message(SIMPLE, "Update failed")
1188 def update_machine_account_password(samdb, secrets_ldb, names):
1189 """Update (change) the password of the current DC both in the SAM db and in
1192 :param samdb: An LDB object related to the sam.ldb file of a given provision
1193 :param secrets_ldb: An LDB object related to the secrets.ldb file of a given
1195 :param names: List of key provision parameters"""
1197 message(SIMPLE, "Update machine account")
1198 expression = "samAccountName=%s$" % names.netbiosname
1199 secrets_msg = secrets_ldb.search(expression=expression,
1200 attrs=["secureChannelType"])
1201 if int(secrets_msg[0]["secureChannelType"][0]) == SEC_CHAN_BDC:
1202 res = samdb.search(expression=expression, attrs=[])
1203 assert(len(res) == 1)
1205 msg = Message(res[0].dn)
1206 machinepass = samba.generate_random_password(128, 255)
1207 msg["userPassword"] = MessageElement(machinepass, FLAG_MOD_REPLACE,
1211 res = samdb.search(expression=("samAccountName=%s$" % names.netbiosname),
1212 attrs=["msDs-keyVersionNumber"])
1213 assert(len(res) == 1)
1214 kvno = int(str(res[0]["msDs-keyVersionNumber"]))
1215 secChanType = int(secrets_msg[0]["secureChannelType"][0])
1217 secretsdb_self_join(secrets_ldb, domain=names.domain,
1218 realm=names.realm or sambaopts._lp.get('realm'),
1219 domainsid=names.domainsid,
1220 dnsdomain=names.dnsdomain,
1221 netbiosname=names.netbiosname,
1222 machinepass=machinepass,
1223 key_version_number=kvno,
1224 secure_channel_type=secChanType)
1226 raise ProvisioningError("Unable to find a Secure Channel"
1227 "of type SEC_CHAN_BDC")
1231 def setup_path(file):
1232 return os.path.join(setup_dir, file)
1234 # Synopsis for updateprovision
1235 # 1) get path related to provision to be update (called current)
1236 # 2) open current provision ldbs
1237 # 3) fetch the key provision parameter (domain sid, domain guid, invocationid
1239 # 4) research of lastProvisionUSN in order to get ranges of USN modified
1240 # by either upgradeprovision or provision
1241 # 5) creation of a new provision the latest version of provision script
1242 # (called reference)
1243 # 6) get reference provision paths
1244 # 7) open reference provision ldbs
1245 # 8) setup helpers data that will help the update process
1246 # 9) update the privilege ldb by copying the one of referecence provision to
1247 # the current provision
1248 # 10)get the oemInfo field, this field contains information about the different
1249 # provision that have been done
1250 # 11)Depending on whether oemInfo has the string "alpha9" or alphaxx (x as an
1251 # integer) or none of this the following things are done
1252 # A) When alpha9 or alphaxx is present
1253 # The base sam.ldb file is updated by looking at the difference between
1254 # referrence one and the current one. Everything is copied with the
1255 # exception of lastProvisionUSN attributes. The highest used USN
1256 # is fetched so that changed by upgradeprovision usn can be tracked
1257 # B) Other case (it reflect that that provision was done before alpha9)
1258 # The base sam.ldb of the reference provision is copied over
1259 # the current one, if necessary ldb related to partitions are moved
1261 # 12)A Schema object is created, it will be used to provide a complete
1262 # schema to current provision during update (as the schema of the
1263 # current provision might not be complete and so won't allow some
1264 # object to be created)
1265 # 13)Proceed to full update of sam DB (see the separate paragraph about i)
1266 # 14)The secrets db is updated by pull all the difference from the reference
1267 # provision into the current provision
1268 # 15)As the previous step has most probably modified the password stored in
1269 # in secret for the current DC, a new password is generated,
1270 # the kvno is bumped and the entry in samdb is also updated
1271 # 16)For current provision older than alpha9, we must fix the SD a little bit
1272 # administrator to update them because SD used to be generated with the
1273 # system account before alpha9.
1274 # 17)The highest usn modified so far is searched in the database it will be
1275 # the upper limit for usn modified during provision.
1276 # This is done before potential SD recalculation because we do not want
1277 # SD modified during recalculation to be marked as modified during provision
1278 # (and so possibly remplaced at next upgradeprovision)
1279 # 18)Rebuilt SD if the flag indicate to do so
1280 # 19)Check difference between SD of reference provision and those of the
1281 # current provision. The check is done by getting the sddl representation
1282 # of the SD. Each sddl in chuncked into parts (user,group,dacl,sacl)
1283 # Each part is verified separetly, for dacl and sacl ACL is splited into
1284 # ACEs and each ACE is verified separately (so that a permutation in ACE
1285 # didn't raise as an error).
1286 # 20)The oemInfo field is updated to add information about the fact that the
1287 # provision has been updated by the upgradeprovision version xxx
1288 # (the version is the one obtained when starting samba with the --version
1290 # 21)Check if the current provision has all the settings needed for dynamic
1291 # DNS update to work (that is to say the provision is newer than
1292 # january 2010). If not dns configuration file from reference provision
1293 # are copied in a sub folder and the administrator is invited to
1294 # do what is needed.
1295 # 22)If the lastProvisionUSN attribute was present it is updated to add
1296 # the range of usns modified by the current upgradeprovision
1299 # About updating the sam DB
1300 # The update takes place in update_partition function
1301 # This function read both current and reference provision and list all
1302 # the available DN of objects
1303 # If the string representation of a DN in reference provision is
1304 # equal to the string representation of a DN in current provision
1305 # (without taking care of case) then the object is flaged as being
1306 # present. If the object is not present in current provision the object
1307 # is being flaged as missing in current provision. Object present in current
1308 # provision but not in reference provision are ignored.
1309 # Once the list of objects present and missing is done, the deleted object
1310 # containers are created in the differents partitions (if missing)
1312 # Then the function add_missing_entries is called
1313 # This function will go through the list of missing entries by calling
1314 # add_missing_object for the given object. If this function returns 0
1315 # it means that the object needs some other object in order to be created
1316 # The object is reappended at the end of the list to be created later
1317 # (and preferably after all the needed object have been created)
1318 # The function keeps on looping on the list of object to be created until
1319 # it's empty or that the number of defered creation is equal to the number
1320 # of object that still needs to be created.
1322 # The function add_missing_object will first check if the object can be created.
1323 # That is to say that it didn't depends other not yet created objects
1324 # If requisit can't be fullfilled it exists with 0
1325 # Then it will try to create the missing entry by creating doing
1326 # an ldb_message_diff between the object in the reference provision and
1328 # This resulting object is filtered to remove all the back link attribute
1329 # (ie. memberOf) as they will be created by the other linked object (ie.
1330 # the one with the member attribute)
1331 # All attributes specified in the hashAttrNotCopied associative array are
1332 # also removed it's most of the time generated attributes
1334 # After missing entries have been added the update_partition function will
1335 # take care of object that exist but that need some update.
1336 # In order to do so the function update_present is called with the list
1337 # of object that are present in both provision and that might need an update.
1339 # This function handle first case mismatch so that the DN in the current
1340 # provision have the same case as in reference provision
1342 # It will then construct an associative array consiting of attributes as
1343 # key and invocationid as value( if the originating invocation id is
1344 # different from the invocation id of the current DC the value is -1 instead).
1346 # If the range of provision modified attributes is present, the function will
1347 # use the replMetadataProperty update method which is the following:
1348 # Removing attributes that should not be updated: rIDAvailablePool, objectSid,
1349 # creationTime, msDs-KeyVersionNumber, oEMInformation
1350 # Check for each attribute if its usn is within one of the modified by
1351 # provision range and if its originating id is the invocation id of the
1352 # current DC, then validate the update from reference to current.
1353 # If not or if there is no replMetatdataProperty for this attribute then we
1355 # Otherwise (case the range of provision modified attribute is not present) it
1356 # use the following process:
1357 # All attributes that need to be added are accepted at the exeption of those
1358 # listed in hashOverwrittenAtt, in this case the attribute needs to have the
1359 # correct flags specified.
1360 # For attributes that need to be modified or removed, a check is performed
1361 # in OverwrittenAtt, if the attribute is present and the modification flag
1362 # (remove, delete) is one of those listed for this attribute then modification
1363 # is accepted. For complicated handling of attribute update, the control is passed
1364 # to handle_special_case
1368 if __name__ == '__main__':
1369 global defSDmodified
1370 defSDmodified = False
1371 # From here start the big steps of the program
1372 # 1) First get files paths
1373 paths = get_paths(param, smbconf=smbconf)
1374 paths.setup = setup_dir
1375 # Get ldbs with the system session, it is needed for searching
1376 # provision parameters
1377 session = system_session()
1379 # This variable will hold the last provision USN once if it exists.
1382 ldbs = get_ldbs(paths, creds, session, lp)
1383 ldbs.startTransactions()
1385 # 3) Guess all the needed names (variables in fact) from the current
1387 names = find_provision_key_parameters(ldbs.sam, ldbs.secrets, ldbs.idmap,
1390 lastProvisionUSNs = get_last_provision_usn(ldbs.sam)
1391 if lastProvisionUSNs is not None:
1393 "Find a last provision USN, %d range(s)" % len(lastProvisionUSNs))
1395 # Objects will be created with the admin session
1396 # (not anymore system session)
1397 adm_session = admin_session(lp, str(names.domainsid))
1398 # So we reget handle on objects
1399 # ldbs = get_ldbs(paths, creds, adm_session, lp)
1401 if not sanitychecks(ldbs.sam, names):
1402 message(SIMPLE, "Sanity checks for the upgrade fails, checks messages"
1403 " and correct them before rerunning upgradeprovision")
1406 # Let's see provision parameters
1407 print_provision_key_parameters(names)
1409 # 5) With all this information let's create a fresh new provision used as
1411 message(SIMPLE, "Creating a reference provision")
1412 provisiondir = tempfile.mkdtemp(dir=paths.private_dir,
1413 prefix="referenceprovision")
1414 newprovision(names, setup_dir, creds, session, smbconf, provisiondir,
1419 # We need to get a list of object which SD is directly computed from
1420 # defaultSecurityDescriptor.
1421 # This will allow us to know which object we can rebuild the SD in case
1422 # of change of the parent's SD or of the defaultSD.
1423 # Get file paths of this new provision
1424 newpaths = get_paths(param, targetdir=provisiondir)
1425 new_ldbs = get_ldbs(newpaths, creds, session, lp)
1426 new_ldbs.startTransactions()
1428 # 8) Populate some associative array to ease the update process
1429 # List of attribute which are link and backlink
1430 populate_links(new_ldbs.sam, names.schemadn)
1431 # List of attribute with ASN DN synthax)
1432 populate_dnsyntax(new_ldbs.sam, names.schemadn)
1434 update_privilege(newpaths.private_dir, paths.private_dir)
1436 oem = getOEMInfo(ldbs.sam, str(names.rootdn))
1437 # Do some modification on sam.ldb
1438 ldbs.groupedCommit()
1440 if re.match(".*alpha((9)|(\d\d+)).*", str(oem)):
1442 # Starting from alpha9 we can consider that the structure is quite ok
1443 # and that we should do only dela
1444 new_ldbs.groupedCommit()
1445 delta_update_basesamdb(newpaths.samdb, paths.samdb, creds, session, lp, message)
1446 ldbs.startTransactions()
1447 minUSN = int(str(get_max_usn(ldbs.sam, str(names.rootdn)))) + 1
1448 new_ldbs.startTransactions()
1451 simple_update_basesamdb(newpaths, paths, names)
1452 ldbs = get_ldbs(paths, creds, session, lp)
1453 removeProvisionUSN(ldbs.sam)
1454 ldbs.startTransactions()
1457 schema = Schema(setup_path, names.domainsid, schemadn=str(names.schemadn),
1458 serverdn=str(names.serverdn))
1461 if not update_samdb(new_ldbs.sam, ldbs.sam, names, lastProvisionUSNs,
1463 message(SIMPLE, "Rollbacking every changes. Check the reason"
1465 message(SIMPLE, "In any case your system as it was before"
1467 ldbs.groupedRollback()
1468 new_ldbs.groupedRollback()
1469 shutil.rmtree(provisiondir)
1472 update_secrets(new_ldbs.secrets, ldbs.secrets, message)
1474 update_machine_account_password(ldbs.sam, ldbs.secrets, names)
1476 # 16) SD should be created with admin but as some previous acl were so wrong
1477 # that admin can't modify them we have first to recreate them with the good
1478 # form but with system account and then give the ownership to admin ...
1479 if not re.match(r'.*alpha(9|\d\d+)', str(oem)):
1480 message(SIMPLE, "Fixing old povision SD")
1481 fix_partition_sd(ldbs.sam, names)
1482 rebuild_sd(ldbs.sam, names)
1484 # We calculate the max USN before recalculating the SD because we might
1485 # touch object that have been modified after a provision and we do not
1486 # want that the next upgradeprovision thinks that it has a green light
1490 maxUSN = get_max_usn(ldbs.sam, str(names.rootdn))
1492 # 18) We rebuild SD only if defaultSecurityDescriptor is modified
1493 # But in fact we should do it also if one object has its SD modified as
1494 # child might need rebuild
1496 message(SIMPLE, "Updating SD")
1497 ldbs.sam.set_session_info(adm_session)
1498 # Alpha10 was a bit broken still
1499 if re.match(r'.*alpha(\d|10)', str(oem)):
1500 fix_partition_sd(ldbs.sam, names)
1501 rebuild_sd(ldbs.sam, names)
1504 # Now we are quite confident in the recalculate process of the SD, we make
1506 # Also the check must be done in a clever way as for the moment we just
1508 if opts.debugchangesd:
1509 check_updated_sd(new_ldbs.sam, ldbs.sam, names)
1512 updateOEMInfo(ldbs.sam, str(names.rootdn))
1514 check_for_DNS(newpaths.private_dir, paths.private_dir)
1516 if lastProvisionUSNs is not None:
1517 update_provision_usn(ldbs.sam, minUSN, maxUSN)
1518 if opts.full and (names.policyid is None or names.policyid_dc is None):
1519 update_policyids(names, ldbs.sam)
1520 if opts.full or opts.resetfileacl:
1522 update_gpo(paths, ldbs.sam, names, lp, message, 1)
1523 except ProvisioningError, e:
1524 message(ERROR, "The policy for domain controller is missing,"
1525 " you should restart upgradeprovision with --full")
1528 update_gpo(paths, ldbs.sam, names, lp, message, 0)
1529 except ProvisioningError, e:
1530 message(ERROR, "The policy for domain controller is missing,"
1531 " you should restart upgradeprovision with --full")
1532 ldbs.groupedCommit()
1533 new_ldbs.groupedCommit()
1534 message(SIMPLE, "Upgrade finished !")
1535 # remove reference provision now that everything is done !
1536 shutil.rmtree(provisiondir)