s4-upgradeprovision: add function to know if attribute is replicated or not
[Samba/gebeck_regimport.git] / source4 / scripting / bin / upgradeprovision
bloba9dffc0ab58bedf13dfdd747745b2a548c342a93
1 #!/usr/bin/env python
2 # vim: expandtab
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/>.
25 import logging
26 import optparse
27 import os
28 import shutil
29 import sys
30 import tempfile
31 import re
32 import traceback
33 # Allow to run from s4 source directory (without installing samba)
34 sys.path.insert(0, "bin/python")
36 import ldb
37 import samba
38 import samba.getopt as options
40 from base64 import b64encode
41 from samba.credentials import DONT_USE_KERBEROS
42 from samba.auth import system_session, admin_session
43 from ldb import (SCOPE_SUBTREE, SCOPE_BASE,
44 FLAG_MOD_REPLACE, FLAG_MOD_ADD, FLAG_MOD_DELETE,
45 MessageElement, Message, Dn)
46 from samba import param, dsdb, Ldb
47 from samba.provision import (get_domain_descriptor, find_provision_key_parameters,
48 get_config_descriptor,
49 ProvisioningError, get_last_provision_usn,
50 get_max_usn, update_provision_usn, setup_path)
51 from samba.schema import get_linked_attributes, Schema, get_schema_descriptor
52 from samba.dcerpc import security, drsblobs, xattr
53 from samba.ndr import ndr_unpack
54 from samba.upgradehelpers import (dn_sort, get_paths, newprovision,
55 get_ldbs,
56 usn_in_range, identic_rename, get_diff_sddls,
57 update_secrets, CHANGE, ERROR, SIMPLE,
58 CHANGEALL, GUESS, CHANGESD, PROVISION,
59 updateOEMInfo, getOEMInfo, update_gpo,
60 delta_update_basesamdb, update_policyids,
61 update_machine_account_password,
62 search_constructed_attrs_stored,
63 int64range2str, update_dns_account_password,
64 increment_calculated_keyversion_number)
66 replace=2**FLAG_MOD_REPLACE
67 add=2**FLAG_MOD_ADD
68 delete=2**FLAG_MOD_DELETE
69 never=0
72 # Will be modified during provision to tell if default sd has been modified
73 # somehow ...
75 #Errors are always logged
77 __docformat__ = "restructuredText"
79 # Attributes that are never copied from the reference provision (even if they
80 # do not exist in the destination object).
81 # This is most probably because they are populated automatcally when object is
82 # created
83 # This also apply to imported object from reference provision
84 hashAttrNotCopied = { "dn": 1, "whenCreated": 1, "whenChanged": 1,
85 "objectGUID": 1, "uSNCreated": 1,
86 "replPropertyMetaData": 1, "uSNChanged": 1,
87 "parentGUID": 1, "objectCategory": 1,
88 "distinguishedName": 1, "nTMixedDomain": 1,
89 "showInAdvancedViewOnly": 1, "instanceType": 1,
90 "msDS-Behavior-Version":1, "nextRid":1, "cn": 1,
91 "lmPwdHistory":1, "pwdLastSet": 1,
92 "ntPwdHistory":1, "unicodePwd":1,"dBCSPwd":1,
93 "supplementalCredentials":1, "gPCUserExtensionNames":1,
94 "gPCMachineExtensionNames":1,"maxPwdAge":1, "secret":1,
95 "possibleInferiors":1, "privilege":1,
96 "sAMAccountType":1 }
98 # Usually for an object that already exists we do not overwrite attributes as
99 # they might have been changed for good reasons. Anyway for a few of them it's
100 # mandatory to replace them otherwise the provision will be broken somehow.
101 # But for attribute that are just missing we do not have to specify them as the default
102 # behavior is to add missing attribute
103 hashOverwrittenAtt = { "prefixMap": replace, "systemMayContain": replace,
104 "systemOnly":replace, "searchFlags":replace,
105 "mayContain":replace, "systemFlags":replace+add,
106 "description":replace, "operatingSystemVersion":replace,
107 "adminPropertyPages":replace, "groupType":replace,
108 "wellKnownObjects":replace, "privilege":never,
109 "defaultSecurityDescriptor": replace,
110 "rIDAvailablePool": never,
111 "rIDNextRID": add, "rIDUsedPool": never,
112 "defaultSecurityDescriptor": replace + add,
113 "isMemberOfPartialAttributeSet": delete,
114 "attributeDisplayNames": replace + add,
115 "versionNumber": add}
117 backlinked = []
118 forwardlinked = set()
119 dn_syntax_att = []
120 not_replicated = []
121 def define_what_to_log(opts):
122 what = 0
123 if opts.debugchange:
124 what = what | CHANGE
125 if opts.debugchangesd:
126 what = what | CHANGESD
127 if opts.debugguess:
128 what = what | GUESS
129 if opts.debugprovision:
130 what = what | PROVISION
131 if opts.debugall:
132 what = what | CHANGEALL
133 return what
136 parser = optparse.OptionParser("provision [options]")
137 sambaopts = options.SambaOptions(parser)
138 parser.add_option_group(sambaopts)
139 parser.add_option_group(options.VersionOptions(parser))
140 credopts = options.CredentialsOptions(parser)
141 parser.add_option_group(credopts)
142 parser.add_option("--setupdir", type="string", metavar="DIR",
143 help="directory with setup files")
144 parser.add_option("--debugprovision", help="Debug provision", action="store_true")
145 parser.add_option("--debugguess", action="store_true",
146 help="Print information on which values are guessed")
147 parser.add_option("--debugchange", action="store_true",
148 help="Print information on what is different but won't be changed")
149 parser.add_option("--debugchangesd", action="store_true",
150 help="Print security descriptor differences")
151 parser.add_option("--debugall", action="store_true",
152 help="Print all available information (very verbose)")
153 parser.add_option("--resetfileacl", action="store_true",
154 help="Force a reset on filesystem acls in sysvol / netlogon share")
155 parser.add_option("--fixntacl", action="store_true",
156 help="Only fix NT ACLs in sysvol / netlogon share")
157 parser.add_option("--full", action="store_true",
158 help="Perform full upgrade of the samdb (schema, configuration, new objects, ...")
160 opts = parser.parse_args()[0]
162 handler = logging.StreamHandler(sys.stdout)
163 upgrade_logger = logging.getLogger("upgradeprovision")
164 upgrade_logger.setLevel(logging.INFO)
166 upgrade_logger.addHandler(handler)
168 provision_logger = logging.getLogger("provision")
169 provision_logger.addHandler(handler)
171 whatToLog = define_what_to_log(opts)
173 def message(what, text):
174 """Print a message if this message type has been selected to be printed
176 :param what: Category of the message
177 :param text: Message to print """
178 if (whatToLog & what) or what <= 0:
179 upgrade_logger.info("%s", text)
181 if len(sys.argv) == 1:
182 opts.interactive = True
183 lp = sambaopts.get_loadparm()
184 smbconf = lp.configfile
186 creds = credopts.get_credentials(lp)
187 creds.set_kerberos_state(DONT_USE_KERBEROS)
191 def check_for_DNS(refprivate, private):
192 """Check if the provision has already the requirement for dynamic dns
194 :param refprivate: The path to the private directory of the reference
195 provision
196 :param private: The path to the private directory of the upgraded
197 provision"""
199 spnfile = "%s/spn_update_list" % private
200 dnsfile = "%s/dns_update_list" % private
201 namedfile = lp.get("dnsupdate:path")
203 if not namedfile:
204 namedfile = "%s/named.conf.update" % private
206 if not os.path.exists(spnfile):
207 shutil.copy("%s/spn_update_list" % refprivate, "%s" % spnfile)
209 if not os.path.exists(dnsfile):
210 shutil.copy("%s/dns_update_list" % refprivate, "%s" % dnsfile)
212 destdir = "%s/new_dns" % private
213 dnsdir = "%s/dns" % private
215 if not os.path.exists(namedfile):
216 if not os.path.exists(destdir):
217 os.mkdir(destdir)
218 if not os.path.exists(dnsdir):
219 os.mkdir(dnsdir)
220 shutil.copy("%s/named.conf" % refprivate, "%s/named.conf" % destdir)
221 shutil.copy("%s/named.txt" % refprivate, "%s/named.txt" % destdir)
222 message(SIMPLE, "It seems that your provision did not integrate "
223 "new rules for dynamic dns update of domain related entries")
224 message(SIMPLE, "A copy of the new bind configuration files and "
225 "template has been put in %s, you should read them and "
226 "configure dynamic dns updates" % destdir)
229 def populate_links(samdb, schemadn):
230 """Populate an array with all the back linked attributes
232 This attributes that are modified automaticaly when
233 front attibutes are changed
235 :param samdb: A LDB object for sam.ldb file
236 :param schemadn: DN of the schema for the partition"""
237 linkedAttHash = get_linked_attributes(Dn(samdb, str(schemadn)), samdb)
238 backlinked.extend(linkedAttHash.values())
239 for t in linkedAttHash.keys():
240 forwardlinked.add(t)
242 def isReplicated(att):
243 """ Indicate if the attribute is replicated or not
245 :param att: Name of the attribute to be tested
246 :return: True is the attribute is replicated, False otherwise
249 return (att not in not_replicated)
251 def populateNotReplicated(samdb, schemadn):
252 """Populate an array with all the attributes that are not replicated
254 :param samdb: A LDB object for sam.ldb file
255 :param schemadn: DN of the schema for the partition"""
256 res = samdb.search(expression="(&(objectclass=attributeSchema)(systemflags:1.2.840.113556.1.4.803:=1))", base=Dn(samdb,
257 str(schemadn)), scope=SCOPE_SUBTREE,
258 attrs=["lDAPDisplayName"])
259 for elem in res:
260 not_replicated.append(elem["lDAPDisplayName"])
262 def populate_dnsyntax(samdb, schemadn):
263 """Populate an array with all the attributes that have DN synthax
264 (oid 2.5.5.1)
266 :param samdb: A LDB object for sam.ldb file
267 :param schemadn: DN of the schema for the partition"""
268 res = samdb.search(expression="(attributeSyntax=2.5.5.1)", base=Dn(samdb,
269 str(schemadn)), scope=SCOPE_SUBTREE,
270 attrs=["lDAPDisplayName"])
271 for elem in res:
272 dn_syntax_att.append(elem["lDAPDisplayName"])
275 def sanitychecks(samdb, names):
276 """Make some checks before trying to update
278 :param samdb: An LDB object opened on sam.ldb
279 :param names: list of key provision parameters
280 :return: Status of check (1 for Ok, 0 for not Ok) """
281 res = samdb.search(expression="objectClass=ntdsdsa", base=str(names.configdn),
282 scope=SCOPE_SUBTREE, attrs=["dn"],
283 controls=["search_options:1:2"])
284 if len(res) == 0:
285 print "No DC found. Your provision is most probably broken!"
286 return False
287 elif len(res) != 1:
288 print "Found %d domain controllers. For the moment " \
289 "upgradeprovision is not able to handle an upgrade on a " \
290 "domain with more than one DC. Please demote the other " \
291 "DC(s) before upgrading" % len(res)
292 return False
293 else:
294 return True
297 def print_provision_key_parameters(names):
298 """Do a a pretty print of provision parameters
300 :param names: list of key provision parameters """
301 message(GUESS, "rootdn :" + str(names.rootdn))
302 message(GUESS, "configdn :" + str(names.configdn))
303 message(GUESS, "schemadn :" + str(names.schemadn))
304 message(GUESS, "serverdn :" + str(names.serverdn))
305 message(GUESS, "netbiosname :" + names.netbiosname)
306 message(GUESS, "defaultsite :" + names.sitename)
307 message(GUESS, "dnsdomain :" + names.dnsdomain)
308 message(GUESS, "hostname :" + names.hostname)
309 message(GUESS, "domain :" + names.domain)
310 message(GUESS, "realm :" + names.realm)
311 message(GUESS, "invocationid:" + names.invocation)
312 message(GUESS, "policyguid :" + names.policyid)
313 message(GUESS, "policyguiddc:" + str(names.policyid_dc))
314 message(GUESS, "domainsid :" + str(names.domainsid))
315 message(GUESS, "domainguid :" + names.domainguid)
316 message(GUESS, "ntdsguid :" + names.ntdsguid)
317 message(GUESS, "domainlevel :" + str(names.domainlevel))
320 def handle_special_case(att, delta, new, old, useReplMetadata, basedn, aldb):
321 """Define more complicate update rules for some attributes
323 :param att: The attribute to be updated
324 :param delta: A messageElement object that correspond to the difference
325 between the updated object and the reference one
326 :param new: The reference object
327 :param old: The Updated object
328 :param useReplMetadata: A boolean that indicate if the update process
329 use replPropertyMetaData to decide what has to be updated.
330 :param basedn: The base DN of the provision
331 :param aldb: An ldb object used to build DN
332 :return: True to indicate that the attribute should be kept, False for
333 discarding it"""
335 flag = delta.get(att).flags()
336 # We do most of the special case handle if we do not have the
337 # highest usn as otherwise the replPropertyMetaData will guide us more
338 # correctly
339 if not useReplMetadata:
340 if (att == "sPNMappings" and flag == FLAG_MOD_REPLACE and
341 ldb.Dn(aldb, "CN=Directory Service,CN=Windows NT,"
342 "CN=Services,CN=Configuration,%s" % basedn)
343 == old[0].dn):
344 return True
345 if (att == "userAccountControl" and flag == FLAG_MOD_REPLACE and
346 ldb.Dn(aldb, "CN=Administrator,CN=Users,%s" % basedn)
347 == old[0].dn):
348 message(SIMPLE, "We suggest that you change the userAccountControl"
349 " for user Administrator from value %d to %d" %
350 (int(str(old[0][att])), int(str(new[0][att]))))
351 return False
352 if (att == "minPwdAge" and flag == FLAG_MOD_REPLACE):
353 if (long(str(old[0][att])) == 0):
354 delta[att] = MessageElement(new[0][att], FLAG_MOD_REPLACE, att)
355 return True
357 if (att == "member" and flag == FLAG_MOD_REPLACE):
358 hash = {}
359 newval = []
360 changeDelta=0
361 for elem in old[0][att]:
362 hash[str(elem).lower()]=1
363 newval.append(str(elem))
365 for elem in new[0][att]:
366 if not hash.has_key(str(elem).lower()):
367 changeDelta=1
368 newval.append(str(elem))
369 if changeDelta == 1:
370 delta[att] = MessageElement(newval, FLAG_MOD_REPLACE, att)
371 else:
372 delta.remove(att)
373 return True
375 if (att in ("gPLink", "gPCFileSysPath") and
376 flag == FLAG_MOD_REPLACE and
377 str(new[0].dn).lower() == str(old[0].dn).lower()):
378 delta.remove(att)
379 return True
381 if att == "forceLogoff":
382 ref=0x8000000000000000
383 oldval=int(old[0][att][0])
384 newval=int(new[0][att][0])
385 ref == old and ref == abs(new)
386 return True
388 if att in ("adminDisplayName", "adminDescription"):
389 return True
391 if (str(old[0].dn) == "CN=Samba4-Local-Domain, %s" % (names.schemadn)
392 and att == "defaultObjectCategory" and flag == FLAG_MOD_REPLACE):
393 return True
395 if (str(old[0].dn) == "CN=Title, %s" % (str(names.schemadn)) and
396 att == "rangeUpper" and flag == FLAG_MOD_REPLACE):
397 return True
399 if (str(old[0].dn) == "%s" % (str(names.rootdn))
400 and att == "subRefs" and flag == FLAG_MOD_REPLACE):
401 return True
402 #Allow to change revision of ForestUpdates objects
403 if (att == "revision" or att == "objectVersion"):
404 if str(delta.dn).lower().find("domainupdates") and str(delta.dn).lower().find("forestupdates") > 0:
405 return True
406 if str(delta.dn).endswith("CN=DisplaySpecifiers, %s" % names.configdn):
407 return True
409 # This is a bit of special animal as we might have added
410 # already SPN entries to the list that has to be modified
411 # So we go in detail to try to find out what has to be added ...
412 if (att == "servicePrincipalName" and flag == FLAG_MOD_REPLACE):
413 hash = {}
414 newval = []
415 changeDelta=0
416 for elem in old[0][att]:
417 hash[str(elem)]=1
418 newval.append(str(elem))
420 for elem in new[0][att]:
421 if not hash.has_key(str(elem)):
422 changeDelta=1
423 newval.append(str(elem))
424 if changeDelta == 1:
425 delta[att] = MessageElement(newval, FLAG_MOD_REPLACE, att)
426 else:
427 delta.remove(att)
428 return True
430 return False
432 def dump_denied_change(dn, att, flagtxt, current, reference):
433 """Print detailed information about why a change is denied
435 :param dn: DN of the object which attribute is denied
436 :param att: Attribute that was supposed to be upgraded
437 :param flagtxt: Type of the update that should be performed
438 (add, change, remove, ...)
439 :param current: Value(s) of the current attribute
440 :param reference: Value(s) of the reference attribute"""
442 message(CHANGE, "dn= " + str(dn)+" " + att+" with flag " + flagtxt
443 + " must not be changed/removed. Discarding the change")
444 if att == "objectSid" :
445 message(CHANGE, "old : %s" % ndr_unpack(security.dom_sid, current[0]))
446 message(CHANGE, "new : %s" % ndr_unpack(security.dom_sid, reference[0]))
447 elif att == "rIDPreviousAllocationPool" or att == "rIDAllocationPool":
448 message(CHANGE, "old : %s" % int64range2str(current[0]))
449 message(CHANGE, "new : %s" % int64range2str(reference[0]))
450 else:
451 i = 0
452 for e in range(0, len(current)):
453 message(CHANGE, "old %d : %s" % (i, str(current[e])))
454 i+=1
455 if reference is not None:
456 i = 0
457 for e in range(0, len(reference)):
458 message(CHANGE, "new %d : %s" % (i, str(reference[e])))
459 i+=1
461 def handle_special_add(samdb, dn, names):
462 """Handle special operation (like remove) on some object needed during
463 upgrade
465 This is mostly due to wrong creation of the object in previous provision.
466 :param samdb: An Ldb object representing the SAM database
467 :param dn: DN of the object to inspect
468 :param names: list of key provision parameters
471 dntoremove = None
472 objDn = Dn(samdb, "CN=IIS_IUSRS, CN=Builtin, %s" % names.rootdn)
473 if dn == objDn :
474 #This entry was misplaced lets remove it if it exists
475 dntoremove = "CN=IIS_IUSRS, CN=Users, %s" % names.rootdn
477 objDn = Dn(samdb,
478 "CN=Certificate Service DCOM Access, CN=Builtin, %s" % names.rootdn)
479 if dn == objDn:
480 #This entry was misplaced lets remove it if it exists
481 dntoremove = "CN=Certificate Service DCOM Access,"\
482 "CN=Users, %s" % names.rootdn
484 objDn = Dn(samdb, "CN=Cryptographic Operators, CN=Builtin, %s" % names.rootdn)
485 if dn == objDn:
486 #This entry was misplaced lets remove it if it exists
487 dntoremove = "CN=Cryptographic Operators, CN=Users, %s" % names.rootdn
489 objDn = Dn(samdb, "CN=Event Log Readers, CN=Builtin, %s" % names.rootdn)
490 if dn == objDn:
491 #This entry was misplaced lets remove it if it exists
492 dntoremove = "CN=Event Log Readers, CN=Users, %s" % names.rootdn
494 objDn = Dn(samdb,"CN=System,CN=WellKnown Security Principals,"
495 "CN=Configuration,%s" % names.rootdn)
496 if dn == objDn:
497 oldDn = Dn(samdb,"CN=Well-Known-Security-Id-System,"
498 "CN=WellKnown Security Principals,"
499 "CN=Configuration,%s" % names.rootdn)
501 res = samdb.search(expression="(dn=%s)" % oldDn,
502 base=str(names.rootdn),
503 scope=SCOPE_SUBTREE, attrs=["dn"],
504 controls=["search_options:1:2"])
506 res2 = samdb.search(expression="(dn=%s)" % dn,
507 base=str(names.rootdn),
508 scope=SCOPE_SUBTREE, attrs=["dn"],
509 controls=["search_options:1:2"])
511 if len(res) > 0 and len(res2) == 0:
512 message(CHANGE, "Existing object %s must be replaced by %s. "
513 "Renaming old object" % (str(oldDn), str(dn)))
514 samdb.rename(oldDn, objDn, ["relax:0", "provision:0"])
516 return 0
518 if dntoremove is not None:
519 res = samdb.search(expression="(cn=RID Set)",
520 base=str(names.rootdn),
521 scope=SCOPE_SUBTREE, attrs=["dn"],
522 controls=["search_options:1:2"])
524 if len(res) == 0:
525 return 2
526 res = samdb.search(expression="(dn=%s)" % dntoremove,
527 base=str(names.rootdn),
528 scope=SCOPE_SUBTREE, attrs=["dn"],
529 controls=["search_options:1:2"])
530 if len(res) > 0:
531 message(CHANGE, "Existing object %s must be replaced by %s. "
532 "Removing old object" % (dntoremove, str(dn)))
533 samdb.delete(res[0]["dn"])
534 return 0
536 return 1
539 def check_dn_nottobecreated(hash, index, listdn):
540 """Check if one of the DN present in the list has a creation order
541 greater than the current.
543 Hash is indexed by dn to be created, with each key
544 is associated the creation order.
546 First dn to be created has the creation order 0, second has 1, ...
547 Index contain the current creation order
549 :param hash: Hash holding the different DN of the object to be
550 created as key
551 :param index: Current creation order
552 :param listdn: List of DNs on which the current DN depends on
553 :return: None if the current object do not depend on other
554 object or if all object have been created before."""
555 if listdn is None:
556 return None
557 for dn in listdn:
558 key = str(dn).lower()
559 if hash.has_key(key) and hash[key] > index:
560 return str(dn)
561 return None
565 def add_missing_object(ref_samdb, samdb, dn, names, basedn, hash, index):
566 """Add a new object if the dependencies are satisfied
568 The function add the object if the object on which it depends are already
569 created
571 :param ref_samdb: Ldb object representing the SAM db of the reference
572 provision
573 :param samdb: Ldb object representing the SAM db of the upgraded
574 provision
575 :param dn: DN of the object to be added
576 :param names: List of key provision parameters
577 :param basedn: DN of the partition to be updated
578 :param hash: Hash holding the different DN of the object to be
579 created as key
580 :param index: Current creation order
581 :return: True if the object was created False otherwise"""
583 ret = handle_special_add(samdb, dn, names)
585 if ret == 2:
586 return False
588 if ret == 0:
589 return True
592 reference = ref_samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
593 scope=SCOPE_SUBTREE, controls=["search_options:1:2"])
594 empty = Message()
595 delta = samdb.msg_diff(empty, reference[0])
596 delta.dn
597 skip = False
598 try:
599 if str(reference[0].get("cn")) == "RID Set":
600 for klass in reference[0].get("objectClass"):
601 if str(klass).lower() == "ridset":
602 skip = True
603 finally:
604 if delta.get("objectSid"):
605 sid = str(ndr_unpack(security.dom_sid, str(reference[0]["objectSid"])))
606 m = re.match(r".*-(\d+)$", sid)
607 if m and int(m.group(1))>999:
608 delta.remove("objectSid")
609 for att in hashAttrNotCopied.keys():
610 delta.remove(att)
611 for att in backlinked:
612 delta.remove(att)
613 depend_on_yettobecreated = None
614 for att in dn_syntax_att:
615 depend_on_yet_tobecreated = check_dn_nottobecreated(hash, index,
616 delta.get(str(att)))
617 if depend_on_yet_tobecreated is not None:
618 message(CHANGE, "Object %s depends on %s in attribute %s. "
619 "Delaying the creation" % (dn,
620 depend_on_yet_tobecreated, att))
621 return False
623 delta.dn = dn
624 if not skip:
625 message(CHANGE,"Object %s will be added" % dn)
626 samdb.add(delta, ["relax:0", "provision:0"])
627 else:
628 message(CHANGE,"Object %s was skipped" % dn)
630 return True
632 def gen_dn_index_hash(listMissing):
633 """Generate a hash associating the DN to its creation order
635 :param listMissing: List of DN
636 :return: Hash with DN as keys and creation order as values"""
637 hash = {}
638 for i in range(0, len(listMissing)):
639 hash[str(listMissing[i]).lower()] = i
640 return hash
642 def add_deletedobj_containers(ref_samdb, samdb, names):
643 """Add the object containter: CN=Deleted Objects
645 This function create the container for each partition that need one and
646 then reference the object into the root of the partition
648 :param ref_samdb: Ldb object representing the SAM db of the reference
649 provision
650 :param samdb: Ldb object representing the SAM db of the upgraded provision
651 :param names: List of key provision parameters"""
654 wkoPrefix = "B:32:18E2EA80684F11D2B9AA00C04F79F805"
655 partitions = [str(names.rootdn), str(names.configdn)]
656 for part in partitions:
657 ref_delObjCnt = ref_samdb.search(expression="(cn=Deleted Objects)",
658 base=part, scope=SCOPE_SUBTREE,
659 attrs=["dn"],
660 controls=["show_deleted:0",
661 "show_recycled:0"])
662 delObjCnt = samdb.search(expression="(cn=Deleted Objects)",
663 base=part, scope=SCOPE_SUBTREE,
664 attrs=["dn"],
665 controls=["show_deleted:0",
666 "show_recycled:0"])
667 if len(ref_delObjCnt) > len(delObjCnt):
668 reference = ref_samdb.search(expression="cn=Deleted Objects",
669 base=part, scope=SCOPE_SUBTREE,
670 controls=["show_deleted:0",
671 "show_recycled:0"])
672 empty = Message()
673 delta = samdb.msg_diff(empty, reference[0])
675 delta.dn = Dn(samdb, str(reference[0]["dn"]))
676 for att in hashAttrNotCopied.keys():
677 delta.remove(att)
679 modcontrols = ["relax:0", "provision:0"]
680 samdb.add(delta, modcontrols)
682 listwko = []
683 res = samdb.search(expression="(objectClass=*)", base=part,
684 scope=SCOPE_BASE,
685 attrs=["dn", "wellKnownObjects"])
687 targetWKO = "%s:%s" % (wkoPrefix, str(reference[0]["dn"]))
688 found = False
690 if len(res[0]) > 0:
691 wko = res[0]["wellKnownObjects"]
693 # The wellKnownObject that we want to add.
694 for o in wko:
695 if str(o) == targetWKO:
696 found = True
697 listwko.append(str(o))
699 if not found:
700 listwko.append(targetWKO)
702 delta = Message()
703 delta.dn = Dn(samdb, str(res[0]["dn"]))
704 delta["wellKnownObjects"] = MessageElement(listwko,
705 FLAG_MOD_REPLACE,
706 "wellKnownObjects" )
707 samdb.modify(delta)
709 def add_missing_entries(ref_samdb, samdb, names, basedn, list):
710 """Add the missing object whose DN is the list
712 The function add the object if the objects on which it depends are
713 already created.
715 :param ref_samdb: Ldb object representing the SAM db of the reference
716 provision
717 :param samdb: Ldb object representing the SAM db of the upgraded
718 provision
719 :param dn: DN of the object to be added
720 :param names: List of key provision parameters
721 :param basedn: DN of the partition to be updated
722 :param list: List of DN to be added in the upgraded provision"""
724 listMissing = []
725 listDefered = list
727 while(len(listDefered) != len(listMissing) and len(listDefered) > 0):
728 index = 0
729 listMissing = listDefered
730 listDefered = []
731 hashMissing = gen_dn_index_hash(listMissing)
732 for dn in listMissing:
733 ret = add_missing_object(ref_samdb, samdb, dn, names, basedn,
734 hashMissing, index)
735 index = index + 1
736 if ret == 0:
737 # DN can't be created because it depends on some
738 # other DN in the list
739 listDefered.append(dn)
741 if len(listDefered) != 0:
742 raise ProvisioningError("Unable to insert missing elements: "
743 "circular references")
745 def handle_links(samdb, att, basedn, dn, value, ref_value, delta):
746 """This function handle updates on links
748 :param samdb: An LDB object pointing to the updated provision
749 :param att: Attribute to update
750 :param basedn: The root DN of the provision
751 :param dn: The DN of the inspected object
752 :param value: The value of the attribute
753 :param ref_value: The value of this attribute in the reference provision
754 :param delta: The MessageElement object that will be applied for
755 transforming the current provision"""
757 res = samdb.search(expression="dn=%s" % dn, base=basedn,
758 controls=["search_options:1:2", "reveal:1"],
759 attrs=[att])
761 blacklist = {}
762 hash = {}
763 newlinklist = []
764 changed = False
766 newlinklist.extend(value)
768 for e in value:
769 hash[e] = 1
770 # for w2k domain level the reveal won't reveal anything ...
771 # it means that we can readd links that were removed on purpose ...
772 # Also this function in fact just accept add not removal
774 for e in res[0][att]:
775 if not hash.has_key(e):
776 # We put in the blacklist all the element that are in the "revealed"
777 # result and not in the "standard" result
778 # This element are links that were removed before and so that
779 # we don't wan't to readd
780 blacklist[e] = 1
782 for e in ref_value:
783 if not blacklist.has_key(e) and not hash.has_key(e):
784 newlinklist.append(str(e))
785 changed = True
786 if changed:
787 delta[att] = MessageElement(newlinklist, FLAG_MOD_REPLACE, att)
788 else:
789 delta.remove(att)
792 msg_elt_flag_strs = {
793 ldb.FLAG_MOD_ADD: "MOD_ADD",
794 ldb.FLAG_MOD_REPLACE: "MOD_REPLACE",
795 ldb.FLAG_MOD_DELETE: "MOD_DELETE" }
797 def checkKeepAttributeOldMtd(delta, att, reference, current,
798 basedn, samdb):
799 """ Check if we should keep the attribute modification or not.
800 This function didn't use replicationMetadata to take a decision.
802 :param delta: A message diff object
803 :param att: An attribute
804 :param reference: A message object for the current entry comming from
805 the reference provision.
806 :param current: A message object for the current entry commin from
807 the current provision.
808 :param basedn: The DN of the partition
809 :param samdb: A ldb connection to the sam database of the current provision.
811 :return: The modified message diff.
813 # Old school way of handling things for pre alpha12 upgrade
814 global defSDmodified
815 isFirst = False
816 txt = ""
817 dn = current[0].dn
819 for att in list(delta):
820 defSDmodified = True
821 msgElt = delta.get(att)
823 if att == "nTSecurityDescriptor":
824 delta.remove(att)
825 continue
827 if att == "dn":
828 continue
830 if not hashOverwrittenAtt.has_key(att):
831 if msgElt.flags() != FLAG_MOD_ADD:
832 if not handle_special_case(att, delta, reference, current,
833 False, basedn, samdb):
834 if opts.debugchange or opts.debugall:
835 try:
836 dump_denied_change(dn, att,
837 msg_elt_flag_strs[msgElt.flags()],
838 current[0][att], reference[0][att])
839 except KeyError:
840 dump_denied_change(dn, att,
841 msg_elt_flag_strs[msgElt.flags()],
842 current[0][att], None)
843 delta.remove(att)
844 continue
845 else:
846 if hashOverwrittenAtt.get(att)&2**msgElt.flags() :
847 continue
848 elif hashOverwrittenAtt.get(att)==never:
849 delta.remove(att)
850 continue
852 return delta
854 def checkKeepAttributeWithMetadata(delta, att, message, reference, current,
855 hash_attr_usn, basedn, usns, samdb):
856 """ Check if we should keep the attribute modification or not
858 :param delta: A message diff object
859 :param att: An attribute
860 :param message: A function to print messages
861 :param reference: A message object for the current entry comming from
862 the reference provision.
863 :param current: A message object for the current entry commin from
864 the current provision.
865 :param hash_attr_usn: A dictionnary with attribute name as keys,
866 USN and invocation id as values.
867 :param basedn: The DN of the partition
868 :param usns: A dictionnary with invocation ID as keys and USN ranges
869 as values.
870 :param samdb: A ldb object pointing to the sam DB
872 :return: The modified message diff.
874 global defSDmodified
875 isFirst = False
876 txt = ""
877 dn = current[0].dn
879 for att in list(delta):
880 # We have updated by provision usn information so let's exploit
881 # replMetadataProperties
882 if att in forwardlinked:
883 curval = current[0].get(att, ())
884 refval = reference[0].get(att, ())
885 handle_links(samdb, att, basedn, current[0]["dn"],
886 curval, refval, delta)
887 continue
889 if isFirst and len(delta.items())>1:
890 isFirst = True
891 txt = "%s\n" % (str(dn))
893 keptAttr = ["dn", "rIDAvailablePool", "objectSid", "creationTime", "oEMInformation", "msDs-KeyVersionNumber"]
894 if att in keptAttr:
895 delta.remove(att)
896 continue
898 if handle_special_case(att, delta, reference, current, True, None, None):
899 # This attribute is "complicated" to handle and handling
900 # was done in handle_special_case
901 continue
903 attrUSN = None
904 if hash_attr_usn.get(att):
905 attrUSN = hash_attr_usn.get(att)
907 if att == "forceLogoff" and attrUSN is None:
908 continue
909 if attrUSN is None:
910 delta.remove(att)
911 continue
912 if att == "nTSecurityDescriptor":
913 cursd = ndr_unpack(security.descriptor,
914 str(current[0]["nTSecurityDescriptor"]))
915 cursddl = cursd.as_sddl(names.domainsid)
916 refsd = ndr_unpack(security.descriptor,
917 str(reference[0]["nTSecurityDescriptor"]))
918 refsddl = refsd.as_sddl(names.domainsid)
920 if get_diff_sddls(refsddl, cursddl) == "":
921 message(CHANGE, "sd are identical")
922 else:
923 message(CHANGE, "sd are not identical")
924 if attrUSN == -1:
925 # This attribute was last modified by another DC forget
926 # about it
927 message(CHANGE, "%sAttribute: %s has been "
928 "created/modified/deleted by another DC. "
929 "Doing nothing" % (txt, att))
930 txt = ""
931 delta.remove(att)
932 continue
933 elif not usn_in_range(int(attrUSN), usns.get(attInvId)):
934 message(CHANGE, "%sAttribute: %s was not "
935 "created/modified/deleted during a "
936 "provision or upgradeprovision. Current "
937 "usn: %d. Doing nothing" % (txt, att,
938 attrUSN))
939 txt = ""
940 delta.remove(att)
941 continue
942 else:
943 if att == "defaultSecurityDescriptor":
944 defSDmodified = True
945 if attrUSN:
946 message(CHANGE, "%sAttribute: %s will be modified"
947 "/deleted it was last modified "
948 "during a provision. Current usn: "
949 "%d" % (txt, att, attrUSN))
950 txt = ""
951 else:
952 message(CHANGE, "%sAttribute: %s will be added because "
953 "it did not exist before" % (txt, att))
954 txt = ""
955 continue
957 return delta
959 def update_present(ref_samdb, samdb, basedn, listPresent, usns, invocationid):
960 """ This function updates the object that are already present in the
961 provision
963 :param ref_samdb: An LDB object pointing to the reference provision
964 :param samdb: An LDB object pointing to the updated provision
965 :param basedn: A string with the value of the base DN for the provision
966 (ie. DC=foo, DC=bar)
967 :param listPresent: A list of object that is present in the provision
968 :param usns: A list of USN range modified by previous provision and
969 upgradeprovision
970 :param invocationid: The value of the invocationid for the current DC"""
972 # This hash is meant to speedup lookup of attribute name from an oid,
973 # it's for the replPropertyMetaData handling
974 hash_oid_name = {}
975 res = samdb.search(expression="objectClass=attributeSchema", base=basedn,
976 controls=["search_options:1:2"], attrs=["attributeID",
977 "lDAPDisplayName"])
978 if len(res) > 0:
979 for e in res:
980 strDisplay = str(e.get("lDAPDisplayName"))
981 hash_oid_name[str(e.get("attributeID"))] = strDisplay
982 else:
983 msg = "Unable to insert missing elements: circular references"
984 raise ProvisioningError(msg)
986 changed = 0
987 controls = ["search_options:1:2", "sd_flags:1:2"]
988 if usns is not None:
989 message(CHANGE, "Using replPropertyMetadata for change selection")
990 for dn in listPresent:
991 reference = ref_samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
992 scope=SCOPE_SUBTREE,
993 controls=controls)
994 current = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
995 scope=SCOPE_SUBTREE, controls=controls)
997 if (
998 (str(current[0].dn) != str(reference[0].dn)) and
999 (str(current[0].dn).upper() == str(reference[0].dn).upper())
1001 message(CHANGE, "Names are the same except for the case. "
1002 "Renaming %s to %s" % (str(current[0].dn),
1003 str(reference[0].dn)))
1004 identic_rename(samdb, reference[0].dn)
1005 current = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
1006 scope=SCOPE_SUBTREE,
1007 controls=controls)
1009 delta = samdb.msg_diff(current[0], reference[0])
1011 for att in backlinked:
1012 delta.remove(att)
1014 delta.remove("name")
1016 if len(delta.items()) > 1 and usns is not None:
1017 # Fetch the replPropertyMetaData
1018 res = samdb.search(expression="dn=%s" % (str(dn)), base=basedn,
1019 scope=SCOPE_SUBTREE, controls=controls,
1020 attrs=["replPropertyMetaData"])
1021 ctr = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
1022 str(res[0]["replPropertyMetaData"])).ctr
1024 hash_attr_usn = {}
1025 for o in ctr.array:
1026 # We put in this hash only modification
1027 # made on the current host
1028 att = hash_oid_name[samdb.get_oid_from_attid(o.attid)]
1029 if str(o.originating_invocation_id) == str(invocationid):
1030 # Note we could just use 1 here
1031 hash_attr_usn[att] = o.originating_usn
1032 else:
1034 if usns is not None:
1035 delta = checkKeepAttributeWithMetadata(delta, att, message, reference,
1036 current, hash_attr_usn,
1037 basedn, usns, samdb)
1038 else:
1039 for att in hashAttrNotCopied.keys():
1040 delta.remove(att)
1041 delta = checkKeepAttributeOldMtd(delta, att, reference, current, basedn, samdb)
1043 delta.dn = dn
1044 if len(delta.items()) >1:
1045 attributes=", ".join(delta.keys())
1046 modcontrols = []
1047 relaxedatt = ['iscriticalsystemobject', 'grouptype']
1048 # Let's try to reduce as much as possible the use of relax control
1049 #for checkedatt in relaxedatt:
1050 for attr in delta.keys():
1051 if attr.lower() in relaxedatt:
1052 modcontrols = ["relax:0", "provision:0"]
1053 message(CHANGE, "%s is different from the reference one, changed"
1054 " attributes: %s\n" % (dn, attributes))
1055 changed += 1
1056 samdb.modify(delta, modcontrols)
1057 return changed
1059 def reload_full_schema(samdb, names):
1060 """Load the updated schema with all the new and existing classes
1061 and attributes.
1063 :param samdb: An LDB object connected to the sam.ldb of the update
1064 provision
1065 :param names: List of key provision parameters
1068 current = samdb.search(expression="objectClass=*", base=str(names.schemadn),
1069 scope=SCOPE_SUBTREE)
1070 schema_ldif = ""
1071 prefixmap_data = ""
1073 for ent in current:
1074 schema_ldif += samdb.write_ldif(ent, ldb.CHANGETYPE_NONE)
1076 prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()
1077 prefixmap_data = b64encode(prefixmap_data)
1079 # We don't actually add this ldif, just parse it
1080 prefixmap_ldif = "dn: cn=schema\nprefixMap:: %s\n\n" % prefixmap_data
1082 dsdb._dsdb_set_schema_from_ldif(samdb, prefixmap_ldif, schema_ldif)
1085 def update_partition(ref_samdb, samdb, basedn, names, schema, provisionUSNs, prereloadfunc):
1086 """Check differences between the reference provision and the upgraded one.
1088 It looks for all objects which base DN is name.
1090 This function will also add the missing object and update existing object
1091 to add or remove attributes that were missing.
1093 :param ref_sambdb: An LDB object conntected to the sam.ldb of the
1094 reference provision
1095 :param samdb: An LDB object connected to the sam.ldb of the update
1096 provision
1097 :param basedn: String value of the DN of the partition
1098 :param names: List of key provision parameters
1099 :param schema: A Schema object
1100 :param provisionUSNs: The USNs modified by provision/upgradeprovision
1101 last time
1102 :param prereloadfunc: A function that must be executed just before the reload
1103 of the schema
1106 hash_new = {}
1107 hash = {}
1108 listMissing = []
1109 listPresent = []
1110 reference = []
1111 current = []
1113 # Connect to the reference provision and get all the attribute in the
1114 # partition referred by name
1115 reference = ref_samdb.search(expression="objectClass=*", base=basedn,
1116 scope=SCOPE_SUBTREE, attrs=["dn"],
1117 controls=["search_options:1:2"])
1119 current = samdb.search(expression="objectClass=*", base=basedn,
1120 scope=SCOPE_SUBTREE, attrs=["dn"],
1121 controls=["search_options:1:2"])
1122 # Create a hash for speeding the search of new object
1123 for i in range(0, len(reference)):
1124 hash_new[str(reference[i]["dn"]).lower()] = reference[i]["dn"]
1126 # Create a hash for speeding the search of existing object in the
1127 # current provision
1128 for i in range(0, len(current)):
1129 hash[str(current[i]["dn"]).lower()] = current[i]["dn"]
1132 for k in hash_new.keys():
1133 if not hash.has_key(k):
1134 if not str(hash_new[k]) == "CN=Deleted Objects, %s" % names.rootdn:
1135 listMissing.append(hash_new[k])
1136 else:
1137 listPresent.append(hash_new[k])
1139 # Sort the missing object in order to have object of the lowest level
1140 # first (which can be containers for higher level objects)
1141 listMissing.sort(dn_sort)
1142 listPresent.sort(dn_sort)
1144 # The following lines is to load the up to
1145 # date schema into our current LDB
1146 # a complete schema is needed as the insertion of attributes
1147 # and class is done against it
1148 # and the schema is self validated
1149 samdb.set_schema(schema)
1150 try:
1151 message(SIMPLE, "There are %d missing objects" % (len(listMissing)))
1152 add_deletedobj_containers(ref_samdb, samdb, names)
1154 add_missing_entries(ref_samdb, samdb, names, basedn, listMissing)
1156 prereloadfunc()
1157 message(SIMPLE, "Reloading a merged schema, which might trigger "
1158 "reindexing so please be patient")
1159 reload_full_schema(samdb, names)
1160 message(SIMPLE, "Schema reloaded!")
1162 changed = update_present(ref_samdb, samdb, basedn, listPresent,
1163 provisionUSNs, names.invocation)
1164 message(SIMPLE, "There are %d changed objects" % (changed))
1165 return 1
1167 except StandardError, err:
1168 message(ERROR, "Exception during upgrade of samdb:")
1169 (typ, val, tb) = sys.exc_info()
1170 traceback.print_exception(typ, val, tb)
1171 return 0
1174 def check_updated_sd(ref_sam, cur_sam, names):
1175 """Check if the security descriptor in the upgraded provision are the same
1176 as the reference
1178 :param ref_sam: A LDB object connected to the sam.ldb file used as
1179 the reference provision
1180 :param cur_sam: A LDB object connected to the sam.ldb file used as
1181 upgraded provision
1182 :param names: List of key provision parameters"""
1183 reference = ref_sam.search(expression="objectClass=*", base=str(names.rootdn),
1184 scope=SCOPE_SUBTREE,
1185 attrs=["dn", "nTSecurityDescriptor"],
1186 controls=["search_options:1:2"])
1187 current = cur_sam.search(expression="objectClass=*", base=str(names.rootdn),
1188 scope=SCOPE_SUBTREE,
1189 attrs=["dn", "nTSecurityDescriptor"],
1190 controls=["search_options:1:2"])
1191 hash = {}
1192 for i in range(0, len(reference)):
1193 refsd = ndr_unpack(security.descriptor,
1194 str(reference[i]["nTSecurityDescriptor"]))
1195 hash[str(reference[i]["dn"]).lower()] = refsd.as_sddl(names.domainsid)
1198 for i in range(0, len(current)):
1199 key = str(current[i]["dn"]).lower()
1200 if hash.has_key(key):
1201 cursd = ndr_unpack(security.descriptor,
1202 str(current[i]["nTSecurityDescriptor"]))
1203 sddl = cursd.as_sddl(names.domainsid)
1204 if sddl != hash[key]:
1205 txt = get_diff_sddls(hash[key], sddl)
1206 if txt != "":
1207 message(CHANGESD, "On object %s ACL is different"
1208 " \n%s" % (current[i]["dn"], txt))
1212 def fix_partition_sd(samdb, names):
1213 """This function fix the SD for partition containers (basedn, configdn, ...)
1214 This is needed because some provision use to have broken SD on containers
1216 :param samdb: An LDB object pointing to the sam of the current provision
1217 :param names: A list of key provision parameters
1219 # First update the SD for the rootdn
1220 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1221 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1222 controls=["search_options:1:2"])
1223 delta = Message()
1224 delta.dn = Dn(samdb, str(res[0]["dn"]))
1225 descr = get_domain_descriptor(names.domainsid)
1226 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1227 "nTSecurityDescriptor")
1228 samdb.modify(delta)
1229 # Then the config dn
1230 res = samdb.search(expression="objectClass=*", base=str(names.configdn),
1231 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1232 controls=["search_options:1:2"])
1233 delta = Message()
1234 delta.dn = Dn(samdb, str(res[0]["dn"]))
1235 descr = get_config_descriptor(names.domainsid)
1236 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1237 "nTSecurityDescriptor" )
1238 samdb.modify(delta)
1239 # Then the schema dn
1240 res = samdb.search(expression="objectClass=*", base=str(names.schemadn),
1241 scope=SCOPE_BASE, attrs=["dn", "whenCreated"],
1242 controls=["search_options:1:2"])
1244 delta = Message()
1245 delta.dn = Dn(samdb, str(res[0]["dn"]))
1246 descr = get_schema_descriptor(names.domainsid)
1247 delta["nTSecurityDescriptor"] = MessageElement(descr, FLAG_MOD_REPLACE,
1248 "nTSecurityDescriptor" )
1249 samdb.modify(delta)
1251 def rebuild_sd(samdb, names):
1252 """Rebuild security descriptor of the current provision from scratch
1254 During the different pre release of samba4 security descriptors (SD)
1255 were notarly broken (up to alpha11 included)
1256 This function allow to get them back in order, this function make the
1257 assumption that nobody has modified manualy an SD
1258 and so SD can be safely recalculated from scratch to get them right.
1260 :param names: List of key provision parameters"""
1263 hash = {}
1264 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1265 scope=SCOPE_SUBTREE, attrs=["dn", "whenCreated"],
1266 controls=["search_options:1:2"])
1267 for obj in res:
1268 if not (str(obj["dn"]) == str(names.rootdn) or
1269 str(obj["dn"]) == str(names.configdn) or
1270 str(obj["dn"]) == str(names.schemadn)):
1271 hash[str(obj["dn"])] = obj["whenCreated"]
1273 listkeys = hash.keys()
1274 listkeys.sort(dn_sort)
1276 for key in listkeys:
1277 try:
1278 delta = Message()
1279 delta.dn = Dn(samdb, key)
1280 delta["whenCreated"] = MessageElement(hash[key], FLAG_MOD_REPLACE,
1281 "whenCreated" )
1282 samdb.modify(delta, ["recalculate_sd:0"])
1283 except:
1284 # XXX: We should always catch an explicit exception.
1285 # What could go wrong here?
1286 samdb.transaction_cancel()
1287 res = samdb.search(expression="objectClass=*", base=str(names.rootdn),
1288 scope=SCOPE_SUBTREE,
1289 attrs=["dn", "nTSecurityDescriptor"],
1290 controls=["search_options:1:2"])
1291 badsd = ndr_unpack(security.descriptor,
1292 str(res[0]["nTSecurityDescriptor"]))
1293 print "bad stuff %s" % badsd.as_sddl(names.domainsid)
1294 return
1296 def removeProvisionUSN(samdb):
1297 attrs = [samba.provision.LAST_PROVISION_USN_ATTRIBUTE, "dn"]
1298 entry = samdb.search(expression="dn=@PROVISION", base = "",
1299 scope=SCOPE_SUBTREE,
1300 controls=["search_options:1:2"],
1301 attrs=attrs)
1302 empty = Message()
1303 empty.dn = entry[0].dn
1304 delta = samdb.msg_diff(entry[0], empty)
1305 delta.remove("dn")
1306 delta.dn = entry[0].dn
1307 samdb.modify(delta)
1309 def remove_stored_generated_attrs(paths, creds, session, lp):
1310 """Remove previously stored constructed attributes
1312 :param paths: List of paths for different provision objects
1313 from the upgraded provision
1314 :param creds: A credential object
1315 :param session: A session object
1316 :param lp: A line parser object
1317 :return: An associative array whose key are the different constructed
1318 attributes and the value the dn where this attributes were found.
1322 def simple_update_basesamdb(newpaths, paths, names):
1323 """Update the provision container db: sam.ldb
1324 This function is aimed at very old provision (before alpha9)
1326 :param newpaths: List of paths for different provision objects
1327 from the reference provision
1328 :param paths: List of paths for different provision objects
1329 from the upgraded provision
1330 :param names: List of key provision parameters"""
1332 message(SIMPLE, "Copy samdb")
1333 shutil.copy(newpaths.samdb, paths.samdb)
1335 message(SIMPLE, "Update partitions filename if needed")
1336 schemaldb = os.path.join(paths.private_dir, "schema.ldb")
1337 configldb = os.path.join(paths.private_dir, "configuration.ldb")
1338 usersldb = os.path.join(paths.private_dir, "users.ldb")
1339 samldbdir = os.path.join(paths.private_dir, "sam.ldb.d")
1341 if not os.path.isdir(samldbdir):
1342 os.mkdir(samldbdir)
1343 os.chmod(samldbdir, 0700)
1344 if os.path.isfile(schemaldb):
1345 shutil.copy(schemaldb, os.path.join(samldbdir,
1346 "%s.ldb"%str(names.schemadn).upper()))
1347 os.remove(schemaldb)
1348 if os.path.isfile(usersldb):
1349 shutil.copy(usersldb, os.path.join(samldbdir,
1350 "%s.ldb"%str(names.rootdn).upper()))
1351 os.remove(usersldb)
1352 if os.path.isfile(configldb):
1353 shutil.copy(configldb, os.path.join(samldbdir,
1354 "%s.ldb"%str(names.configdn).upper()))
1355 os.remove(configldb)
1358 def update_privilege(ref_private_path, cur_private_path):
1359 """Update the privilege database
1361 :param ref_private_path: Path to the private directory of the reference
1362 provision.
1363 :param cur_private_path: Path to the private directory of the current
1364 (and to be updated) provision."""
1365 message(SIMPLE, "Copy privilege")
1366 shutil.copy(os.path.join(ref_private_path, "privilege.ldb"),
1367 os.path.join(cur_private_path, "privilege.ldb"))
1370 def update_samdb(ref_samdb, samdb, names, highestUSN, schema, prereloadfunc):
1371 """Upgrade the SAM DB contents for all the provision partitions
1373 :param ref_sambdb: An LDB object conntected to the sam.ldb of the reference
1374 provision
1375 :param samdb: An LDB object connected to the sam.ldb of the update
1376 provision
1377 :param names: List of key provision parameters
1378 :param highestUSN: The highest USN modified by provision/upgradeprovision
1379 last time
1380 :param schema: A Schema object that represent the schema of the provision
1381 :param prereloadfunc: A function that must be executed just before the reload
1382 of the schema
1385 message(SIMPLE, "Starting update of samdb")
1386 ret = update_partition(ref_samdb, samdb, str(names.rootdn), names,
1387 schema, highestUSN, prereloadfunc)
1388 if ret:
1389 message(SIMPLE, "Update of samdb finished")
1390 return 1
1391 else:
1392 message(SIMPLE, "Update failed")
1393 return 0
1396 def copyxattrs(dir, refdir):
1397 """ Copy owner, groups, extended ACL and NT acls from
1398 a reference dir to a destination dir
1400 Both dir are supposed to hold the same files
1401 :param dir: Destination dir
1402 :param refdir: Reference directory"""
1404 noxattr = 0
1405 for root, dirs, files in os.walk(dir, topdown=True):
1406 for name in files:
1407 subdir=root[len(dir):]
1408 ref = os.path.join("%s%s" % (refdir, subdir), name)
1409 statsinfo = os.stat(ref)
1410 tgt = os.path.join(root, name)
1411 try:
1413 os.chown(tgt, statsinfo.st_uid, statsinfo.st_gid)
1414 # Get the xattr attributes if any
1415 try:
1416 attribute = samba.xattr_native.wrap_getxattr(ref,
1417 xattr.XATTR_NTACL_NAME)
1418 samba.xattr_native.wrap_setxattr(tgt,
1419 xattr.XATTR_NTACL_NAME,
1420 attribute)
1421 except:
1422 noxattr = 1
1423 attribute = samba.xattr_native.wrap_getxattr(ref,
1424 "system.posix_acl_access")
1425 samba.xattr_native.wrap_setxattr(tgt,
1426 "system.posix_acl_access",
1427 attribute)
1428 except:
1429 continue
1430 for name in dirs:
1431 subdir=root[len(dir):]
1432 ref = os.path.join("%s%s" % (refdir, subdir), name)
1433 statsinfo = os.stat(ref)
1434 tgt = os.path.join(root, name)
1435 try:
1436 os.chown(os.path.join(root, name), statsinfo.st_uid,
1437 statsinfo.st_gid)
1438 try:
1439 attribute = samba.xattr_native.wrap_getxattr(ref,
1440 xattr.XATTR_NTACL_NAME)
1441 samba.xattr_native.wrap_setxattr(tgt,
1442 xattr.XATTR_NTACL_NAME,
1443 attribute)
1444 except:
1445 noxattr = 1
1446 attribute = samba.xattr_native.wrap_getxattr(ref,
1447 "system.posix_acl_access")
1448 samba.xattr_native.wrap_setxattr(tgt,
1449 "system.posix_acl_access",
1450 attribute)
1452 except:
1453 continue
1456 def backup_provision(paths, dir):
1457 """This function backup the provision files so that a rollback
1458 is possible
1460 :param paths: Paths to different objects
1461 :param dir: Directory where to store the backup
1464 shutil.copytree(paths.sysvol, os.path.join(dir, "sysvol"))
1465 copyxattrs(os.path.join(dir, "sysvol"), paths.sysvol)
1466 shutil.copy2(paths.samdb, dir)
1467 shutil.copy2(paths.secrets, dir)
1468 shutil.copy2(paths.idmapdb, dir)
1469 shutil.copy2(paths.privilege, dir)
1470 if os.path.isfile(os.path.join(paths.private_dir,"eadb.tdb")):
1471 shutil.copy2(os.path.join(paths.private_dir,"eadb.tdb"), dir)
1472 shutil.copy2(paths.smbconf, dir)
1473 shutil.copy2(os.path.join(paths.private_dir,"secrets.keytab"), dir)
1475 samldbdir = os.path.join(paths.private_dir, "sam.ldb.d")
1476 if not os.path.isdir(samldbdir):
1477 samldbdir = paths.private_dir
1478 schemaldb = os.path.join(paths.private_dir, "schema.ldb")
1479 configldb = os.path.join(paths.private_dir, "configuration.ldb")
1480 usersldb = os.path.join(paths.private_dir, "users.ldb")
1481 shutil.copy2(schemaldb, dir)
1482 shutil.copy2(usersldb, dir)
1483 shutil.copy2(configldb, dir)
1484 else:
1485 shutil.copytree(samldbdir, os.path.join(dir, "sam.ldb.d"))
1490 def sync_calculated_attributes(samdb, names):
1491 """Synchronize attributes used for constructed ones, with the
1492 old constructed that were stored in the database.
1494 This apply for instance to msds-keyversionnumber that was
1495 stored and that is now constructed from replpropertymetadata.
1497 :param samdb: An LDB object attached to the currently upgraded samdb
1498 :param names: Various key parameter about current provision.
1500 listAttrs = ["msDs-KeyVersionNumber"]
1501 hash = search_constructed_attrs_stored(samdb, names.rootdn, listAttrs)
1502 if hash.has_key("msDs-KeyVersionNumber"):
1503 increment_calculated_keyversion_number(samdb, names.rootdn,
1504 hash["msDs-KeyVersionNumber"])
1506 # Synopsis for updateprovision
1507 # 1) get path related to provision to be update (called current)
1508 # 2) open current provision ldbs
1509 # 3) fetch the key provision parameter (domain sid, domain guid, invocationid
1510 # of the DC ....)
1511 # 4) research of lastProvisionUSN in order to get ranges of USN modified
1512 # by either upgradeprovision or provision
1513 # 5) creation of a new provision the latest version of provision script
1514 # (called reference)
1515 # 6) get reference provision paths
1516 # 7) open reference provision ldbs
1517 # 8) setup helpers data that will help the update process
1518 # 9) update the privilege ldb by copying the one of referecence provision to
1519 # the current provision
1520 # 10)get the oemInfo field, this field contains information about the different
1521 # provision that have been done
1522 # 11)Depending on whether oemInfo has the string "alpha9" or alphaxx (x as an
1523 # integer) or none of this the following things are done
1524 # A) When alpha9 or alphaxx is present
1525 # The base sam.ldb file is updated by looking at the difference between
1526 # referrence one and the current one. Everything is copied with the
1527 # exception of lastProvisionUSN attributes.
1528 # B) Other case (it reflect that that provision was done before alpha9)
1529 # The base sam.ldb of the reference provision is copied over
1530 # the current one, if necessary ldb related to partitions are moved
1531 # and renamed
1532 # The highest used USN is fetched so that changed by upgradeprovision
1533 # usn can be tracked
1534 # 12)A Schema object is created, it will be used to provide a complete
1535 # schema to current provision during update (as the schema of the
1536 # current provision might not be complete and so won't allow some
1537 # object to be created)
1538 # 13)Proceed to full update of sam DB (see the separate paragraph about i)
1539 # 14)The secrets db is updated by pull all the difference from the reference
1540 # provision into the current provision
1541 # 15)As the previous step has most probably modified the password stored in
1542 # in secret for the current DC, a new password is generated,
1543 # the kvno is bumped and the entry in samdb is also updated
1544 # 16)For current provision older than alpha9, we must fix the SD a little bit
1545 # administrator to update them because SD used to be generated with the
1546 # system account before alpha9.
1547 # 17)The highest usn modified so far is searched in the database it will be
1548 # the upper limit for usn modified during provision.
1549 # This is done before potential SD recalculation because we do not want
1550 # SD modified during recalculation to be marked as modified during provision
1551 # (and so possibly remplaced at next upgradeprovision)
1552 # 18)Rebuilt SD if the flag indicate to do so
1553 # 19)Check difference between SD of reference provision and those of the
1554 # current provision. The check is done by getting the sddl representation
1555 # of the SD. Each sddl in chuncked into parts (user,group,dacl,sacl)
1556 # Each part is verified separetly, for dacl and sacl ACL is splited into
1557 # ACEs and each ACE is verified separately (so that a permutation in ACE
1558 # didn't raise as an error).
1559 # 20)The oemInfo field is updated to add information about the fact that the
1560 # provision has been updated by the upgradeprovision version xxx
1561 # (the version is the one obtained when starting samba with the --version
1562 # parameter)
1563 # 21)Check if the current provision has all the settings needed for dynamic
1564 # DNS update to work (that is to say the provision is newer than
1565 # january 2010). If not dns configuration file from reference provision
1566 # are copied in a sub folder and the administrator is invited to
1567 # do what is needed.
1568 # 22)If the lastProvisionUSN attribute was present it is updated to add
1569 # the range of usns modified by the current upgradeprovision
1572 # About updating the sam DB
1573 # The update takes place in update_partition function
1574 # This function read both current and reference provision and list all
1575 # the available DN of objects
1576 # If the string representation of a DN in reference provision is
1577 # equal to the string representation of a DN in current provision
1578 # (without taking care of case) then the object is flaged as being
1579 # present. If the object is not present in current provision the object
1580 # is being flaged as missing in current provision. Object present in current
1581 # provision but not in reference provision are ignored.
1582 # Once the list of objects present and missing is done, the deleted object
1583 # containers are created in the differents partitions (if missing)
1585 # Then the function add_missing_entries is called
1586 # This function will go through the list of missing entries by calling
1587 # add_missing_object for the given object. If this function returns 0
1588 # it means that the object needs some other object in order to be created
1589 # The object is reappended at the end of the list to be created later
1590 # (and preferably after all the needed object have been created)
1591 # The function keeps on looping on the list of object to be created until
1592 # it's empty or that the number of defered creation is equal to the number
1593 # of object that still needs to be created.
1595 # The function add_missing_object will first check if the object can be created.
1596 # That is to say that it didn't depends other not yet created objects
1597 # If requisit can't be fullfilled it exists with 0
1598 # Then it will try to create the missing entry by creating doing
1599 # an ldb_message_diff between the object in the reference provision and
1600 # an empty object.
1601 # This resulting object is filtered to remove all the back link attribute
1602 # (ie. memberOf) as they will be created by the other linked object (ie.
1603 # the one with the member attribute)
1604 # All attributes specified in the hashAttrNotCopied associative array are
1605 # also removed it's most of the time generated attributes
1607 # After missing entries have been added the update_partition function will
1608 # take care of object that exist but that need some update.
1609 # In order to do so the function update_present is called with the list
1610 # of object that are present in both provision and that might need an update.
1612 # This function handle first case mismatch so that the DN in the current
1613 # provision have the same case as in reference provision
1615 # It will then construct an associative array consiting of attributes as
1616 # key and invocationid as value( if the originating invocation id is
1617 # different from the invocation id of the current DC the value is -1 instead).
1619 # If the range of provision modified attributes is present, the function will
1620 # use the replMetadataProperty update method which is the following:
1621 # Removing attributes that should not be updated: rIDAvailablePool, objectSid,
1622 # creationTime, msDs-KeyVersionNumber, oEMInformation
1623 # Check for each attribute if its usn is within one of the modified by
1624 # provision range and if its originating id is the invocation id of the
1625 # current DC, then validate the update from reference to current.
1626 # If not or if there is no replMetatdataProperty for this attribute then we
1627 # do not update it.
1628 # Otherwise (case the range of provision modified attribute is not present) it
1629 # use the following process:
1630 # All attributes that need to be added are accepted at the exeption of those
1631 # listed in hashOverwrittenAtt, in this case the attribute needs to have the
1632 # correct flags specified.
1633 # For attributes that need to be modified or removed, a check is performed
1634 # in OverwrittenAtt, if the attribute is present and the modification flag
1635 # (remove, delete) is one of those listed for this attribute then modification
1636 # is accepted. For complicated handling of attribute update, the control is passed
1637 # to handle_special_case
1641 if __name__ == '__main__':
1642 global defSDmodified
1643 defSDmodified = False
1644 # From here start the big steps of the program
1645 # 1) First get files paths
1646 paths = get_paths(param, smbconf=smbconf)
1647 # Get ldbs with the system session, it is needed for searching
1648 # provision parameters
1649 session = system_session()
1651 # This variable will hold the last provision USN once if it exists.
1652 minUSN = 0
1653 # 2)
1654 ldbs = get_ldbs(paths, creds, session, lp)
1655 backupdir = tempfile.mkdtemp(dir=paths.private_dir,
1656 prefix="backupprovision")
1657 backup_provision(paths, backupdir)
1658 try:
1659 ldbs.startTransactions()
1661 # 3) Guess all the needed names (variables in fact) from the current
1662 # provision.
1663 names = find_provision_key_parameters(ldbs.sam, ldbs.secrets, ldbs.idmap,
1664 paths, smbconf, lp)
1665 # 4)
1666 lastProvisionUSNs = get_last_provision_usn(ldbs.sam)
1667 if lastProvisionUSNs is not None:
1668 message(CHANGE,
1669 "Find a last provision USN, %d range(s)" % len(lastProvisionUSNs))
1671 # Objects will be created with the admin session
1672 # (not anymore system session)
1673 adm_session = admin_session(lp, str(names.domainsid))
1674 # So we reget handle on objects
1675 # ldbs = get_ldbs(paths, creds, adm_session, lp)
1676 if not opts.fixntacl:
1677 if not sanitychecks(ldbs.sam, names):
1678 message(SIMPLE, "Sanity checks for the upgrade have failed. "
1679 "Check the messages and correct the errors "
1680 "before rerunning upgradeprovision")
1681 ldbs.groupedRollback()
1682 sys.exit(1)
1684 # Let's see provision parameters
1685 print_provision_key_parameters(names)
1687 # 5) With all this information let's create a fresh new provision used as
1688 # reference
1689 message(SIMPLE, "Creating a reference provision")
1690 provisiondir = tempfile.mkdtemp(dir=paths.private_dir,
1691 prefix="referenceprovision")
1692 newprovision(names, creds, session, smbconf, provisiondir,
1693 provision_logger)
1695 # TODO
1696 # 6) and 7)
1697 # We need to get a list of object which SD is directly computed from
1698 # defaultSecurityDescriptor.
1699 # This will allow us to know which object we can rebuild the SD in case
1700 # of change of the parent's SD or of the defaultSD.
1701 # Get file paths of this new provision
1702 newpaths = get_paths(param, targetdir=provisiondir)
1703 new_ldbs = get_ldbs(newpaths, creds, session, lp)
1704 new_ldbs.startTransactions()
1706 # 8) Populate some associative array to ease the update process
1707 # List of attribute which are link and backlink
1708 populate_links(new_ldbs.sam, names.schemadn)
1709 # List of attribute with ASN DN synthax)
1710 populate_dnsyntax(new_ldbs.sam, names.schemadn)
1711 # 9)
1712 update_privilege(newpaths.private_dir, paths.private_dir)
1713 # 10)
1714 oem = getOEMInfo(ldbs.sam, str(names.rootdn))
1715 # Do some modification on sam.ldb
1716 ldbs.groupedCommit()
1717 new_ldbs.groupedCommit()
1718 deltaattr = None
1719 # 11)
1720 if re.match(".*alpha((9)|(\d\d+)).*", str(oem)):
1721 # 11) A
1722 # Starting from alpha9 we can consider that the structure is quite ok
1723 # and that we should do only dela
1724 deltaattr = delta_update_basesamdb(newpaths.samdb,
1725 paths.samdb,
1726 creds,
1727 session,
1729 message)
1730 else:
1731 # 11) B
1732 simple_update_basesamdb(newpaths, paths, names)
1733 ldbs = get_ldbs(paths, creds, session, lp)
1734 removeProvisionUSN(ldbs.sam)
1736 ldbs.startTransactions()
1737 minUSN = int(str(get_max_usn(ldbs.sam, str(names.rootdn)))) + 1
1738 new_ldbs.startTransactions()
1740 # 12)
1741 schema = Schema(names.domainsid, schemadn=str(names.schemadn))
1742 # We create a closure that will be invoked just before schema reload
1743 def schemareloadclosure():
1744 basesam = Ldb(paths.samdb, session_info=session, credentials=creds, lp=lp,
1745 options=["modules:"])
1746 doit = False
1747 if deltaattr is not None and len(deltaattr) > 1:
1748 doit = True
1749 if doit:
1750 deltaattr.remove("dn")
1751 for att in deltaattr:
1752 if att.lower() == "dn":
1753 continue
1754 if (deltaattr.get(att) is not None
1755 and deltaattr.get(att).flags() != FLAG_MOD_ADD):
1756 doit = False
1757 elif deltaattr.get(att) is None:
1758 doit = False
1759 if doit:
1760 message(CHANGE, "Applying delta to @ATTRIBUTES")
1761 deltaattr.dn = ldb.Dn(basesam, "@ATTRIBUTES")
1762 basesam.modify(deltaattr)
1763 else:
1764 message(CHANGE, "Not applying delta to @ATTRIBUTES because "
1765 "there is not only add")
1766 # 13)
1767 if opts.full:
1768 if not update_samdb(new_ldbs.sam, ldbs.sam, names, lastProvisionUSNs,
1769 schema, schemareloadclosure):
1770 message(SIMPLE, "Rolling back all changes. Check the cause"
1771 " of the problem")
1772 message(SIMPLE, "Your system is as it was before the upgrade")
1773 ldbs.groupedRollback()
1774 new_ldbs.groupedRollback()
1775 shutil.rmtree(provisiondir)
1776 sys.exit(1)
1777 else:
1778 # Try to reapply the change also when we do not change the sam
1779 # as the delta_upgrade
1780 schemareloadclosure()
1781 sync_calculated_attributes(ldbs.sam, names)
1782 res = ldbs.sam.search(expression="(samaccountname=dns)",
1783 scope=SCOPE_SUBTREE, attrs=["dn"],
1784 controls=["search_options:1:2"])
1785 if len(res) > 0:
1786 message(SIMPLE, "You still have the old DNS object for managing "
1787 "dynamic DNS, but you didn't supply --full so "
1788 "a correct update can't be done")
1789 ldbs.groupedRollback()
1790 new_ldbs.groupedRollback()
1791 shutil.rmtree(provisiondir)
1792 sys.exit(1)
1793 # 14)
1794 update_secrets(new_ldbs.secrets, ldbs.secrets, message)
1795 # 14bis)
1796 res = ldbs.sam.search(expression="(samaccountname=dns)",
1797 scope=SCOPE_SUBTREE, attrs=["dn"],
1798 controls=["search_options:1:2"])
1800 if (len(res) == 1):
1801 ldbs.sam.delete(res[0]["dn"])
1802 res2 = ldbs.secrets.search(expression="(samaccountname=dns)",
1803 scope=SCOPE_SUBTREE, attrs=["dn"])
1804 update_dns_account_password(ldbs.sam, ldbs.secrets, names)
1805 message(SIMPLE, "IMPORTANT!!! "
1806 "If you were using Dynamic DNS before you need "
1807 "to update your configuration, so that the "
1808 "tkey-gssapi-credential has the following value: "
1809 "DNS/%s.%s" % (names.netbiosname.lower(),
1810 names.realm.lower()))
1811 # 15)
1812 message(SIMPLE, "Update machine account")
1813 update_machine_account_password(ldbs.sam, ldbs.secrets, names)
1815 # 16) SD should be created with admin but as some previous acl were so wrong
1816 # that admin can't modify them we have first to recreate them with the good
1817 # form but with system account and then give the ownership to admin ...
1818 if not re.match(r'.*alpha(9|\d\d+)', str(oem)):
1819 message(SIMPLE, "Fixing old povision SD")
1820 fix_partition_sd(ldbs.sam, names)
1821 rebuild_sd(ldbs.sam, names)
1823 # We calculate the max USN before recalculating the SD because we might
1824 # touch object that have been modified after a provision and we do not
1825 # want that the next upgradeprovision thinks that it has a green light
1826 # to modify them
1828 # 17)
1829 maxUSN = get_max_usn(ldbs.sam, str(names.rootdn))
1831 # 18) We rebuild SD only if defaultSecurityDescriptor is modified
1832 # But in fact we should do it also if one object has its SD modified as
1833 # child might need rebuild
1834 if defSDmodified:
1835 message(SIMPLE, "Updating SD")
1836 ldbs.sam.set_session_info(adm_session)
1837 # Alpha10 was a bit broken still
1838 if re.match(r'.*alpha(\d|10)', str(oem)):
1839 fix_partition_sd(ldbs.sam, names)
1840 rebuild_sd(ldbs.sam, names)
1842 # 19)
1843 # Now we are quite confident in the recalculate process of the SD, we make
1844 # it optional.
1845 # Also the check must be done in a clever way as for the moment we just
1846 # compare SDDL
1847 if opts.debugchangesd:
1848 check_updated_sd(new_ldbs.sam, ldbs.sam, names)
1850 # 20)
1851 updateOEMInfo(ldbs.sam, str(names.rootdn))
1852 # 21)
1853 check_for_DNS(newpaths.private_dir, paths.private_dir)
1854 # 22)
1855 if lastProvisionUSNs is not None:
1856 update_provision_usn(ldbs.sam, minUSN, maxUSN)
1857 if opts.full and (names.policyid is None or names.policyid_dc is None):
1858 update_policyids(names, ldbs.sam)
1859 if opts.full or opts.resetfileacl or opts.fixntacl:
1860 try:
1861 update_gpo(paths, ldbs.sam, names, lp, message, 1)
1862 except ProvisioningError, e:
1863 message(ERROR, "The policy for domain controller is missing. "
1864 "You should restart upgradeprovision with --full")
1865 except IOError, e:
1866 message(ERROR, "Setting ACL not supported on your filesystem")
1867 else:
1868 try:
1869 update_gpo(paths, ldbs.sam, names, lp, message, 0)
1870 except ProvisioningError, e:
1871 message(ERROR, "The policy for domain controller is missing. "
1872 "You should restart upgradeprovision with --full")
1873 if not opts.fixntacl:
1874 ldbs.groupedCommit()
1875 new_ldbs.groupedCommit()
1876 message(SIMPLE, "Upgrade finished!")
1877 # remove reference provision now that everything is done !
1878 # So we have reindexed first if need when the merged schema was reloaded
1879 # (as new attributes could have quick in)
1880 # But the second part of the update (when we update existing objects
1881 # can also have an influence on indexing as some attribute might have their
1882 # searchflag modificated
1883 message(SIMPLE, "Reopenning samdb to trigger reindexing if needed "
1884 "after modification")
1885 samdb = Ldb(paths.samdb, session_info=session, credentials=creds, lp=lp)
1886 message(SIMPLE, "Reindexing finished")
1888 shutil.rmtree(provisiondir)
1889 else:
1890 ldbs.groupedRollback()
1891 message(SIMPLE, "ACLs fixed !")
1892 except StandardError, err:
1893 message(ERROR, "A problem occurred while trying to upgrade your "
1894 "provision. A full backup is located at %s" % backupdir)
1895 if opts.debugall or opts.debugchange:
1896 (typ, val, tb) = sys.exc_info()
1897 traceback.print_exception(typ, val, tb)
1898 sys.exit(1)