cf8262aef9654afff1eb6ea8690483edbd285b79
[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 setup_dir = "/usr/local/src/samba4/source4/setup"
133 session = system_session()
134
135 # Create an array of backlinked attributes
136 def populate_backlink(newpaths,creds,session,schemadn):
137         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
138         backlinked.extend(get_linked_attributes(ldb.Dn(newsam_ldb,str(schemadn)),newsam_ldb).values())
139
140 # Get Paths for important objects (ldb, keytabs ...)
141 def get_paths(targetdir=None,smbconf=None):
142         if targetdir is not None:
143                 if (not os.path.exists(os.path.join(targetdir, "etc"))):
144                         os.makedirs(os.path.join(targetdir, "etc"))
145                 smbconf = os.path.join(targetdir, "etc", "smb.conf")
146         if smbconf is None:
147                         smbconf = param.default_path()
148
149         if not os.path.exists(smbconf):
150                 print >>sys.stderr, "Unable to find smb.conf .."
151                 parser.print_usage()
152                 sys.exit(1)
153
154         lp = param.LoadParm()
155         lp.load(smbconf)
156 # Normaly we need the domain name for this function but for our needs it's pointless 
157         paths = provision_paths_from_lp(lp,"foo")
158         return paths
159
160 # This function guess(fetch) informations needed to make a fresh provision from the current provision   
161 # It includes: realm, workgroup, partitions, netbiosname, domain guid, ...
162 def guess_names_from_current_provision(credentials,session_info,paths):
163         lp = param.LoadParm()
164         lp.load(paths.smbconf)
165         names = ProvisionNames()
166         # NT domain, kerberos realm, root dn, domain dn, domain dns name
167         names.domain = string.upper(lp.get("workgroup"))
168         names.realm = lp.get("realm")
169         rootdn = "DC=" + names.realm.replace(".",",DC=")
170         names.domaindn = rootdn
171         names.dnsdomain = names.realm
172         names.realm = string.upper(names.realm)
173         # netbiosname
174         secrets_ldb = Ldb(paths.secrets, session_info=session_info, credentials=credentials,lp=lp)
175         # Get the netbiosname first (could be obtained from smb.conf in theory)
176         attrs = ["sAMAccountName"]
177         res = secrets_ldb.search(expression="(flatname=%s)"%names.domain,base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=attrs)
178         names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
179
180         #partitions = get_partitions(credentials,session_info,paths,lp)
181         names.smbconf = smbconf
182         samdb = SamDB(paths.samdb, session_info=session_info,
183                                                                 credentials=credentials, lp=lp)
184         
185         # partitions (schema,config,root)
186         # That's a bit simplistic but it's ok as long as we have only 3 partitions 
187         attrs2 = ["schemaNamingContext","configurationNamingContext","rootDomainNamingContext"]
188         res2 = samdb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
189
190         names.configdn = res2[0]["configurationNamingContext"]
191         configdn = str(names.configdn)
192         names.schemadn = res2[0]["schemaNamingContext"]
193         if not (rootdn == str(res2[0]["rootDomainNamingContext"])):
194                 print >>sys.stderr, "rootdn in sam.ldb and smb.conf is not the same ..."
195         else:
196                 names.rootdn=res2[0]["rootDomainNamingContext"]
197         # default site name
198         attrs3 = ["cn"]
199         res3= samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=attrs3)
200         names.sitename = str(res3[0]["cn"])
201         
202         # dns hostname and server dn 
203         attrs4 = ["dNSHostName"]
204         res4= samdb.search(expression="(CN=%s)"%names.netbiosname,base="OU=Domain Controllers,"+rootdn, \
205                                                 scope=SCOPE_ONELEVEL, attrs=attrs4)
206         names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
207
208         names.serverdn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (names.netbiosname, names.sitename, configdn)
209         
210         # invocation id
211         attrs5 = ["invocationId"]
212         res5 = samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_SUBTREE, attrs=attrs5)
213         for i in range(0,len(res5)):
214                 if ( len(res5[i]) > 0):
215                         names.invocation = str(ndr_unpack( misc.GUID,res5[i]["invocationId"][0]))
216                         break
217         # domain guid/sid
218         attrs6 = ["objectGUID", "objectSid", ]
219         res6 = samdb.search(expression="(objectClass=*)",base=rootdn, scope=SCOPE_BASE, attrs=attrs6)
220         names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
221         names.domainsid = str(ndr_unpack( security.dom_sid,res6[0]["objectSid"][0]))
222
223         # policy guid
224         attrs7 = ["cn","displayName"]
225         res7 = samdb.search(expression="(displayName=Default Domain Policy)",base="CN=Policies,CN=System,"+rootdn, \
226                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
227         names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
228         # dc policy guid
229         attrs8 = ["cn","displayName"]
230         res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",base="CN=Policies,CN=System,"+rootdn, \
231                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
232         if len(res8) == 1:
233                 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
234         else:
235                 names.policyid_dc = None
236         # ntds guid
237         attrs9 = ["objectGUID" ]
238         exp = "(dn=CN=NTDS Settings,%s)"%(names.serverdn)
239         print exp
240         res9 = samdb.search(expression="(dn=CN=NTDS Settings,%s)"%(names.serverdn),base=str(names.configdn), scope=SCOPE_SUBTREE, attrs=attrs9)
241         names.ntdsguid = str(ndr_unpack( misc.GUID,res9[0]["objectGUID"][0]))
242
243
244         return names
245
246 # Debug a little bit
247 def print_names(names):
248         message(GUESS, "rootdn      :"+str(names.rootdn))
249         message(GUESS, "configdn    :"+str(names.configdn))
250         message(GUESS, "schemadn    :"+str(names.schemadn))
251         message(GUESS, "serverdn    :"+names.serverdn)
252         message(GUESS, "netbiosname :"+names.netbiosname)
253         message(GUESS, "defaultsite :"+names.sitename)
254         message(GUESS, "dnsdomain   :"+names.dnsdomain)
255         message(GUESS, "hostname    :"+names.hostname)
256         message(GUESS, "domain      :"+names.domain)
257         message(GUESS, "realm       :"+names.realm)
258         message(GUESS, "invocationid:"+names.invocation)
259         message(GUESS, "policyguid  :"+names.policyid)
260         message(GUESS, "policyguiddc:"+str(names.policyid_dc))
261         message(GUESS, "domainsid   :"+names.domainsid)
262         message(GUESS, "domainguid  :"+names.domainguid)
263         message(GUESS, "ntdsguid    :"+names.ntdsguid)
264
265 # Create a fresh new reference provision
266 # This provision will be the reference for knowing what has changed in the 
267 # since the latest upgrade in the current provision
268 def newprovision(names,setup_dir,creds,session,smbconf):
269         random.seed()
270         provdir=os.path.join(os.environ["HOME"],"provision"+str(int(100000*random.random())))
271         logstd=os.path.join(provdir,"log.std")
272         os.chdir(os.path.join(setup_dir,".."))
273         os.mkdir(provdir)
274
275         provision(setup_dir, messageprovision,
276                 session, creds, smbconf=smbconf, targetdir=provdir,
277                 samdb_fill=FILL_FULL, realm=names.realm, domain=names.domain,
278                 domainguid=names.domainguid, domainsid=names.domainsid,ntdsguid=names.ntdsguid,
279                 policyguid=names.policyid,policyguid_dc=names.policyid_dc,hostname=names.hostname,
280                 hostip=None, hostip6=None,
281                 invocationid=names.invocation, adminpass=None,
282                 krbtgtpass=None, machinepass=None,
283                 dnspass=None, root=None, nobody=None,
284                 wheel=None, users=None,
285                 serverrole="domain controller",
286                 ldap_backend_extra_port=None,
287                 backend_type=None,
288                 ldapadminpass=None,
289                 ol_mmr_urls=None,
290                 slapd_path=None,
291                 setup_ds_path=None,
292                 nosync=None,
293                 ldap_dryrun_mode=None)
294         print >>sys.stderr, "provisiondir: "+provdir
295         return provdir
296
297 # This function sorts two dn in the lexicographical order and put higher level DN before
298 # So given the dns cn=bar,cn=foo and cn=foo the later will be return as smaller (-1) as it has less 
299 # level
300 def dn_sort(x,y):
301         p = re.compile(r'(?<!\\),')
302         tab1 = p.split(str(x))
303         tab2 = p.split(str(y))
304         min = 0
305         if (len(tab1) > len(tab2)):
306                 min = len(tab2)
307         elif (len(tab1) < len(tab2)):
308                 min = len(tab1) 
309         else: 
310                 min = len(tab1)
311         len1=len(tab1)-1
312         len2=len(tab2)-1
313         space = " "
314         # Note: python range go up to upper limit but do not include it
315         for i in range(0,min):
316                 ret=cmp(tab1[len1-i],tab2[len2-i])
317                 if(ret != 0):
318                         return ret      
319                 else:
320                         if(i==min-1):
321                                 if(len1==len2):
322                                         print >>sys.stderr,"PB PB PB"+space.join(tab1)+" / "+space.join(tab2)
323                                 if(len1>len2):
324                                         return 1
325                                 else:
326                                         return -1
327         return ret
328
329 # check from security descriptors modifications return 1 if it is 0 otherwise
330 # it also populate hash structure for later use in the upgrade process
331 def handle_security_desc(ischema,att,msgElt,hashallSD,old,new):
332         if ischema == 1 and att == "defaultSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
333                 hashSD = {}
334                 hashSD["oldSD"] = old[0][att]
335                 hashSD["newSD"] = new[0][att]
336                 hashallSD[str(old[0].dn)] = hashSD
337                 return 1
338         if att == "nTSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
339                 if ischema == 0:
340                         hashSD = {}
341                         hashSD["oldSD"] =  ndr_unpack(security.descriptor,str(old[0][att]))
342                         hashSD["newSD"] =  ndr_unpack(security.descriptor,str(new[0][att]))
343                         hashallSD[str(old[0].dn)] = hashSD
344                 return 1
345         return 0
346
347 # Hangle special cases ... That's when we want to update an attribute only 
348 # if it has a certain value or if it's for a certain object or 
349 # a class of object. 
350 # It can be also if we want to do a merge of value instead of a simple replace 
351
352 def handle_special_case(att,delta,new,old,ischema):
353         flag = delta.get(att).flags()
354         if (att == "gPLink" or att == "gPCFileSysPath") and flag ==  ldb.FLAG_MOD_REPLACE and str(new[0].dn).lower() == str(old[0].dn).lower():
355                 delta.remove(att)
356                 return 1
357         if att == "forceLogoff":
358                 ref=0x8000000000000000 
359                 oldval=int(old[0][att][0])
360                 newval=int(new[0][att][0])
361                 ref == old and ref == abs(new)
362                 return 1
363         if (att == "adminDisplayName" or att == "adminDescription") and ischema:
364                 return 1
365         if (str(old[0].dn) == "CN=Samba4-Local-Domain,%s"%(str(names.schemadn)) and att == "defaultObjectCategory" and flag  == ldb.FLAG_MOD_REPLACE):
366                 return 1
367         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):
368                 return 1
369         if (str(old[0].dn) == "CN=Title,%s"%(str(names.schemadn)) and att == "rangeUpper" and flag  == ldb.FLAG_MOD_REPLACE):
370                 return 1
371         if ( (att == "member" or att == "servicePrincipalName") and flag  == ldb.FLAG_MOD_REPLACE):
372
373                 hash = {}
374                 newval = []
375                 changeDelta=0
376                 for elem in old[0][att]:
377                         hash[str(elem)]=1
378                         newval.append(str(elem))
379
380                 for elem in new[0][att]:
381                         if not hash.has_key(str(elem)):
382                                 changeDelta=1
383                                 newval.append(str(elem))
384                 if changeDelta == 1:
385                         delta[att] = ldb.MessageElement(newval, ldb.FLAG_MOD_REPLACE, att)
386                 else:
387                         delta.remove(att)
388                 return 1
389         if (str(old[0].dn) == "%s"%(str(names.rootdn)) and att == "subRefs" and flag  == ldb.FLAG_MOD_REPLACE):
390                 return 1
391         if str(delta.dn).endswith("CN=DisplaySpecifiers,%s"%names.configdn):
392                 return 1
393         return 0
394
395 def update_secrets(newpaths,paths,creds,session):
396         newsam_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
397         sam_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
398         res = newsam_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
399         res2 = sam_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
400         delta = sam_ldb.msg_diff(res2[0],res[0])
401         delta.dn = res2[0].dn
402         sam_ldb.modify(delta)   
403
404         newsam_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
405         sam_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
406         res = newsam_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
407         res2 = sam_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
408         hash_new = {}
409         hash = {}
410         listMissing = []
411         listPresent = []
412
413         empty = ldb.Message()
414         for i in range(0,len(res)):
415                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
416         
417         # Create a hash for speeding the search of existing object in the current provision
418         for i in range(0,len(res2)):
419                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
420
421         for k in hash_new.keys():
422                 if not hash.has_key(k):
423                         listMissing.append(hash_new[k])
424                 else:
425                         listPresent.append(hash_new[k])
426         for entry in listMissing:
427                 res = newsam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
428                 res2 = sam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
429                 delta = sam_ldb.msg_diff(empty,res[0])
430                 for att in hashAttrNotCopied.keys():
431                         delta.remove(att)
432                 message(CHANGE,"Entry %s is missing from secrets.ldb"%res[0].dn)
433                 for att in delta:
434                         message(CHANGE," Adding attribute %s"%att)
435                 delta.dn = res[0].dn
436                 sam_ldb.add(delta)      
437
438         for entry in listPresent:
439                 res = newsam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
440                 res2 = sam_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
441                 delta = sam_ldb.msg_diff(res2[0],res[0])
442                 i=0
443                 for att in hashAttrNotCopied.keys():
444                         delta.remove(att)
445                 for att in delta:
446                         i = i + 1
447                         if att != "dn":
448                                 message(CHANGE," Adding/Changing attribute %s to %s"%(att,res2[0].dn))
449                                 
450                 delta.dn = res2[0].dn
451                 sam_ldb.modify(delta)   
452 # Check difference between the current provision and the reference provision.
453 # It looks for all object which base DN is name if ischema is false then scan is done in 
454 # cross partition mode.
455 # If ischema is true, then special handling is done for dealing with schema
456 def check_diff_name(newpaths,paths,creds,session,basedn,names,ischema):
457         hash_new = {}
458         hash = {}
459         hashallSD = {}
460         listMissing = []
461         listPresent = []
462         res = []
463         res2 = []
464         # Connect to the reference provision and get all the attribute in the partition referred by name
465         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
466         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
467         if ischema:
468                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
469                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
470         else:
471                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
472                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
473                 
474         # Create a hash for speeding the search of new object
475         for i in range(0,len(res)):
476                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
477         
478         # Create a hash for speeding the search of existing object in the current provision
479         for i in range(0,len(res2)):
480                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
481
482         for k in hash_new.keys():
483                 if not hash.has_key(k):
484                         listMissing.append(hash_new[k])
485                 else:
486                         listPresent.append(hash_new[k])
487
488         # Sort the missing object in order to have object of the lowest level first (which can be 
489         # containers for higher level objects)
490         listMissing.sort(dn_sort)
491         listPresent.sort(dn_sort)
492
493         if ischema:
494                 # The following lines (up to the for loop) is to load the up to date schema into our current LDB 
495                 # a complete schema is needed as the insertion of attributes and class is done against it 
496                 # and the schema is self validated
497                 # The double ldb open and schema validation is taken from the initial provision script
498                 # it's not certain that it is really needed ....
499                 sam_ldb = Ldb(session_info=session, credentials=creds, lp=lp)
500                 schema = Schema(setup_path, security.dom_sid(names.domainsid), schemadn=basedn, serverdn=names.serverdn)
501                 # Load the schema from the one we computed earlier
502                 sam_ldb.set_schema_from_ldb(schema.ldb)
503                 # And now we can connect to the DB - the schema won't be loaded from the DB
504                 sam_ldb.connect(paths.samdb)
505                 sam_ldb.transaction_start()
506         else:   
507                 sam_ldb.transaction_start()
508
509         empty = ldb.Message()
510         print "There are %d missing objects"%(len(listMissing))
511         for dn in listMissing:
512                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
513                 #print >>sys.stderr, "@@@"+str(dn)
514                 delta = sam_ldb.msg_diff(empty,res[0])
515                 for att in hashAttrNotCopied.keys():
516                         delta.remove(att)
517                 for att in backlinked:
518                         delta.remove(att)
519                 delta.dn = dn
520
521                 sam_ldb.add(delta,["relax:0"])
522
523         changed = 0
524         for dn in listPresent:
525                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
526                 res2 = sam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
527                 delta = sam_ldb.msg_diff(res2[0],res[0])
528                 for att in hashAttrNotCopied.keys():
529                         delta.remove(att)
530                 for att in backlinked:
531                         delta.remove(att)
532                 delta.remove("parentGUID")
533                 nb = 0
534                 for att in delta:
535                         msgElt = delta.get(att)
536                         if att == "dn":
537                                 continue
538                         if handle_security_desc(ischema,att,msgElt,hashallSD,res2,res):
539                                 delta.remove(att)
540                                 continue
541                         if (not hashOverwrittenAtt.has_key(att) or not (hashOverwrittenAtt.get(att)&2^msgElt.flags())):
542                                 if  handle_special_case(att,delta,res,res2,ischema)==0 and msgElt.flags()!=ldb.FLAG_MOD_ADD:
543                                         i = 0
544                                         if opts.debugchange:
545                                                 message(CHANGE, "dn= "+str(dn)+ " "+att + " with flag "+str(msgElt.flags())+ " is not allowed to be changed/removed, I discard this change ...")
546                                                 for e in range(0,len(res2[0][att])):
547                                                         message(CHANGE,"old %d : %s"%(i,str(res2[0][att][e])))
548                                                 if msgElt.flags() == 2:
549                                                         i = 0
550                                                         for e in range(0,len(res[0][att])):
551                                                                 message(CHANGE,"new %d : %s"%(i,str(res[0][att][e])))
552                                         delta.remove(att)
553                 delta.dn = dn
554                 if len(delta.items()) >1:
555                         attributes=",".join(delta.keys())
556                         message(CHANGE,"%s is different from the reference one, changed attributes: %s"%(dn,attributes))
557                         changed = changed + 1
558                         sam_ldb.modify(delta)
559
560         sam_ldb.transaction_commit()
561         print "There are %d changed objects"%(changed)
562         return hashallSD
563
564
565 # This function updates SD for AD objects.
566 # As SD in the upgraded provision can be different for various reasons 
567 # this function check if an automatic update can be performed and do it 
568 # or if it can't be done.
569 def update_sds(diffDefSD,diffSD,paths,creds,session,rootdn,domSIDTxt):
570         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
571         sam_ldb.transaction_start()
572         domSID = security.dom_sid(domSIDTxt)
573         hashClassSD = {}
574         admin_session_info = admin_session(lp, str(domSID))
575         system_session_info = system_session()
576         upgrade = 0
577         for dn in diffSD.keys():
578                 newSD = diffSD[dn]["newSD"].as_sddl(domSID)
579                 oldSD = diffSD[dn]["oldSD"].as_sddl(domSID)
580                 message(CHANGESD, "ntsecuritydescriptor for %s has changed old %s new %s"%(dn,oldSD,diffSD[dn]["newSD"].as_sddl(domSID)))
581                 # First let's find the defaultSD for the object which SD is different from the reference one.
582                 res = sam_ldb.search(expression="dn=%s"%(dn),base=rootdn, scope=SCOPE_SUBTREE,attrs=["objectClass"],controls=["search_options:1:2"])
583                 classObj = res[0]["objectClass"][-1]
584                 defSD = ""
585                 if hashClassSD.has_key(classObj):
586                         defSD = hashClassSD[classObj]
587                 else:
588                         res2 = sam_ldb.search(expression="lDAPDisplayName=%s"%(classObj),base=rootdn, scope=SCOPE_SUBTREE,attrs=["defaultSecurityDescriptor"],controls=["search_options:1:2"])
589                         if len(res2) > 0:
590                                 defSD = str(res2[0]["defaultSecurityDescriptor"])
591                                 hashClassSD[classObj] = defSD
592                 # Because somewhere between alpha8 and alpha9 samba4 changed the owner of ACLs in the AD so 
593                 # we check if it's the case and if so use the "old" owner to see if the ACL is a direct calculation 
594                 # from the defaultSecurityDescriptor
595                 session = admin_session_info
596                 if oldSD.startswith("O:SYG:BA"):
597                         session = system_session_info
598                 descr = security.descriptor.ntsd_from_defaultsd(defSD, domSID,session)
599                 if descr.as_sddl(domSID) != oldSD:
600                         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"
601                         print "Old Descriptor: %s"%(oldSD)
602                         print "New Descriptor: %s"%(newSD)
603                         if diffDefSD.has_key(classObj):
604                                 # We have a pending modification for the defaultSecurityDescriptor of the class Object of the currently inspected object
605                                 # and we have a conflict so write down that we won't upgrade this defaultSD for this class object
606                                 diffDefSD[classObj]["noupgrade"]=1
607                 else:
608                         # At this point we know that the SD was directly generated from the defaultSecurityDescriptor
609                         # so we can take the new SD and replace the old one
610                         upgrade = upgrade +1
611                         delta = ldb.Message()
612                         delta.dn = ldb.Dn(sam_ldb,dn)
613                         delta["nTSecurityDescriptor"] = ldb.MessageElement( ndr_pack(diffSD[dn]["newSD"]),ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
614                 sam_ldb.modify(delta)
615                 
616         sam_ldb.transaction_commit()
617         print "%d nTSecurityDescriptor attribute(s) have been updated"%(upgrade)
618         sam_ldb.transaction_start()
619         upgrade = 0
620         for dn in diffDefSD:
621                 message(CHANGESD, "DefaultSecurityDescriptor for class object %s has changed"%(dn)) 
622                 if not diffDefSD[dn].has_key("noupgrade"):
623                         upgrade = upgrade +1
624                         delta = ldb.Message()
625                         delta.dn = ldb.Dn(sam_ldb,dn)
626                         delta["defaultSecurityDescriptor"] = ldb.MessageElement(diffDefSD[dn]["newSD"],ldb.FLAG_MOD_REPLACE,"defaultSecurityDescriptor" )
627                         sam_ldb.modify(delta)
628                 else:
629                         message(CHANGESD,"Not updating the defaultSecurityDescriptor for class object %s as one or more dependant object hasn't been upgraded"%(dn))
630
631         sam_ldb.transaction_commit()
632         print "%d defaultSecurityDescriptor attribute(s) have been updated"%(upgrade)
633                         
634 def rmall(topdir):
635         for root, dirs, files in os.walk(topdir, topdown=False):
636                 for name in files:
637                         os.remove(os.path.join(root, name))
638                 for name in dirs:
639                         os.rmdir(os.path.join(root, name))
640         os.rmdir(topdir)
641
642 # For each partition check the differences
643
644 def check_diff(newpaths,paths,creds,session,names):
645         #for name in [str(names.schemadn), str(names.configdn), str(names.rootdn)] :
646         #for name in [str(names.configdn)] :
647         print "Copy samdb"
648         shutil.copy(newpaths.samdb,paths.samdb)
649
650         print "Update ldb names if needed"
651         schemaldb=os.path.join(paths.private_dir,"schema.ldb")
652         configldb=os.path.join(paths.private_dir,"configuration.ldb")
653         usersldb=os.path.join(paths.private_dir,"users.ldb")
654         if os.path.isfile(schemaldb):
655                 shutil.copy(schemaldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.schemadn).upper()))
656                 os.remove(schemaldb)
657         if os.path.isfile(usersldb):
658                 shutil.copy(usersldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.rootdn).upper()))
659                 os.remove(usersldb)
660         if os.path.isfile(configldb):
661                 shutil.copy(configldb,os.path.join(paths.private_dir,"%s.ldb"%str(names.configdn).upper()))
662                 os.remove(configldb)
663         shutil.copy(os.path.join(newpaths.private_dir,"privilege.ldb"),os.path.join(paths.private_dir,"privilege.ldb"))
664
665         print "Doing schema update"
666         hashdef = check_diff_name(newpaths,paths,creds,session,str(names.schemadn),names,1)
667         print "Done with schema update"
668         print "Scanning whole provision for updates and additions"
669         hashSD = check_diff_name(newpaths,paths,creds,session,str(names.rootdn),names,0)
670         print "Done with scanning"
671         print "Updating secrets"
672         update_secrets(newpaths,paths,creds,session)
673 #       update_sds(hashdef,hashSD,paths,creds,session,str(names.rootdn),names.domainsid)
674
675 # From here start the big steps of the program
676 # First get files paths
677 paths=get_paths(targetdir=opts.targetdir,smbconf=smbconf)
678 paths.setup = setup_dir
679 def setup_path(file):
680         return os.path.join(setup_dir, file)
681 # Guess all the needed names (variables in fact) from the current 
682 # provision.
683 names = guess_names_from_current_provision(creds,session,paths)
684 # Let's see them
685 print_names(names)
686 # With all this information let's create a fresh new provision used as reference
687 provisiondir = newprovision(names,setup_dir,creds,session,smbconf)
688 #provisiondir = "/home/mat/provision12962"
689 # Get file paths of this new provision
690 newpaths = get_paths(targetdir=provisiondir)
691 populate_backlink(newpaths,creds,session,names.schemadn)
692 # Check the difference
693 check_diff(newpaths,paths,creds,session,names)
694 # remove reference provision now that everything is done !
695 rmall(provisiondir)