s4: Handle the case in secrets.ldb without name attribute
[kamenim/samba.git] / source4 / scripting / bin / upgradeprovision
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 import tempfile
34 # Find right directory when running from source tree
35 sys.path.insert(0, "bin/python")
36
37 from base64 import b64encode
38
39 import samba
40 from samba.credentials import DONT_USE_KERBEROS
41 from samba.auth import system_session, admin_session
42 from samba import Ldb, DS_DOMAIN_FUNCTION_2000, DS_DOMAIN_FUNCTION_2003, DS_DOMAIN_FUNCTION_2008, DS_DC_FUNCTION_2008_R2
43 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError
44 import ldb
45 import samba.getopt as options
46 from samba.samdb import SamDB
47 from samba import param
48 from samba import glue
49 from samba.provision import  ProvisionNames,provision_paths_from_lp,find_setup_dir,FILL_FULL,provision, get_domain_descriptor, get_config_descriptor, secretsdb_self_join
50 from samba.provisionexceptions import ProvisioningError
51 from samba.schema import get_dnsyntax_attributes, get_linked_attributes, Schema, get_schema_descriptor
52 from samba.dcerpc import misc, security
53 from samba.ndr import ndr_pack, ndr_unpack
54 from samba.dcerpc.misc import SEC_CHAN_BDC
55
56 replace=2^ldb.FLAG_MOD_REPLACE
57 add=2^ldb.FLAG_MOD_ADD
58 delete=2^ldb.FLAG_MOD_DELETE
59
60 #Errors are always logged
61 ERROR =         -1
62 SIMPLE =        0x00
63 CHANGE =        0x01
64 CHANGESD =      0x02
65 GUESS =         0x04
66 PROVISION =     0x08
67 CHANGEALL =     0xff
68
69 # Attributes that not copied from the reference provision even if they do not exists in the destination object
70 # This is most probably because they are populated automatcally when object is created
71 hashAttrNotCopied = {   "dn": 1,"whenCreated": 1,"whenChanged": 1,"objectGUID": 1,"replPropertyMetaData": 1,"uSNChanged": 1,\
72                                                 "uSNCreated": 1,"parentGUID": 1,"objectCategory": 1,"distinguishedName": 1,\
73                                                 "showInAdvancedViewOnly": 1,"instanceType": 1, "cn": 1, "msDS-Behavior-Version":1, "nextRid":1,\
74                                                 "nTMixedDomain": 1,"versionNumber":1, "lmPwdHistory":1, "pwdLastSet": 1, "ntPwdHistory":1, "unicodePwd":1,\
75                                                 "dBCSPwd":1,"supplementalCredentials":1,"gPCUserExtensionNames":1, "gPCMachineExtensionNames":1,\
76                                                 "maxPwdAge":1, "mail":1, "secret":1,"possibleInferiors":1, "sAMAccountType":1}
77
78 # Usually for an object that already exists we do not overwrite attributes as they might have been changed for good
79 # reasons. Anyway for a few of thems it's mandatory to replace them otherwise the provision will be broken somehow.
80 hashOverwrittenAtt = {   "prefixMap": replace, "systemMayContain": replace,"systemOnly":replace, "searchFlags":replace,\
81                                                  "mayContain":replace,  "systemFlags":replace,
82                                                  "oEMInformation":replace, "operatingSystemVersion":replace, "adminPropertyPages":replace,
83                                                  "defaultSecurityDescriptor": replace}
84 backlinked = []
85
86 def define_what_to_log(opts):
87         what = 0
88         if opts.debugchange:
89                 what = what | CHANGE
90         if opts.debugchangesd:
91                 what = what | CHANGESD
92         if opts.debugguess:
93                 what = what | GUESS
94         if opts.debugprovision:
95                 what = what | PROVISION
96         if opts.debugall:
97                 what = what | CHANGEALL
98         return what
99
100
101 parser = optparse.OptionParser("provision [options]")
102 sambaopts = options.SambaOptions(parser)
103 parser.add_option_group(sambaopts)
104 parser.add_option_group(options.VersionOptions(parser))
105 credopts = options.CredentialsOptions(parser)
106 parser.add_option_group(credopts)
107 parser.add_option("--setupdir", type="string", metavar="DIR",
108                                         help="directory with setup files")
109 parser.add_option("--debugprovision", help="Debug provision", action="store_true")
110 parser.add_option("--debugguess", help="Print information on what is different but won't be changed", action="store_true")
111 parser.add_option("--debugchange", help="Print information on what is different but won't be changed", action="store_true")
112 parser.add_option("--debugchangesd", help="Print information security descriptors differences", action="store_true")
113 parser.add_option("--debugall", help="Print all available information (very verbose)", action="store_true")
114 parser.add_option("--full", help="Perform full upgrade of the samdb (schema, configuration, new objects, ...", action="store_true")
115 parser.add_option("--targetdir", type="string", metavar="DIR",
116                                         help="Set target directory")
117
118 opts = parser.parse_args()[0]
119
120 whatToLog = define_what_to_log(opts)
121
122 def messageprovision(text):
123         """print a message if quiet is not set."""
124         if opts.debugprovision or opts.debugall:
125                 print text
126
127 def message(what,text):
128         """print a message if quiet is not set."""
129         if (whatToLog & what) or (what <= 0 ):
130                 print text
131
132 if len(sys.argv) == 1:
133         opts.interactive = True
134 lp = sambaopts.get_loadparm()
135 smbconf = lp.configfile
136
137 creds = credopts.get_credentials(lp)
138 creds.set_kerberos_state(DONT_USE_KERBEROS)
139 setup_dir = opts.setupdir
140 if setup_dir is None:
141     setup_dir = find_setup_dir()
142
143 session = system_session()
144
145 # Create an array of backlinked attributes
146 def populate_backlink(newpaths,creds,session,schemadn):
147         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
148         backlinked.extend(get_linked_attributes(ldb.Dn(newsam_ldb,str(schemadn)),newsam_ldb).values())
149
150 # Get Paths for important objects (ldb, keytabs ...)
151 def get_paths(targetdir=None,smbconf=None):
152         if targetdir is not None:
153                 if (not os.path.exists(os.path.join(targetdir, "etc"))):
154                         os.makedirs(os.path.join(targetdir, "etc"))
155                 smbconf = os.path.join(targetdir, "etc", "smb.conf")
156         if smbconf is None:
157                         smbconf = param.default_path()
158
159         if not os.path.exists(smbconf):
160                 message(ERROR,"Unable to find smb.conf ..")
161                 parser.print_usage()
162                 sys.exit(1)
163
164         lp = param.LoadParm()
165         lp.load(smbconf)
166 # Normaly we need the domain name for this function but for our needs it's pointless
167         paths = provision_paths_from_lp(lp,"foo")
168         return paths
169
170 # This function guess(fetch) informations needed to make a fresh provision from the current provision
171 # It includes: realm, workgroup, partitions, netbiosname, domain guid, ...
172 def guess_names_from_current_provision(credentials,session_info,paths):
173         lp = param.LoadParm()
174         lp.load(paths.smbconf)
175         names = ProvisionNames()
176         # NT domain, kerberos realm, root dn, domain dn, domain dns name
177         names.domain = string.upper(lp.get("workgroup"))
178         names.realm = lp.get("realm")
179         basedn = "DC=" + names.realm.replace(".",",DC=")
180         names.dnsdomain = names.realm
181         names.realm = string.upper(names.realm)
182         # netbiosname
183         secrets_ldb = Ldb(paths.secrets, session_info=session_info, credentials=credentials,lp=lp, options=["modules:samba_secrets"])
184         # Get the netbiosname first (could be obtained from smb.conf in theory)
185         attrs = ["sAMAccountName"]
186         res = secrets_ldb.search(expression="(flatname=%s)"%names.domain,base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=attrs)
187         names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
188
189         names.smbconf = smbconf
190         #It's important here to let ldb load with the old module or it's quite certain that the LDB won't load ...
191         samdb = Ldb(paths.samdb, session_info=session_info,
192                     credentials=credentials, lp=lp, options=["modules:samba_dsdb"])
193
194         # That's a bit simplistic but it's ok as long as we have only 3 partitions
195         attrs2 = ["defaultNamingContext", "schemaNamingContext","configurationNamingContext","rootDomainNamingContext"]
196         res2 = samdb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
197
198         names.configdn = res2[0]["configurationNamingContext"]
199         configdn = str(names.configdn)
200         names.schemadn = res2[0]["schemaNamingContext"]
201         if not (ldb.Dn(samdb, basedn) == (ldb.Dn(samdb, res2[0]["defaultNamingContext"][0]))):
202                 raise ProvisioningError(("basedn in %s (%s) and from %s (%s) is not the same ..." % (paths.samdb, str(res2[0]["defaultNamingContext"][0]), paths.smbconf, basedn)))
203
204         names.domaindn=res2[0]["defaultNamingContext"]
205         names.rootdn=res2[0]["rootDomainNamingContext"]
206         # default site name
207         attrs3 = ["cn"]
208         res3= samdb.search(expression="(objectClass=*)",base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=attrs3)
209         names.sitename = str(res3[0]["cn"])
210
211         # dns hostname and server dn
212         attrs4 = ["dNSHostName"]
213         res4= samdb.search(expression="(CN=%s)"%names.netbiosname,base="OU=Domain Controllers,"+basedn, \
214                                                 scope=SCOPE_ONELEVEL, attrs=attrs4)
215         names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
216
217         server_res = samdb.search(expression="serverReference=%s"%res4[0].dn, attrs=[], base=configdn)
218         names.serverdn = server_res[0].dn
219
220         # invocation id/objectguid
221         res5 = samdb.search(expression="(objectClass=*)",base="CN=NTDS Settings,%s" % str(names.serverdn), scope=SCOPE_BASE, attrs=["invocationID","objectGUID"])
222         names.invocation = str(ndr_unpack( misc.GUID,res5[0]["invocationId"][0]))
223         names.ntdsguid = str(ndr_unpack( misc.GUID,res5[0]["objectGUID"][0]))
224
225         # domain guid/sid
226         attrs6 = ["objectGUID", "objectSid","msDS-Behavior-Version" ]
227         res6 = samdb.search(expression="(objectClass=*)",base=basedn, scope=SCOPE_BASE, attrs=attrs6)
228         names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
229         names.domainsid = ndr_unpack( security.dom_sid,res6[0]["objectSid"][0])
230         if res6[0].get("msDS-Behavior-Version") == None or int(res6[0]["msDS-Behavior-Version"][0]) < DS_DOMAIN_FUNCTION_2000:
231                 names.domainlevel = DS_DOMAIN_FUNCTION_2000
232         else:
233                 names.domainlevel = int(res6[0]["msDS-Behavior-Version"][0])
234
235         # policy guid
236         attrs7 = ["cn","displayName"]
237         res7 = samdb.search(expression="(displayName=Default Domain Policy)",base="CN=Policies,CN=System,"+basedn, \
238                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
239         names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
240         # dc policy guid
241         attrs8 = ["cn","displayName"]
242         res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",base="CN=Policies,CN=System,"+basedn, \
243                                                         scope=SCOPE_ONELEVEL, attrs=attrs7)
244         if len(res8) == 1:
245                 names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
246         else:
247                 names.policyid_dc = None
248
249
250         return names
251
252 # Debug a little bit
253 def print_names(names):
254         message(GUESS, "rootdn      :"+str(names.rootdn))
255         message(GUESS, "configdn    :"+str(names.configdn))
256         message(GUESS, "schemadn    :"+str(names.schemadn))
257         message(GUESS, "serverdn    :"+str(names.serverdn))
258         message(GUESS, "netbiosname :"+names.netbiosname)
259         message(GUESS, "defaultsite :"+names.sitename)
260         message(GUESS, "dnsdomain   :"+names.dnsdomain)
261         message(GUESS, "hostname    :"+names.hostname)
262         message(GUESS, "domain      :"+names.domain)
263         message(GUESS, "realm       :"+names.realm)
264         message(GUESS, "invocationid:"+names.invocation)
265         message(GUESS, "policyguid  :"+names.policyid)
266         message(GUESS, "policyguiddc:"+str(names.policyid_dc))
267         message(GUESS, "domainsid   :"+str(names.domainsid))
268         message(GUESS, "domainguid  :"+names.domainguid)
269         message(GUESS, "ntdsguid    :"+names.ntdsguid)
270         message(GUESS, "domainlevel :"+str(names.domainlevel))
271
272 # Create a fresh new reference provision
273 # This provision will be the reference for knowing what has changed in the
274 # since the latest upgrade in the current provision
275 def newprovision(names,setup_dir,creds,session,smbconf):
276         message(SIMPLE, "Creating a reference provision")
277         provdir=tempfile.mkdtemp(dir=paths.private_dir, prefix="referenceprovision")
278         if os.path.isdir(provdir):
279                 rmall(provdir)
280         logstd=os.path.join(provdir,"log.std")
281         os.chdir(os.path.join(setup_dir,".."))
282         os.mkdir(provdir)
283         os.close(2)
284         sys.stderr = open("%s/provision.log"%provdir, "w")
285         message(PROVISION, "Reference provision stored in %s"%provdir)
286         message(PROVISION, "STDERR message of provision will be logged in %s/provision.log"%provdir)
287         sys.stderr = open("/dev/stdout", "w")
288         provision(setup_dir, messageprovision,
289                 session, creds, smbconf=smbconf, targetdir=provdir,
290                 samdb_fill=FILL_FULL, realm=names.realm, domain=names.domain,
291                 domainguid=names.domainguid, domainsid=str(names.domainsid),ntdsguid=names.ntdsguid,
292                 policyguid=names.policyid,policyguid_dc=names.policyid_dc,hostname=names.netbiosname,
293                 hostip=None, hostip6=None,
294                 invocationid=names.invocation, adminpass=None,
295                 krbtgtpass=None, machinepass=None,
296                 dnspass=None, root=None, nobody=None,
297                 wheel=None, users=None,
298                 serverrole="domain controller",
299                 ldap_backend_extra_port=None,
300                 backend_type=None,
301                 ldapadminpass=None,
302                 ol_mmr_urls=None,
303                 slapd_path=None,
304                 setup_ds_path=None,
305                 nosync=None,
306                 dom_for_fun_level=names.domainlevel,
307                 ldap_dryrun_mode=None)
308         return provdir
309
310 # This function sorts two dn in the lexicographical order and put higher level DN before
311 # So given the dns cn=bar,cn=foo and cn=foo the later will be return as smaller (-1) as it has less
312 # level
313 def dn_sort(x,y):
314         p = re.compile(r'(?<!\\),')
315         tab1 = p.split(str(x))
316         tab2 = p.split(str(y))
317         min = 0
318         if (len(tab1) > len(tab2)):
319                 min = len(tab2)
320         elif (len(tab1) < len(tab2)):
321                 min = len(tab1)
322         else:
323                 min = len(tab1)
324         len1=len(tab1)-1
325         len2=len(tab2)-1
326         space = " "
327         # Note: python range go up to upper limit but do not include it
328         for i in range(0,min):
329                 ret=cmp(tab1[len1-i],tab2[len2-i])
330                 if(ret != 0):
331                         return ret
332                 else:
333                         if(i==min-1):
334                                 if(len1==len2):
335                                         message(ERROR,"PB PB PB"+space.join(tab1)+" / "+space.join(tab2))
336                                 if(len1>len2):
337                                         return 1
338                                 else:
339                                         return -1
340         return ret
341
342 # check from security descriptors modifications return 1 if it is 0 otherwise
343 # it also populate hash structure for later use in the upgrade process
344 def handle_security_desc(ischema,att,msgElt,hashallSD,old,new):
345         if ischema == 1 and att == "defaultSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
346                 hashSD = {}
347                 hashSD["oldSD"] = old[0][att]
348                 hashSD["newSD"] = new[0][att]
349                 hashallSD[str(old[0].dn)] = hashSD
350                 return 0
351         if att == "nTSecurityDescriptor"  and msgElt.flags() == ldb.FLAG_MOD_REPLACE:
352                 if ischema == 0:
353                         hashSD = {}
354                         hashSD["oldSD"] =  ndr_unpack(security.descriptor,str(old[0][att]))
355                         hashSD["newSD"] =  ndr_unpack(security.descriptor,str(new[0][att]))
356                         hashallSD[str(old[0].dn)] = hashSD
357                 return 1
358         return 0
359
360 # Hangle special cases ... That's when we want to update an attribute only
361 # if it has a certain value or if it's for a certain object or
362 # a class of object.
363 # It can be also if we want to do a merge of value instead of a simple replace
364 def handle_special_case(att,delta,new,old,ischema):
365         flag = delta.get(att).flags()
366         if (att == "gPLink" or att == "gPCFileSysPath") and flag ==  ldb.FLAG_MOD_REPLACE and str(new[0].dn).lower() == str(old[0].dn).lower():
367                 delta.remove(att)
368                 return 1
369         if att == "forceLogoff":
370                 ref=0x8000000000000000
371                 oldval=int(old[0][att][0])
372                 newval=int(new[0][att][0])
373                 ref == old and ref == abs(new)
374                 return 1
375         if (att == "adminDisplayName" or att == "adminDescription") and ischema:
376                 return 1
377         if (str(old[0].dn) == "CN=Samba4-Local-Domain,%s"%(str(names.schemadn)) and att == "defaultObjectCategory" and flag  == ldb.FLAG_MOD_REPLACE):
378                 return 1
379         if (str(old[0].dn) == "CN=S-1-5-11,CN=ForeignSecurityPrincipals,%s"%(str(names.rootdn)) and att == "description" and flag  == ldb.FLAG_MOD_DELETE):
380                 return 1
381         if (str(old[0].dn) == "CN=Title,%s"%(str(names.schemadn)) and att == "rangeUpper" and flag  == ldb.FLAG_MOD_REPLACE):
382                 return 1
383         if ( (att == "member" or att == "servicePrincipalName") and flag  == ldb.FLAG_MOD_REPLACE):
384
385                 hash = {}
386                 newval = []
387                 changeDelta=0
388                 for elem in old[0][att]:
389                         hash[str(elem)]=1
390                         newval.append(str(elem))
391
392                 for elem in new[0][att]:
393                         if not hash.has_key(str(elem)):
394                                 changeDelta=1
395                                 newval.append(str(elem))
396                 if changeDelta == 1:
397                         delta[att] = ldb.MessageElement(newval, ldb.FLAG_MOD_REPLACE, att)
398                 else:
399                         delta.remove(att)
400                 return 1
401         if (str(old[0].dn) == "%s"%(str(names.rootdn)) and att == "subRefs" and flag  == ldb.FLAG_MOD_REPLACE):
402                 return 1
403         if str(delta.dn).endswith("CN=DisplaySpecifiers,%s"%names.configdn):
404                 return 1
405         return 0
406
407 def update_secrets(newpaths,paths,creds,session):
408         message(SIMPLE,"update secrets.ldb")
409         newsecrets_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
410         secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp, options=["modules:samba_secrets"])
411         res = newsecrets_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
412         res2 = secrets_ldb.search(expression="dn=@MODULES",base="", scope=SCOPE_SUBTREE)
413         delta = secrets_ldb.msg_diff(res2[0],res[0])
414         delta.dn = res2[0].dn
415         secrets_ldb.modify(delta)
416
417         newsecrets_ldb = Ldb(newpaths.secrets, session_info=session, credentials=creds,lp=lp)
418         secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
419         res = newsecrets_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
420         res2 = secrets_ldb.search(expression="objectClass=top",base="", scope=SCOPE_SUBTREE,attrs=["dn"])
421         hash_new = {}
422         hash = {}
423         listMissing = []
424         listPresent = []
425
426         empty = ldb.Message()
427         for i in range(0,len(res)):
428                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
429
430         # Create a hash for speeding the search of existing object in the current provision
431         for i in range(0,len(res2)):
432                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
433
434         for k in hash_new.keys():
435                 if not hash.has_key(k):
436                         listMissing.append(hash_new[k])
437                 else:
438                         listPresent.append(hash_new[k])
439         for entry in listMissing:
440                 res = newsecrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
441                 res2 = secrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
442                 delta = secrets_ldb.msg_diff(empty,res[0])
443                 for att in hashAttrNotCopied.keys():
444                         delta.remove(att)
445                 message(CHANGE,"Entry %s is missing from secrets.ldb"%res[0].dn)
446                 for att in delta:
447                         message(CHANGE," Adding attribute %s"%att)
448                 delta.dn = res[0].dn
449                 secrets_ldb.add(delta)
450
451         for entry in listPresent:
452                 res = newsecrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
453                 res2 = secrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
454                 delta = secrets_ldb.msg_diff(res2[0],res[0])
455                 i=0
456                 for att in hashAttrNotCopied.keys():
457                         delta.remove(att)
458                 for att in delta:
459                         i = i + 1
460
461                         if att == "name":
462                                 message(CHANGE,"Found attribute name on  %s, must rename the DN "%(res2[0].dn))
463                                 secrets_ldb.rename(res2[0].dn,ldb.Dn(secrets_ldb,"%sfoo"%str(res2[0].dn)))
464                                 secrets_ldb.rename(ldb.Dn(secrets_ldb,"%sfoo"%str(res2[0].dn)),res2[0].dn)
465                         else:
466                                 delta.remove(att)
467
468
469         for entry in listPresent:
470                 res = newsecrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
471                 res2 = secrets_ldb.search(expression="dn=%s"%entry,base="", scope=SCOPE_SUBTREE)
472                 delta = secrets_ldb.msg_diff(res2[0],res[0])
473                 i=0
474                 for att in hashAttrNotCopied.keys():
475                         delta.remove(att)
476                 for att in delta:
477                         i = i + 1
478                         if att != "dn":
479                                 message(CHANGE," Adding/Changing attribute %s to %s"%(att,res2[0].dn))
480
481                 delta.dn = res2[0].dn
482                 secrets_ldb.modify(delta)
483
484
485 # Check difference between the current provision and the reference provision.
486 # It looks for all object which base DN is name if ischema is false then scan is done in
487 # cross partition mode.
488 # If ischema is true, then special handling is done for dealing with schema
489 def check_diff_name(newpaths,paths,creds,session,basedn,names,ischema):
490         hash_new = {}
491         hash = {}
492         hashallSD = {}
493         listMissing = []
494         listPresent = []
495         res = []
496         res2 = []
497         # Connect to the reference provision and get all the attribute in the partition referred by name
498         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
499         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp, options=["modules:samba_dsdb"])
500         if ischema:
501                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
502                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"])
503         else:
504                 res = newsam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
505                 res2 = sam_ldb.search(expression="objectClass=*",base=basedn, scope=SCOPE_SUBTREE,attrs=["dn"],controls=["search_options:1:2"])
506
507         # Create a hash for speeding the search of new object
508         for i in range(0,len(res)):
509                 hash_new[str(res[i]["dn"]).lower()] = res[i]["dn"]
510
511         # Create a hash for speeding the search of existing object in the current provision
512         for i in range(0,len(res2)):
513                 hash[str(res2[i]["dn"]).lower()] = res2[i]["dn"]
514
515         for k in hash_new.keys():
516                 if not hash.has_key(k):
517                         listMissing.append(hash_new[k])
518                 else:
519                         listPresent.append(hash_new[k])
520
521         # Sort the missing object in order to have object of the lowest level first (which can be
522         # containers for higher level objects)
523         listMissing.sort(dn_sort)
524         listPresent.sort(dn_sort)
525
526         if ischema:
527                 # The following lines (up to the for loop) is to load the up to date schema into our current LDB
528                 # a complete schema is needed as the insertion of attributes and class is done against it
529                 # and the schema is self validated
530                 # The double ldb open and schema validation is taken from the initial provision script
531                 # it's not certain that it is really needed ....
532                 sam_ldb = Ldb(session_info=session, credentials=creds, lp=lp)
533                 schema = Schema(setup_path, names.domainsid, schemadn=basedn, serverdn=str(names.serverdn))
534                 # Load the schema from the one we computed earlier
535                 sam_ldb.set_schema_from_ldb(schema.ldb)
536                 # And now we can connect to the DB - the schema won't be loaded from the DB
537                 sam_ldb.connect(paths.samdb)
538                 sam_ldb.transaction_start()
539         else:
540                 sam_ldb.transaction_start()
541
542         empty = ldb.Message()
543         message(SIMPLE,"There are %d missing objects"%(len(listMissing)))
544         for dn in listMissing:
545                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
546                 delta = sam_ldb.msg_diff(empty,res[0])
547                 for att in hashAttrNotCopied.keys():
548                         delta.remove(att)
549                 for att in backlinked:
550                         delta.remove(att)
551                 delta.dn = dn
552
553                 sam_ldb.add(delta,["relax:0"])
554
555         changed = 0
556         for dn in listPresent:
557                 res = newsam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
558                 res2 = sam_ldb.search(expression="dn=%s"%(str(dn)),base=basedn, scope=SCOPE_SUBTREE,controls=["search_options:1:2"])
559                 delta = sam_ldb.msg_diff(res2[0],res[0])
560                 for att in hashAttrNotCopied.keys():
561                         delta.remove(att)
562                 for att in backlinked:
563                         delta.remove(att)
564                 delta.remove("parentGUID")
565                 nb = 0
566                 for att in delta:
567                         msgElt = delta.get(att)
568                         if att == "dn":
569                                 continue
570                         if handle_security_desc(ischema,att,msgElt,hashallSD,res2,res):
571                                 delta.remove(att)
572                                 continue
573                         if (not hashOverwrittenAtt.has_key(att) or not (hashOverwrittenAtt.get(att)&2^msgElt.flags())):
574                                 if  handle_special_case(att,delta,res,res2,ischema)==0 and msgElt.flags()!=ldb.FLAG_MOD_ADD:
575                                         i = 0
576                                         if opts.debugchange:
577                                                 message(CHANGE, "dn= "+str(dn)+ " "+att + " with flag "+str(msgElt.flags())+ " is not allowed to be changed/removed, I discard this change ...")
578                                                 for e in range(0,len(res2[0][att])):
579                                                         message(CHANGE,"old %d : %s"%(i,str(res2[0][att][e])))
580                                                 if msgElt.flags() == 2:
581                                                         i = 0
582                                                         for e in range(0,len(res[0][att])):
583                                                                 message(CHANGE,"new %d : %s"%(i,str(res[0][att][e])))
584                                         delta.remove(att)
585                 delta.dn = dn
586                 if len(delta.items()) >1:
587                         attributes=",".join(delta.keys())
588                         message(CHANGE,"%s is different from the reference one, changed attributes: %s"%(dn,attributes))
589                         changed = changed + 1
590                         sam_ldb.modify(delta)
591
592         sam_ldb.transaction_commit()
593         message(SIMPLE,"There are %d changed objects"%(changed))
594         return hashallSD
595
596 # Check that SD are correct
597 def check_updated_sd(newpaths,paths,creds,session,names):
598         newsam_ldb = Ldb(newpaths.samdb, session_info=session, credentials=creds,lp=lp)
599         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
600         res = newsam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
601         res2 = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
602         hash_new = {}
603         for i in range(0,len(res)):
604                 hash_new[str(res[i]["dn"]).lower()] = ndr_unpack(security.descriptor,str(res[i]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
605
606         for i in range(0,len(res2)):
607                 key = str(res2[i]["dn"]).lower()
608                 if hash_new.has_key(key):
609                         sddl = ndr_unpack(security.descriptor,str(res2[i]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
610                         if sddl != hash_new[key]:
611                                 print "%s new sddl/sddl in ref"%key
612                                 print "%s\n%s"%(sddl,hash_new[key])
613
614 # Simple update method for updating the SD that rely on the fact that nobody should have modified the SD
615 # This assumption is safe right now (alpha9) but should be removed asap
616 def update_sd(paths,creds,session,names):
617         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp,options=["modules:samba_dsdb"])
618         sam_ldb.transaction_start()
619         # First update the SD for the rootdn
620         sam_ldb.set_session_info(session)
621         res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
622         delta = ldb.Message()
623         delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
624         descr = get_domain_descriptor(names.domainsid)
625         delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
626         sam_ldb.modify(delta,["recalculate_sd:0"])
627         # Then the config dn
628         res = sam_ldb.search(expression="objectClass=*",base=str(names.configdn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
629         delta = ldb.Message()
630         delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
631         descr = get_config_descriptor(names.domainsid)
632         delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
633         sam_ldb.modify(delta,["recalculate_sd:0"])
634         # Then the schema dn
635         res = sam_ldb.search(expression="objectClass=*",base=str(names.schemadn), scope=SCOPE_BASE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
636         delta = ldb.Message()
637         delta.dn = ldb.Dn(sam_ldb,str(res[0]["dn"]))
638         descr = get_schema_descriptor(names.domainsid)
639         delta["nTSecurityDescriptor"] = ldb.MessageElement( descr,ldb.FLAG_MOD_REPLACE,"nTSecurityDescriptor" )
640         sam_ldb.modify(delta,["recalculate_sd:0"])
641
642         # Then the rest
643         hash = {}
644         res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","whenCreated"],controls=["search_options:1:2"])
645         for obj in res:
646                 if not (str(obj["dn"]) == str(names.rootdn) or
647                         str(obj["dn"]) == str(names.configdn) or \
648                         str(obj["dn"]) == str(names.schemadn)):
649                         hash[str(obj["dn"])] = obj["whenCreated"]
650
651         listkeys = hash.keys()
652         listkeys.sort(dn_sort)
653
654         for key in listkeys:
655                 try:
656                         delta = ldb.Message()
657                         delta.dn = ldb.Dn(sam_ldb,key)
658                         delta["whenCreated"] = ldb.MessageElement( hash[key],ldb.FLAG_MOD_REPLACE,"whenCreated" )
659                         sam_ldb.modify(delta,["recalculate_sd:0"])
660                 except:
661                         sam_ldb.transaction_cancel()
662                         res = sam_ldb.search(expression="objectClass=*",base=str(names.rootdn), scope=SCOPE_SUBTREE,attrs=["dn","nTSecurityDescriptor"],controls=["search_options:1:2"])
663                         print "bad stuff" +ndr_unpack(security.descriptor,str(res[0]["nTSecurityDescriptor"])).as_sddl(names.domainsid)
664                         return
665         sam_ldb.transaction_commit()
666
667 def rmall(topdir):
668         for root, dirs, files in os.walk(topdir, topdown=False):
669                 for name in files:
670                         os.remove(os.path.join(root, name))
671                 for name in dirs:
672                         os.rmdir(os.path.join(root, name))
673         os.rmdir(topdir)
674
675
676 def update_basesamdb(newpaths,paths,names):
677         message(SIMPLE,"Copy samdb")
678         shutil.copy(newpaths.samdb,paths.samdb)
679
680         message(SIMPLE,"Update partitions filename if needed")
681         schemaldb=os.path.join(paths.private_dir,"schema.ldb")
682         configldb=os.path.join(paths.private_dir,"configuration.ldb")
683         usersldb=os.path.join(paths.private_dir,"users.ldb")
684         samldbdir=os.path.join(paths.private_dir,"sam.ldb.d")
685
686         if not os.path.isdir(samldbdir):
687                 os.mkdir(samldbdir)
688                 os.chmod(samldbdir,0700)
689         if os.path.isfile(schemaldb):
690                 shutil.copy(schemaldb,os.path.join(samldbdir,"%s.ldb"%str(names.schemadn).upper()))
691                 os.remove(schemaldb)
692         if os.path.isfile(usersldb):
693                 shutil.copy(usersldb,os.path.join(samldbdir,"%s.ldb"%str(names.rootdn).upper()))
694                 os.remove(usersldb)
695         if os.path.isfile(configldb):
696                 shutil.copy(configldb,os.path.join(samldbdir,"%s.ldb"%str(names.configdn).upper()))
697                 os.remove(configldb)
698
699 def update_privilege(newpaths,paths):
700         message(SIMPLE,"Copy privilege")
701         shutil.copy(os.path.join(newpaths.private_dir,"privilege.ldb"),os.path.join(paths.private_dir,"privilege.ldb"))
702
703 # For each partition check the differences
704 def update_samdb(newpaths,paths,creds,session,names):
705
706         message(SIMPLE, "Doing schema update")
707         hashdef = check_diff_name(newpaths,paths,creds,session,str(names.schemadn),names,1)
708         message(SIMPLE,"Done with schema update")
709         message(SIMPLE,"Scanning whole provision for updates and additions")
710         hashSD = check_diff_name(newpaths,paths,creds,session,str(names.rootdn),names,0)
711         message(SIMPLE,"Done with scanning")
712
713 def update_machine_account_password(paths,creds,session,names):
714
715         secrets_ldb = Ldb(paths.secrets, session_info=session, credentials=creds,lp=lp)
716         secrets_ldb.transaction_start()
717         secrets_msg = secrets_ldb.search(expression=("samAccountName=%s$" % names.netbiosname), attrs=["secureChannelType"])
718         sam_ldb = Ldb(paths.samdb, session_info=session, credentials=creds,lp=lp)
719         sam_ldb.transaction_start()
720         if int(secrets_msg[0]["secureChannelType"][0]) == SEC_CHAN_BDC:
721                 res = sam_ldb.search(expression=("samAccountName=%s$" % names.netbiosname), attrs=[])
722                 assert(len(res) == 1)
723
724                 msg = ldb.Message(res[0].dn)
725                 machinepass = glue.generate_random_str(12)
726                 msg["userPassword"] = ldb.MessageElement(machinepass, ldb.FLAG_MOD_REPLACE, "userPassword")
727                 sam_ldb.modify(msg)
728
729                 res = sam_ldb.search(expression=("samAccountName=%s$" % names.netbiosname),
730                                      attrs=["msDs-keyVersionNumber"])
731                 assert(len(res) == 1)
732                 kvno = int(str(res[0]["msDs-keyVersionNumber"]))
733
734                 secretsdb_self_join(secrets_ldb, domain=names.domain,
735                                     realm=names.realm,
736                                         domainsid=names.domainsid,
737                                     dnsdomain=names.dnsdomain,
738                                     netbiosname=names.netbiosname,
739                                     machinepass=machinepass,
740                                     key_version_number=kvno,
741                                     secure_channel_type=int(secrets_msg[0]["secureChannelType"][0]))
742                 sam_ldb.transaction_prepare_commit()
743                 secrets_ldb.transaction_prepare_commit()
744                 sam_ldb.transaction_commit()
745                 secrets_ldb.transaction_commit()
746         else:
747                 secrets_ldb.transaction_cancel()
748
749 # From here start the big steps of the program
750 # First get files paths
751 paths=get_paths(targetdir=opts.targetdir,smbconf=smbconf)
752 paths.setup = setup_dir
753 def setup_path(file):
754         return os.path.join(setup_dir, file)
755 # Guess all the needed names (variables in fact) from the current
756 # provision.
757 names = guess_names_from_current_provision(creds,session,paths)
758 # Let's see them
759 print_names(names)
760 # With all this information let's create a fresh new provision used as reference
761 provisiondir = newprovision(names,setup_dir,creds,session,smbconf)
762 # Get file paths of this new provision
763 newpaths = get_paths(targetdir=provisiondir)
764 populate_backlink(newpaths,creds,session,names.schemadn)
765 # Check the difference
766 update_basesamdb(newpaths,paths,names)
767 update_secrets(newpaths,paths,creds,session)
768 update_privilege(newpaths,paths)
769 update_machine_account_password(paths,creds,session,names)
770
771 if opts.full:
772         update_samdb(newpaths,paths,creds,session,names)
773 # SD should be created with admin but as some previous acl were so wrong that admin can't modify them we have first
774 # to recreate them with the good form but with system account and then give the ownership to admin ...
775 admin_session_info = admin_session(lp, str(names.domainsid))
776 message(SIMPLE,"Updating SD")
777 update_sd(paths,creds,session,names)
778 update_sd(paths,creds,admin_session_info,names)
779 check_updated_sd(newpaths,paths,creds,session,names)
780 message(SIMPLE,"Upgrade finished !")
781 # remove reference provision now that everything is done !
782 rmall(provisiondir)