s4:upgradeschema.py Cleanup
[ira/wip.git] / source4 / scripting / bin / upgradeschema.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) Matthieu Patou <mat@matws.net> 2009
4 #
5 # Based on provision a Samba4 server by
6 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
7 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
8 #
9 #   
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #   
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #   
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
23
24 import getopt
25 import shutil
26 import optparse
27 import os
28 import sys
29 import random
30 import string
31 import re
32 import base64
33 # Find right directory when running from source tree
34 sys.path.insert(0, "bin/python")
35
36 from base64 import b64encode
37
38 import samba
39 from samba.credentials import DONT_USE_KERBEROS
40 from samba.auth import system_session, admin_session
41 from samba import Ldb
42 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError
43 import ldb
44 import samba.getopt as options
45 from samba.samdb import SamDB
46 from samba import param
47 from samba.provision import  ProvisionNames,provision_paths_from_lp,find_setup_dir,FILL_FULL,provision
48 from samba.schema import get_dnsyntax_attributes, get_linked_attributes, Schema
49 from samba.dcerpc import misc, security
50 from samba.ndr import ndr_pack, ndr_unpack
51
52 replace=2^ldb.FLAG_MOD_REPLACE
53 add=2^ldb.FLAG_MOD_ADD
54 delete=2^ldb.FLAG_MOD_DELETE
55
56 CHANGE = 0x01
57 CHANGESD = 0x02
58 GUESS = 0x04
59 CHANGEALL = 0xff
60
61 # Attributes that not copied from the reference provision even if they do not exists in the destination object
62 # This is most probably because they are populated automatcally when object is created
63 hashAttrNotCopied = {   "dn": 1,"whenCreated": 1,"whenChanged": 1,"objectGUID": 1,"replPropertyMetaData": 1,"uSNChanged": 1,\
64                                                 "uSNCreated": 1,"parentGUID": 1,"objectCategory": 1,"distinguishedName": 1,\
65                                                 "showInAdvancedViewOnly": 1,"instanceType": 1, "cn": 1, "msDS-Behavior-Version":1, "nextRid":1,\
66                                                 "nTMixedDomain": 1,"versionNumber":1, "lmPwdHistory":1, "pwdLastSet": 1, "ntPwdHistory":1, "unicodePwd":1,\
67                                                 "dBCSPwd":1,"supplementalCredentials":1,"gPCUserExtensionNames":1, "gPCMachineExtensionNames":1,\
68                                                 "maxPwdAge":1, "mail":1, "secret":1}
69
70 # Usually for an object that already exists we do not overwrite attributes as they might have been changed for good
71 # reasons. Anyway for a few of thems it's mandatory to replace them otherwise the provision will be broken somehow.
72 hashOverwrittenAtt = {   "prefixMap": replace, "systemMayContain": replace,"systemOnly":replace, "searchFlags":replace,\
73                                                  "mayContain":replace,  "systemFlags":replace, 
74                                                  "oEMInformation":replace, "operatingSystemVersion":replace, "adminPropertyPages":1,"possibleInferiors":replace+delete}
75 backlinked = []
76
77 def define_what_to_log(opts):
78         what = 0
79         if opts.debugchange:
80                 what = what | CHANGE
81         if opts.debugchangesd:
82                 what = what | CHANGESD
83         if opts.debugguess:
84                 what = what | GUESS
85         if opts.debugall:
86                 what = what | CHANGEALL
87         return what
88
89
90
91 parser = optparse.OptionParser("provision [options]")
92 sambaopts = options.SambaOptions(parser)
93 parser.add_option_group(sambaopts)
94 parser.add_option_group(options.VersionOptions(parser))
95 credopts = options.CredentialsOptions(parser)
96 parser.add_option_group(credopts)
97 parser.add_option("--setupdir", type="string", metavar="DIR", 
98                                         help="directory with setup files")
99 parser.add_option("--debugprovision", help="Debug provision", action="store_true")
100 parser.add_option("--debugguess", help="Print information on what is different but won't be changed", action="store_true")
101 parser.add_option("--debugchange", help="Print information on what is different but won't be changed", action="store_true")
102 parser.add_option("--debugchangesd", help="Print information security descriptors differences", action="store_true")
103 parser.add_option("--debugall", help="Print all available information (very verbose)", action="store_true")
104 parser.add_option("--targetdir", type="string", metavar="DIR", 
105                                         help="Set target directory")
106
107 opts = parser.parse_args()[0]
108
109 whatToLog = define_what_to_log(opts)
110
111 def messageprovision(text):
112         """print a message if quiet is not set."""
113         if opts.debugprovision or opts.debugall:
114                 print text
115
116 def message(what,text):
117         """print a message if quiet is not set."""
118         if whatToLog & what:
119                 print text
120
121 if len(sys.argv) == 1:
122         opts.interactive = True
123 lp = sambaopts.get_loadparm()
124 smbconf = lp.configfile
125
126 creds = credopts.get_credentials(lp)
127 creds.set_kerberos_state(DONT_USE_KERBEROS)
128 setup_dir = opts.setupdir
129 if setup_dir is None:
130     setup_dir = find_setup_dir()
131
132 session = system_session()
133
134 # Create an array of backlinked attributes
135 def populate_backlink(newpaths,creds,session,schemadn):
136         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
137         backlinked.extend(get_linked_attributes(ldb.Dn(newsam_ldb,str(schemadn)),newsam_ldb).values())
138
139 # Get Paths for important objects (ldb, keytabs ...)
140 def get_paths(targetdir=None,smbconf=None):
141         if targetdir is not None:
142                 if (not os.path.exists(os.path.join(targetdir, "etc"))):
143                         os.makedirs(os.path.join(targetdir, "etc"))
144                 smbconf = os.path.join(targetdir, "etc", "smb.conf")
145         if smbconf is None:
146                         smbconf = param.default_path()
147
148         if not os.path.exists(smbconf):
149                 print >>sys.stderr, "Unable to find smb.conf .."
150                 parser.print_usage()
151                 sys.exit(1)
152
153         lp = param.LoadParm()
154         lp.load(smbconf)
155 # Normaly we need the domain name for this function but for our needs it's pointless 
156         paths = provision_paths_from_lp(lp,"foo")
157         return paths
158
159 # This function guess(fetch) informations needed to make a fresh provision from the current provision   
160 # It includes: realm, workgroup, partitions, netbiosname, domain guid, ...
161 def guess_names_from_current_provision(credentials,session_info,paths):
162         lp = param.LoadParm()
163         lp.load(paths.smbconf)
164         names = ProvisionNames()
165         # NT domain, kerberos realm, root dn, domain dn, domain dns name
166         names.domain = string.upper(lp.get("workgroup"))
167         names.realm = lp.get("realm")
168         rootdn = "DC=" + names.realm.replace(".",",DC=")
169         names.domaindn = rootdn
170         names.dnsdomain = names.realm
171         names.realm = string.upper(names.realm)
172         # netbiosname
173         secrets_ldb = Ldb(paths.secrets, session_info=session_info, credentials=credentials,lp=lp)
174         # Get the netbiosname first (could be obtained from smb.conf in theory)
175         attrs = ["sAMAccountName"]
176         res = secrets_ldb.search(expression="(flatname=%s)"%names.domain,base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=attrs)
177         names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
178
179         #partitions = get_partitions(credentials,session_info,paths,lp)
180         names.smbconf = smbconf
181         samdb = SamDB(paths.samdb, session_info=session_info,
182                                                                 credentials=credentials, lp=lp)
183         
184         # partitions (schema,config,root)
185         # That's a bit simplistic but it's ok as long as we have only 3 partitions 
186         attrs2 = ["schemaNamingContext","configurationNamingContext","rootDomainNamingContext"]
187         res2 = samdb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
188
189         names.configdn = res2[0]["configurationNamingContext"]
190         configdn = str(names.configdn)
191         names.schemadn = res2[0]["schemaNamingContext"]
192         if not (rootdn == str(res2[0]["rootDomainNamingContext"])):
193                 print >>sys.stderr, "rootdn in sam.ldb and smb.conf is not the same ..."
194         else:
195                 names.rootdn=res2[0]["rootDomainNamingContext"]
196         # default site name
197         attrs3 = ["cn"]
198         res3= samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=attrs3)
199         names.sitename = str(res3[0]["cn"])
200         
201         # dns hostname and server dn 
202         attrs4 = ["dNSHostName"]
203         res4= samdb.search(expression="(CN=%s)"%names.netbiosname,base="OU=Domain Controllers,"+rootdn, \
204                                                 scope=SCOPE_ONELEVEL, attrs=attrs4)
205         names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
206
207         names.serverdn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (names.netbiosname, names.sitename, configdn)
208         
209         # invocation id
210         attrs5 = ["invocationId"]
211         res5 = samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_SUBTREE, attrs=attrs5)
212         for i in range(0,len(res5)):
213                 if ( len(res5[i]) > 0):
214                         names.invocation = str(ndr_unpack( misc.GUID,res5[i]["invocationId"][0]))
215                         break
216         # domain guid/sid
217         attrs6 = ["objectGUID", "objectSid", ]
218         res6 = samdb.search(expression="(objectClass=*)",base=rootdn, scope=SCOPE_BASE, attrs=attrs6)
219         names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
220         names.domainsid = str(ndr_unpack( security.dom_sid,res6[0]["objectSid"][0]))
221
222         # policy guid
223         attrs7 = ["cn","displayName"]
224         res7 = samdb.search(expression="(displayName=Default Domain Policy)",base="CN=Policies,CN=System,"+rootdn, \
225                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
226         names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
227         # dc policy guid
228         attrs8 = ["cn","displayName"]
229         res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",base="CN=Policies,CN=System,"+rootdn, \
230                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
231         if len(res8) == 1:
232                 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
233         else:
234                 names.policyid_dc = None
235         # ntds guid
236         attrs9 = ["objectGUID" ]
237         exp = "(dn=CN=NTDS Settings,%s)"%(names.serverdn)
238         print exp
239         res9 = samdb.search(expression="(dn=CN=NTDS Settings,%s)"%(names.serverdn),base=str(names.configdn), scope=SCOPE_SUBTREE, attrs=attrs9)
240         names.ntdsguid = str(ndr_unpack( misc.GUID,res9[0]["objectGUID"][0]))
241
242
243         return names
244
245 # Debug a little bit
246 def print_names(names):
247         message(GUESS, "rootdn      :"+str(names.rootdn))
248         message(GUESS, "configdn    :"+str(names.configdn))
249         message(GUESS, "schemadn    :"+str(names.schemadn))
250         message(GUESS, "serverdn    :"+names.serverdn)
251         message(GUESS, "netbiosname :"+names.netbiosname)
252         message(GUESS, "defaultsite :"+names.sitename)
253         message(GUESS, "dnsdomain   :"+names.dnsdomain)
254         message(GUESS, "hostname    :"+names.hostname)
255         message(GUESS, "domain      :"+names.domain)
256         message(GUESS, "realm       :"+names.realm)
257         message(GUESS, "invocationid:"+names.invocation)
258         message(GUESS, "policyguid  :"+names.policyid)
259         message(GUESS, "policyguiddc:"+str(names.policyid_dc))
260         message(GUESS, "domainsid   :"+names.domainsid)
261         message(GUESS, "domainguid  :"+names.domainguid)
262         message(GUESS, "ntdsguid    :"+names.ntdsguid)
263
264 # Create a fresh new reference provision
265 # This provision will be the reference for knowing what has changed in the 
266 # since the latest upgrade in the current provision
267 def newprovision(names,setup_dir,creds,session,smbconf):
268         random.seed()
269         provdir=os.path.join(os.environ["HOME"],"provision"+str(int(100000*random.random())))
270         logstd=os.path.join(provdir,"log.std")
271         os.chdir(os.path.join(setup_dir,".."))
272         os.mkdir(provdir)
273
274         provision(setup_dir, messageprovision,
275                 session, creds, smbconf=smbconf, targetdir=provdir,
276                 samdb_fill=FILL_FULL, realm=names.realm, domain=names.domain,
277                 domainguid=names.domainguid, domainsid=names.domainsid,ntdsguid=names.ntdsguid,
278                 policyguid=names.policyid,policyguid_dc=names.policyid_dc,hostname=names.hostname,
279                 hostip=None, hostip6=None,
280                 invocationid=names.invocation, adminpass=None,
281                 krbtgtpass=None, machinepass=None,
282                 dnspass=None, root=None, nobody=None,
283                 wheel=None, users=None,
284                 serverrole="domain controller",
285                 ldap_backend_extra_port=None,
286                 backend_type=None,
287                 ldapadminpass=None,
288                 ol_mmr_urls=None,
289                 slapd_path=None,
290                 setup_ds_path=None,
291                 nosync=None,
292                 ldap_dryrun_mode=None)
293         print >>sys.stderr, "provisiondir: "+provdir
294         return provdir
295
296 # This function sorts two dn in the lexicographical order and put higher level DN before
297 # So given the dns cn=bar,cn=foo and cn=foo the later will be return as smaller (-1) as it has less 
298 # level
299 def dn_sort(x,y):
300         p = re.compile(r'(?<!\\),')
301         tab1 = p.split(str(x))
302         tab2 = p.split(str(y))
303         min = 0
304         if (len(tab1) > len(tab2)):
305                 min = len(tab2)
306         elif (len(tab1) < len(tab2)):
307                 min = len(tab1) 
308         else: 
309                 min = len(tab1)
310         len1=len(tab1)-1
311         len2=len(tab2)-1
312         space = " "
313         # Note: python range go up to upper limit but do not include it
314         for i in range(0,min):
315                 ret=cmp(tab1[len1-i],tab2[len2-i])
316                 if(ret != 0):
317                         return ret      
318                 else:
319                         if(i==min-1):
320                                 if(len1==len2):
321                                         print >>sys.stderr,"PB PB PB"+space.join(tab1)+" / "+space.join(tab2)
322                                 if(len1>len2):
323                                         return 1
324                                 else:
325                                         return -1
326         return ret
327
328 # check from security descriptors modifications return 1 if it is 0 otherwise
329 # it also populate hash structure for later use in the upgrade process
330 def handle_security_desc(ischema,att,msgElt,hashallSD,old,new):
331         if ischema == 1 and att == "defaultSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
332                 hashSD = {}
333                 hashSD["oldSD"] = old[0][att]
334                 hashSD["newSD"] = new[0][att]
335                 hashallSD[str(old[0].dn)] = hashSD
336                 return 1
337         if att == "nTSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
338                 if ischema == 0:
339                         hashSD = {}
340                         hashSD["oldSD"] =  ndr_unpack(security.descriptor,str(old[0][att]))
341                         hashSD["newSD"] =  ndr_unpack(security.descriptor,str(new[0][att]))
342                         hashallSD[str(old[0].dn)] = hashSD
343                 return 1
344         return 0
345
346 # Hangle special cases ... That's when we want to update an attribute only 
347 # if it has a certain value or if it's for a certain object or 
348 # a class of object. 
349 # It can be also if we want to do a merge of value instead of a simple replace 
350 def handle_special_case(att,delta,new,old,ischema):
351         flag = delta.get(att).flags()
352         if (att == "gPLink" or att == "gPCFileSysPath") and flag ==  ldb.FLAG_MOD_REPLACE and str(new[0].dn).lower() == str(old[0].dn).lower():
353                 delta.remove(att)
354                 return 1
355         if att == "forceLogoff":
356                 ref=0x8000000000000000 
357                 oldval=int(old[0][att][0])
358                 newval=int(new[0][att][0])
359                 ref == old and ref == abs(new)
360                 return 1
361         if (att == "adminDisplayName" or att == "adminDescription") and ischema:
362                 return 1
363         if (str(old[0].dn) == "CN=Samba4-Local-Domain,%s"%(str(names.schemadn)) and att == "defaultObjectCategory" and flag  == ldb.FLAG_MOD_REPLACE):
364                 return 1
365         if (str(old[0].dn) == "CN=S-1-5-11,CN=ForeignSecurityPrincipals,%s"%(str(names.rootdn)) and att == "description" and flag  == ldb.FLAG_MOD_DELETE):
366                 return 1
367         if (str(old[0].dn) == "CN=Title,%s"%(str(names.schemadn)) and att == "rangeUpper" and flag  == ldb.FLAG_MOD_REPLACE):
368                 return 1
369         if ( (att == "member" or att == "servicePrincipalName") and flag  == ldb.FLAG_MOD_REPLACE):
370
371                 hash = {}
372                 newval = []
373                 changeDelta=0
374                 for elem in old[0][att]:
375                         hash[str(elem)]=1
376                         newval.append(str(elem))
377
378                 for elem in new[0][att]:
379                         if not hash.has_key(str(elem)):
380                                 changeDelta=1
381                                 newval.append(str(elem))
382                 if changeDelta == 1:
383                         delta[att] = ldb.MessageElement(newval, ldb.FLAG_MOD_REPLACE, att)
384                 else:
385                         delta.remove(att)
386                 return 1
387         if (str(old[0].dn) == "%s"%(str(names.rootdn)) and att == "subRefs" and flag  == ldb.FLAG_MOD_REPLACE):
388                 return 1
389         if str(delta.dn).endswith("CN=DisplaySpecifiers,%s"%names.configdn):
390                 return 1
391         return 0
392
393 def update_secrets(newpaths,paths,creds,session):
394         newsam_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
395         sam_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
396         res = newsam_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
397         res2 = sam_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
398         delta = sam_ldb.msg_diff(res2[0],res[0])
399         delta.dn = res2[0].dn
400         sam_ldb.modify(delta)   
401
402         newsam_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
403         sam_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
404         res = newsam_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
405         res2 = sam_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
406         hash_new = {}
407         hash = {}
408         listMissing = []
409         listPresent = []
410
411         empty = ldb.Message()
412         for i in range(0,len(res)):
413                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
414         
415         # Create a hash for speeding the search of existing object in the current provision
416         for i in range(0,len(res2)):
417                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
418
419         for k in hash_new.keys():
420                 if not hash.has_key(k):
421                         listMissing.append(hash_new[k])
422                 else:
423                         listPresent.append(hash_new[k])
424         for entry in listMissing:
425                 res = newsam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
426                 res2 = sam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
427                 delta = sam_ldb.msg_diff(empty,res[0])
428                 for att in hashAttrNotCopied.keys():
429                         delta.remove(att)
430                 message(CHANGE,"Entry %s is missing from secrets.ldb"%res[0].dn)
431                 for att in delta:
432                         message(CHANGE," Adding attribute %s"%att)
433                 delta.dn = res[0].dn
434                 sam_ldb.add(delta)      
435
436         for entry in listPresent:
437                 res = newsam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
438                 res2 = sam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
439                 delta = sam_ldb.msg_diff(res2[0],res[0])
440                 i=0
441                 for att in hashAttrNotCopied.keys():
442                         delta.remove(att)
443                 for att in delta:
444                         i = i + 1
445                         if att != "dn":
446                                 message(CHANGE," Adding/Changing attribute %s to %s"%(att,res2[0].dn))
447                                 
448                 delta.dn = res2[0].dn
449                 sam_ldb.modify(delta)   
450
451 # Check difference between the current provision and the reference provision.
452 # It looks for all object which base DN is name if ischema is false then scan is done in 
453 # cross partition mode.
454 # If ischema is true, then special handling is done for dealing with schema
455 def check_diff_name(newpaths,paths,creds,session,basedn,names,ischema):
456         hash_new = {}
457         hash = {}
458         hashallSD = {}
459         listMissing = []
460         listPresent = []
461         res = []
462         res2 = []
463         # Connect to the reference provision and get all the attribute in the partition referred by name
464         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
465         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
466         if ischema:
467                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
468                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
469         else:
470                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
471                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
472                 
473         # Create a hash for speeding the search of new object
474         for i in range(0,len(res)):
475                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
476         
477         # Create a hash for speeding the search of existing object in the current provision
478         for i in range(0,len(res2)):
479                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
480
481         for k in hash_new.keys():
482                 if not hash.has_key(k):
483                         listMissing.append(hash_new[k])
484                 else:
485                         listPresent.append(hash_new[k])
486
487         # Sort the missing object in order to have object of the lowest level first (which can be 
488         # containers for higher level objects)
489         listMissing.sort(dn_sort)
490         listPresent.sort(dn_sort)
491
492         if ischema:
493                 # The following lines (up to the for loop) is to load the up to date schema into our current LDB 
494                 # a complete schema is needed as the insertion of attributes and class is done against it 
495                 # and the schema is self validated
496                 # The double ldb open and schema validation is taken from the initial provision script
497                 # it's not certain that it is really needed ....
498                 sam_ldb = Ldb(session_info=session, credentials=creds, lp=lp)
499                 schema = Schema(setup_path, security.dom_sid(names.domainsid), schemadn=basedn, serverdn=names.serverdn)
500                 # Load the schema from the one we computed earlier
501                 sam_ldb.set_schema_from_ldb(schema.ldb)
502                 # And now we can connect to the DB - the schema won't be loaded from the DB
503                 sam_ldb.connect(paths.samdb)
504                 sam_ldb.transaction_start()
505         else:   
506                 sam_ldb.transaction_start()
507
508         empty = ldb.Message()
509         print "There are %d missing objects"%(len(listMissing))
510         for dn in listMissing:
511                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
512                 delta = sam_ldb.msg_diff(empty,res[0])
513                 for att in hashAttrNotCopied.keys():
514                         delta.remove(att)
515                 for att in backlinked:
516                         delta.remove(att)
517                 delta.dn = dn
518
519                 sam_ldb.add(delta,["relax:0"])
520
521         changed = 0
522         for dn in listPresent:
523                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
524                 res2 = sam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
525                 delta = sam_ldb.msg_diff(res2[0],res[0])
526                 for att in hashAttrNotCopied.keys():
527                         delta.remove(att)
528                 for att in backlinked:
529                         delta.remove(att)
530                 delta.remove("parentGUID")
531                 nb = 0
532                 for att in delta:
533                         msgElt = delta.get(att)
534                         if att == "dn":
535                                 continue
536                         if handle_security_desc(ischema,att,msgElt,hashallSD,res2,res):
537                                 delta.remove(att)
538                                 continue
539                         if (not hashOverwrittenAtt.has_key(att) or not (hashOverwrittenAtt.get(att)&2^msgElt.flags())):
540                                 if  handle_special_case(att,delta,res,res2,ischema)==0 and msgElt.flags()!=ldb.FLAG_MOD_ADD:
541                                         i = 0
542                                         if opts.debugchange:
543                                                 message(CHANGE, "dn= "+str(dn)+ " "+att + " with flag "+str(msgElt.flags())+ " is not allowed to be changed/removed, I discard this change ...")
544                                                 for e in range(0,len(res2[0][att])):
545                                                         message(CHANGE,"old %d : %s"%(i,str(res2[0][att][e])))
546                                                 if msgElt.flags() == 2:
547                                                         i = 0
548                                                         for e in range(0,len(res[0][att])):
549                                                                 message(CHANGE,"new %d : %s"%(i,str(res[0][att][e])))
550                                         delta.remove(att)
551                 delta.dn = dn
552                 if len(delta.items()) >1:
553                         attributes=",".join(delta.keys())
554                         message(CHANGE,"%s is different from the reference one, changed attributes: %s"%(dn,attributes))
555                         changed = changed + 1
556                         sam_ldb.modify(delta)
557
558         sam_ldb.transaction_commit()
559         print "There are %d changed objects"%(changed)
560         return hashallSD
561
562
563 # This function updates SD for AD objects.
564 # As SD in the upgraded provision can be different for various reasons 
565 # this function check if an automatic update can be performed and do it 
566 # or if it can't be done.
567 def update_sds(diffDefSD,diffSD,paths,creds,session,rootdn,domSIDTxt):
568         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
569         sam_ldb.transaction_start()
570         domSID = security.dom_sid(domSIDTxt)
571         hashClassSD = {}
572         admin_session_info = admin_session(lp, str(domSID))
573         system_session_info = system_session()
574         upgrade = 0
575         for dn in diffSD.keys():
576                 newSD = diffSD[dn]["newSD"].as_sddl(domSID)
577                 oldSD = diffSD[dn]["oldSD"].as_sddl(domSID)
578                 message(CHANGESD, "ntsecuritydescriptor for %s has changed old %s new %s"%(dn,oldSD,diffSD[dn]["newSD"].as_sddl(domSID)))
579                 # First let's find the defaultSD for the object which SD is different from the reference one.
580                 res = sam_ldb.search(expression="dn=%s"%(dn),base=rootdn, scope=SCOPE_SUBTREE,attrs=["objectClass"],controls=["search_options:1:2"])
581                 classObj = res[0]["objectClass"][-1]
582                 defSD = ""
583                 if hashClassSD.has_key(classObj):
584                         defSD = hashClassSD[classObj]
585                 else:
586                         res2 = sam_ldb.search(expression="lDAPDisplayName=%s"%(classObj),base=rootdn, scope=SCOPE_SUBTREE,attrs=["defaultSecurityDescriptor"],controls=["search_options:1:2"])
587                         if len(res2) > 0:
588                                 defSD = str(res2[0]["defaultSecurityDescriptor"])
589                                 hashClassSD[classObj] = defSD
590                 # Because somewhere between alpha8 and alpha9 samba4 changed the owner of ACLs in the AD so 
591                 # we check if it's the case and if so use the "old" owner to see if the ACL is a direct calculation 
592                 # from the defaultSecurityDescriptor
593                 session = admin_session_info
594                 if oldSD.startswith("O:SYG:BA"):
595                         session = system_session_info
596                 descr = security.descriptor.ntsd_from_defaultsd(defSD, domSID,session)
597                 if descr.as_sddl(domSID) != oldSD:
598                         print "nTSecurity Descriptor for %s do not directly inherit from the defaultSecurityDescriptor and is different from the one of the reference provision, therefor I can't upgrade i"
599                         print "Old Descriptor: %s"%(oldSD)
600                         print "New Descriptor: %s"%(newSD)
601                         if diffDefSD.has_key(classObj):
602                                 # We have a pending modification for the defaultSecurityDescriptor of the class Object of the currently inspected object
603                                 # and we have a conflict so write down that we won't upgrade this defaultSD for this class object
604                                 diffDefSD[classObj]["noupgrade"]=1
605                 else:
606                         # At this point we know that the SD was directly generated from the defaultSecurityDescriptor
607                         # so we can take the new SD and replace the old one
608                         upgrade = upgrade +1
609                         delta = ldb.Message()
610                         delta.dn = ldb.Dn(sam_ldb,dn)
611                         delta["nTSecurityDescriptor"] = ldb.MessageElement( ndr_pack(diffSD[dn]["newSD"]),ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
612                 sam_ldb.modify(delta)
613                 
614         sam_ldb.transaction_commit()
615         print "%d nTSecurityDescriptor attribute(s) have been updated"%(upgrade)
616         sam_ldb.transaction_start()
617         upgrade = 0
618         for dn in diffDefSD:
619                 message(CHANGESD, "DefaultSecurityDescriptor for class object %s has changed"%(dn)) 
620                 if not diffDefSD[dn].has_key("noupgrade"):
621                         upgrade = upgrade +1
622                         delta = ldb.Message()
623                         delta.dn = ldb.Dn(sam_ldb,dn)
624                         delta["defaultSecurityDescriptor"] = ldb.MessageElement(diffDefSD[dn]["newSD"],ldb.FLAG_MOD_REPLACE,"defaultSecurityDescriptor" )
625                         sam_ldb.modify(delta)
626                 else:
627                         message(CHANGESD,"Not updating the defaultSecurityDescriptor for class object %s as one or more dependant object hasn't been upgraded"%(dn))
628
629         sam_ldb.transaction_commit()
630         print "%d defaultSecurityDescriptor attribute(s) have been updated"%(upgrade)
631                         
632 def rmall(topdir):
633         for root, dirs, files in os.walk(topdir, topdown=False):
634                 for name in files:
635                         os.remove(os.path.join(root, name))
636                 for name in dirs:
637                         os.rmdir(os.path.join(root, name))
638         os.rmdir(topdir)
639
640 # For each partition check the differences
641
642 def check_diff(newpaths,paths,creds,session,names):
643         print "Copy samdb"
644         shutil.copy(newpaths.samdb,paths.samdb)
645
646         print "Update ldb names if needed"
647         schemaldb=os.path.join(paths.private_dir,"schema.ldb")
648         configldb=os.path.join(paths.private_dir,"configuration.ldb")
649         usersldb=os.path.join(paths.private_dir,"users.ldb")
650         if os.path.isfile(schemaldb):
651                 shutil.copy(schemaldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.schemadn).upper()))
652                 os.remove(schemaldb)
653         if os.path.isfile(usersldb):
654                 shutil.copy(usersldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.rootdn).upper()))
655                 os.remove(usersldb)
656         if os.path.isfile(configldb):
657                 shutil.copy(configldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.configdn).upper()))
658                 os.remove(configldb)
659         shutil.copy(os.path.join(newpaths.private_dir,"privilege.ldb"),os.path.join(paths.private_dir,"privilege.ldb"))
660
661         print "Doing schema update"
662         hashdef = check_diff_name(newpaths,paths,creds,session,str(names.schemadn),names,1)
663         print "Done with schema update"
664         print "Scanning whole provision for updates and additions"
665         hashSD = check_diff_name(newpaths,paths,creds,session,str(names.rootdn),names,0)
666         print "Done with scanning"
667         print "Updating secrets"
668         update_secrets(newpaths,paths,creds,session)
669 #       update_sds(hashdef,hashSD,paths,creds,session,str(names.rootdn),names.domainsid)
670
671 # From here start the big steps of the program
672 # First get files paths
673 paths=get_paths(targetdir=opts.targetdir,smbconf=smbconf)
674 paths.setup = setup_dir
675 def setup_path(file):
676         return os.path.join(setup_dir, file)
677 # Guess all the needed names (variables in fact) from the current 
678 # provision.
679 names = guess_names_from_current_provision(creds,session,paths)
680 # Let's see them
681 print_names(names)
682 # With all this information let's create a fresh new provision used as reference
683 provisiondir = newprovision(names,setup_dir,creds,session,smbconf)
684 # Get file paths of this new provision
685 newpaths = get_paths(targetdir=provisiondir)
686 populate_backlink(newpaths,creds,session,names.schemadn)
687 # Check the difference
688 check_diff(newpaths,paths,creds,session,names)
689 # remove reference provision now that everything is done !
690 rmall(provisiondir)