samba-tool dbcheck: handle missing objectClass
[bbaumbach/samba-autobuild/.git] / python / samba / dbchecker.py
1 # Samba4 AD database checker
2 #
3 # Copyright (C) Andrew Tridgell 2011
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 import ldb
21 import samba
22 import time
23 from samba import dsdb
24 from samba import common
25 from samba.dcerpc import misc
26 from samba.ndr import ndr_unpack, ndr_pack
27 from samba.dcerpc import drsblobs
28 from samba.common import dsdb_Dn
29 from samba.dcerpc import security
30 from samba.descriptor import get_wellknown_sds, get_diff_sds
31 from samba.auth import system_session, admin_session
32
33
34 class dbcheck(object):
35     """check a SAM database for errors"""
36
37     def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
38                  yes=False, quiet=False, in_transaction=False,
39                  reset_well_known_acls=False):
40         self.samdb = samdb
41         self.dict_oid_name = None
42         self.samdb_schema = (samdb_schema or samdb)
43         self.verbose = verbose
44         self.fix = fix
45         self.yes = yes
46         self.quiet = quiet
47         self.remove_all_unknown_attributes = False
48         self.remove_all_empty_attributes = False
49         self.fix_all_normalisation = False
50         self.fix_all_DN_GUIDs = False
51         self.fix_all_binary_dn = False
52         self.remove_all_deleted_DN_links = False
53         self.fix_all_target_mismatch = False
54         self.fix_all_metadata = False
55         self.fix_time_metadata = False
56         self.fix_all_missing_backlinks = False
57         self.fix_all_orphaned_backlinks = False
58         self.fix_rmd_flags = False
59         self.fix_ntsecuritydescriptor = False
60         self.fix_ntsecuritydescriptor_owner_group = False
61         self.seize_fsmo_role = False
62         self.move_to_lost_and_found = False
63         self.fix_instancetype = False
64         self.fix_replmetadata_zero_invocationid = False
65         self.fix_deleted_deleted_objects = False
66         self.reset_well_known_acls = reset_well_known_acls
67         self.reset_all_well_known_acls = False
68         self.in_transaction = in_transaction
69         self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
70         self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
71         self.schema_dn = samdb.get_schema_basedn()
72         self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
73         self.ntds_dsa = ldb.Dn(samdb, samdb.get_dsServiceName())
74         self.class_schemaIDGUID = {}
75         self.wellknown_sds = get_wellknown_sds(self.samdb)
76         self.fix_all_missing_objectclass = False
77
78         self.name_map = {}
79         try:
80             res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % samdb.domain_dn(), scope=ldb.SCOPE_BASE,
81                            attrs=["objectSid"])
82             dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
83             self.name_map['DnsAdmins'] = str(dnsadmins_sid)
84         except ldb.LdbError, (enum, estr):
85             if enum != ldb.ERR_NO_SUCH_OBJECT:
86                 raise
87             pass
88
89         self.system_session_info = system_session()
90         self.admin_session_info = admin_session(None, samdb.get_domain_sid())
91
92         res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs'])
93         if "msDS-hasMasterNCs" in res[0]:
94             self.write_ncs = res[0]["msDS-hasMasterNCs"]
95         else:
96             # If the Forest Level is less than 2003 then there is no
97             # msDS-hasMasterNCs, so we fall back to hasMasterNCs
98             # no need to merge as all the NCs that are in hasMasterNCs must
99             # also be in msDS-hasMasterNCs (but not the opposite)
100             if "hasMasterNCs" in res[0]:
101                 self.write_ncs = res[0]["hasMasterNCs"]
102             else:
103                 self.write_ncs = None
104
105         res = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['namingContexts'])
106         try:
107             ncs = res[0]["namingContexts"]
108             self.deleted_objects_containers = []
109             for nc in ncs:
110                 try:
111                     dn = self.samdb.get_wellknown_dn(ldb.Dn(self.samdb, nc),
112                                                      dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER)
113                     self.deleted_objects_containers.append(dn)
114                 except KeyError:
115                     pass
116         except KeyError:
117             pass
118         except IndexError:
119             pass
120
121     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
122         '''perform a database check, returning the number of errors found'''
123
124         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
125         self.report('Checking %u objects' % len(res))
126         error_count = 0
127
128         for object in res:
129             error_count += self.check_object(object.dn, attrs=attrs)
130
131         if DN is None:
132             error_count += self.check_rootdse()
133
134         if error_count != 0 and not self.fix:
135             self.report("Please use --fix to fix these errors")
136
137         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
138         return error_count
139
140     def report(self, msg):
141         '''print a message unless quiet is set'''
142         if not self.quiet:
143             print(msg)
144
145     def confirm(self, msg, allow_all=False, forced=False):
146         '''confirm a change'''
147         if not self.fix:
148             return False
149         if self.quiet:
150             return self.yes
151         if self.yes:
152             forced = True
153         return common.confirm(msg, forced=forced, allow_all=allow_all)
154
155     ################################################################
156     # a local confirm function with support for 'all'
157     def confirm_all(self, msg, all_attr):
158         '''confirm a change with support for "all" '''
159         if not self.fix:
160             return False
161         if self.quiet:
162             return self.yes
163         if getattr(self, all_attr) == 'NONE':
164             return False
165         if getattr(self, all_attr) == 'ALL':
166             forced = True
167         else:
168             forced = self.yes
169         c = common.confirm(msg, forced=forced, allow_all=True)
170         if c == 'ALL':
171             setattr(self, all_attr, 'ALL')
172             return True
173         if c == 'NONE':
174             setattr(self, all_attr, 'NONE')
175             return False
176         return c
177
178     def do_delete(self, dn, controls, msg):
179         '''delete dn with optional verbose output'''
180         if self.verbose:
181             self.report("delete DN %s" % dn)
182         try:
183             controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
184             self.samdb.delete(dn, controls=controls)
185         except Exception, err:
186             self.report("%s : %s" % (msg, err))
187             return False
188         return True
189
190     def do_modify(self, m, controls, msg, validate=True):
191         '''perform a modify with optional verbose output'''
192         if self.verbose:
193             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
194         try:
195             controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
196             self.samdb.modify(m, controls=controls, validate=validate)
197         except Exception, err:
198             self.report("%s : %s" % (msg, err))
199             return False
200         return True
201
202     def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
203         '''perform a modify with optional verbose output'''
204         if self.verbose:
205             self.report("""dn: %s
206 changeType: modrdn
207 newrdn: %s
208 deleteOldRdn: 1
209 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
210         try:
211             to_dn = to_rdn + to_base
212             controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
213             self.samdb.rename(from_dn, to_dn, controls=controls)
214         except Exception, err:
215             self.report("%s : %s" % (msg, err))
216             return False
217         return True
218
219     def err_empty_attribute(self, dn, attrname):
220         '''fix empty attributes'''
221         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
222         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
223             self.report("Not fixing empty attribute %s" % attrname)
224             return
225
226         m = ldb.Message()
227         m.dn = dn
228         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
229         if self.do_modify(m, ["relax:0", "show_recycled:1"],
230                           "Failed to remove empty attribute %s" % attrname, validate=False):
231             self.report("Removed empty attribute %s" % attrname)
232
233     def err_normalise_mismatch(self, dn, attrname, values):
234         '''fix attribute normalisation errors'''
235         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
236         mod_list = []
237         for val in values:
238             normalised = self.samdb.dsdb_normalise_attributes(
239                 self.samdb_schema, attrname, [val])
240             if len(normalised) != 1:
241                 self.report("Unable to normalise value '%s'" % val)
242                 mod_list.append((val, ''))
243             elif (normalised[0] != val):
244                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
245                 mod_list.append((val, normalised[0]))
246         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
247             self.report("Not fixing attribute %s" % attrname)
248             return
249
250         m = ldb.Message()
251         m.dn = dn
252         for i in range(0, len(mod_list)):
253             (val, nval) = mod_list[i]
254             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
255             if nval != '':
256                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
257                     attrname)
258
259         if self.do_modify(m, ["relax:0", "show_recycled:1"],
260                           "Failed to normalise attribute %s" % attrname,
261                           validate=False):
262             self.report("Normalised attribute %s" % attrname)
263
264     def err_normalise_mismatch_replace(self, dn, attrname, values):
265         '''fix attribute normalisation errors'''
266         normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
267         self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
268         self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
269         if list(normalised) == values:
270             return
271         if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
272             self.report("Not fixing attribute '%s'" % attrname)
273             return
274
275         m = ldb.Message()
276         m.dn = dn
277         m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
278
279         if self.do_modify(m, ["relax:0", "show_recycled:1"],
280                           "Failed to normalise attribute %s" % attrname,
281                           validate=False):
282             self.report("Normalised attribute %s" % attrname)
283
284     def is_deleted_objects_dn(self, dsdb_dn):
285         '''see if a dsdb_Dn is the special Deleted Objects DN'''
286         return dsdb_dn.prefix == "B:32:%s:" % dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER
287
288     def err_missing_objectclass(self, dn):
289         """handle object without objectclass"""
290         self.report("ERROR: missing objectclass in object %s.  If you have another working DC, please run 'samba-tool drs replicate --full-sync --local <destinationDC> <sourceDC> %s'" % (dn, self.samdb.get_nc_root(dn)))
291         if not self.confirm_all("If you cannot re-sync from another DC, do you wish to delete object '%s'?" % dn, 'fix_all_missing_objectclass'):
292             self.report("Not deleting object with missing objectclass '%s'" % dn)
293             return
294         if self.do_delete(dn, ["relax:0"],
295                           "Failed to remove DN %s" % dn):
296             self.report("Removed DN %s" % dn)
297
298     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
299         """handle a DN pointing to a deleted object"""
300         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
301         self.report("Target GUID points at deleted DN %s" % correct_dn)
302         if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
303             self.report("Not removing")
304             return
305         m = ldb.Message()
306         m.dn = dn
307         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
308         if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
309                           "Failed to remove deleted DN attribute %s" % attrname):
310             self.report("Removed deleted DN on attribute %s" % attrname)
311
312     def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
313         """handle a missing target DN (both GUID and DN string form are missing)"""
314         # check if its a backlink
315         linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
316         if (linkID & 1 == 0) and str(dsdb_dn).find('\\0ADEL') == -1:
317             self.report("Not removing dangling forward link")
318             return
319         self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
320
321     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
322         """handle a missing GUID extended DN component"""
323         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
324         controls=["extended_dn:1:1", "show_recycled:1"]
325         try:
326             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
327                                     attrs=[], controls=controls)
328         except ldb.LdbError, (enum, estr):
329             self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
330             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
331             return
332         if len(res) == 0:
333             self.report("unable to find object for DN %s" % dsdb_dn.dn)
334             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
335             return
336         dsdb_dn.dn = res[0].dn
337
338         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
339             self.report("Not fixing %s" % errstr)
340             return
341         m = ldb.Message()
342         m.dn = dn
343         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
344         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
345
346         if self.do_modify(m, ["show_recycled:1"],
347                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
348             self.report("Fixed %s on attribute %s" % (errstr, attrname))
349
350     def err_incorrect_binary_dn(self, dn, attrname, val, dsdb_dn, errstr):
351         """handle an incorrect binary DN component"""
352         self.report("ERROR: %s binary component for %s in object %s - %s" % (errstr, attrname, dn, val))
353         controls=["extended_dn:1:1", "show_recycled:1"]
354
355         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_binary_dn'):
356             self.report("Not fixing %s" % errstr)
357             return
358         m = ldb.Message()
359         m.dn = dn
360         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
361         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
362
363         if self.do_modify(m, ["show_recycled:1"],
364                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
365             self.report("Fixed %s on attribute %s" % (errstr, attrname))
366
367     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
368         """handle a DN string being incorrect"""
369         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
370         dsdb_dn.dn = correct_dn
371
372         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
373             self.report("Not fixing %s" % errstr)
374             return
375         m = ldb.Message()
376         m.dn = dn
377         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
378         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
379         if self.do_modify(m, ["show_recycled:1"],
380                           "Failed to fix incorrect DN string on attribute %s" % attrname):
381             self.report("Fixed incorrect DN string on attribute %s" % (attrname))
382
383     def err_unknown_attribute(self, obj, attrname):
384         '''handle an unknown attribute error'''
385         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
386         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
387             self.report("Not removing %s" % attrname)
388             return
389         m = ldb.Message()
390         m.dn = obj.dn
391         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
392         if self.do_modify(m, ["relax:0", "show_recycled:1"],
393                           "Failed to remove unknown attribute %s" % attrname):
394             self.report("Removed unknown attribute %s" % (attrname))
395
396     def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
397         '''handle a missing backlink value'''
398         self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
399         if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
400             self.report("Not fixing missing backlink %s" % backlink_name)
401             return
402         m = ldb.Message()
403         m.dn = obj.dn
404         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
405         m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
406         if self.do_modify(m, ["show_recycled:1"],
407                           "Failed to fix missing backlink %s" % backlink_name):
408             self.report("Fixed missing backlink %s" % (backlink_name))
409
410     def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
411         '''handle a incorrect RMD_FLAGS value'''
412         rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
413         self.report("ERROR: incorrect RMD_FLAGS value %u for attribute '%s' in %s for link %s" % (rmd_flags, attrname, obj.dn, revealed_dn.dn.extended_str()))
414         if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
415             self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
416             return
417         m = ldb.Message()
418         m.dn = obj.dn
419         m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
420         if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
421                           "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
422             self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
423
424     def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
425         '''handle a orphaned backlink value'''
426         self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
427         if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
428             self.report("Not removing orphaned backlink %s" % link_name)
429             return
430         m = ldb.Message()
431         m.dn = obj.dn
432         m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
433         if self.do_modify(m, ["show_recycled:1", "relax:0"],
434                           "Failed to fix orphaned backlink %s" % link_name):
435             self.report("Fixed orphaned backlink %s" % (link_name))
436
437     def err_no_fsmoRoleOwner(self, obj):
438         '''handle a missing fSMORoleOwner'''
439         self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
440         res = self.samdb.search("",
441                                 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
442         assert len(res) == 1
443         serviceName = res[0]["dsServiceName"][0]
444         if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
445             self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
446             return
447         m = ldb.Message()
448         m.dn = obj.dn
449         m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
450         if self.do_modify(m, [],
451                           "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
452             self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
453
454     def err_missing_parent(self, obj):
455         '''handle a missing parent'''
456         self.report("ERROR: parent object not found for %s" % (obj.dn))
457         if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
458             self.report('Not moving object %s into LostAndFound' % (obj.dn))
459             return
460
461         keep_transaction = True
462         self.samdb.transaction_start()
463         try:
464             nc_root = self.samdb.get_nc_root(obj.dn);
465             lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
466             new_dn = ldb.Dn(self.samdb, str(obj.dn))
467             new_dn.remove_base_components(len(new_dn) - 1)
468             if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
469                               "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
470                 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
471
472                 m = ldb.Message()
473                 m.dn = obj.dn
474                 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
475
476                 if self.do_modify(m, [],
477                                   "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
478                     self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
479                     keep_transaction = True
480         except:
481             self.samdb.transaction_cancel()
482             raise
483
484         if keep_transaction:
485             self.samdb.transaction_commit()
486         else:
487             self.samdb.transaction_cancel()
488
489
490     def err_wrong_instancetype(self, obj, calculated_instancetype):
491         '''handle a wrong instanceType'''
492         self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
493         if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
494             self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
495             return
496
497         m = ldb.Message()
498         m.dn = obj.dn
499         m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
500         if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
501                           "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
502             self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
503
504     def find_revealed_link(self, dn, attrname, guid):
505         '''return a revealed link in an object'''
506         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
507                                 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
508         syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
509         for val in res[0][attrname]:
510             dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
511             guid2 = dsdb_dn.dn.get_extended_component("GUID")
512             if guid == guid2:
513                 return dsdb_dn
514         return None
515
516     def check_dn(self, obj, attrname, syntax_oid):
517         '''check a DN attribute for correctness'''
518         error_count = 0
519         for val in obj[attrname]:
520             dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
521
522             # all DNs should have a GUID component
523             guid = dsdb_dn.dn.get_extended_component("GUID")
524             if guid is None:
525                 error_count += 1
526                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
527                     "missing GUID")
528                 continue
529
530             guidstr = str(misc.GUID(guid))
531
532             attrs = ['isDeleted']
533
534             if (str(attrname).lower() == 'msds-hasinstantiatedncs') and (obj.dn == self.ntds_dsa):
535                 fixing_msDS_HasInstantiatedNCs = True
536                 attrs.append("instanceType")
537             else:
538                 fixing_msDS_HasInstantiatedNCs = False
539
540             linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
541             reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
542             if reverse_link_name is not None:
543                 attrs.append(reverse_link_name)
544
545             # check its the right GUID
546             try:
547                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
548                                         attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
549             except ldb.LdbError, (enum, estr):
550                 error_count += 1
551                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
552                 continue
553
554             if fixing_msDS_HasInstantiatedNCs:
555                 dsdb_dn.prefix = "B:8:%08X:" % int(res[0]['instanceType'][0])
556                 dsdb_dn.binary = "%08X" % int(res[0]['instanceType'][0])
557
558                 if str(dsdb_dn) != val:
559                     error_count +=1
560                     self.err_incorrect_binary_dn(obj.dn, attrname, val, dsdb_dn, "incorrect instanceType part of Binary DN")
561                     continue
562
563             # now we have two cases - the source object might or might not be deleted
564             is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
565             target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
566
567             # the target DN is not allowed to be deleted, unless the target DN is the
568             # special Deleted Objects container
569             if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
570                 error_count += 1
571                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
572                 continue
573
574             # check the DN matches in string form
575             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
576                 error_count += 1
577                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
578                                             res[0].dn, "incorrect string version of DN")
579                 continue
580
581             if is_deleted and not target_is_deleted and reverse_link_name is not None:
582                 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
583                 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
584                 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
585                     # the RMD_FLAGS for this link should be 1, as the target is deleted
586                     self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
587                     continue
588
589             # check the reverse_link is correct if there should be one
590             if reverse_link_name is not None:
591                 match_count = 0
592                 if reverse_link_name in res[0]:
593                     for v in res[0][reverse_link_name]:
594                         if v == obj.dn.extended_str():
595                             match_count += 1
596                 if match_count != 1:
597                     error_count += 1
598                     if linkID & 1:
599                         self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
600                     else:
601                         self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
602                     continue
603
604         return error_count
605
606
607     def get_originating_time(self, val, attid):
608         '''Read metadata properties and return the originating time for
609            a given attributeId.
610
611            :return: the originating time or 0 if not found
612         '''
613
614         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
615         obj = repl.ctr
616
617         for o in repl.ctr.array:
618             if o.attid == attid:
619                 return o.originating_change_time
620
621         return 0
622
623     def process_metadata(self, val):
624         '''Read metadata properties and list attributes in it'''
625
626         list_att = []
627
628         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
629         obj = repl.ctr
630
631         for o in repl.ctr.array:
632             att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
633             list_att.append(att.lower())
634
635         return list_att
636
637
638     def fix_metadata(self, dn, attr):
639         '''re-write replPropertyMetaData elements for a single attribute for a
640         object. This is used to fix missing replPropertyMetaData elements'''
641         res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
642                                 controls = ["search_options:1:2", "show_recycled:1"])
643         msg = res[0]
644         nmsg = ldb.Message()
645         nmsg.dn = dn
646         nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
647         if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
648                           "Failed to fix metadata for attribute %s" % attr):
649             self.report("Fixed metadata for attribute %s" % attr)
650
651     def ace_get_effective_inherited_type(self, ace):
652         if ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY:
653             return None
654
655         check = False
656         if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT:
657             check = True
658         elif ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT:
659             check = True
660         elif ace.type == security.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT:
661             check = True
662         elif ace.type == security.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT:
663             check = True
664
665         if not check:
666             return None
667
668         if not ace.object.flags & security.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT:
669             return None
670
671         return str(ace.object.inherited_type)
672
673     def lookup_class_schemaIDGUID(self, cls):
674         if cls in self.class_schemaIDGUID:
675             return self.class_schemaIDGUID[cls]
676
677         flt = "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
678         res = self.samdb.search(base=self.schema_dn,
679                                 expression=flt,
680                                 attrs=["schemaIDGUID"])
681         t = str(ndr_unpack(misc.GUID, res[0]["schemaIDGUID"][0]))
682
683         self.class_schemaIDGUID[cls] = t
684         return t
685
686     def process_sd(self, dn, obj):
687         sd_attr = "nTSecurityDescriptor"
688         sd_val = obj[sd_attr]
689
690         sd = ndr_unpack(security.descriptor, str(sd_val))
691
692         is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
693         if is_deleted:
694             # we don't fix deleted objects
695             return (sd, None)
696
697         sd_clean = security.descriptor()
698         sd_clean.owner_sid = sd.owner_sid
699         sd_clean.group_sid = sd.group_sid
700         sd_clean.type = sd.type
701         sd_clean.revision = sd.revision
702
703         broken = False
704         last_inherited_type = None
705
706         aces = []
707         if sd.sacl is not None:
708             aces = sd.sacl.aces
709         for i in range(0, len(aces)):
710             ace = aces[i]
711
712             if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
713                 sd_clean.sacl_add(ace)
714                 continue
715
716             t = self.ace_get_effective_inherited_type(ace)
717             if t is None:
718                 continue
719
720             if last_inherited_type is not None:
721                 if t != last_inherited_type:
722                     # if it inherited from more than
723                     # one type it's very likely to be broken
724                     #
725                     # If not the recalculation will calculate
726                     # the same result.
727                     broken = True
728                 continue
729
730             last_inherited_type = t
731
732         aces = []
733         if sd.dacl is not None:
734             aces = sd.dacl.aces
735         for i in range(0, len(aces)):
736             ace = aces[i]
737
738             if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
739                 sd_clean.dacl_add(ace)
740                 continue
741
742             t = self.ace_get_effective_inherited_type(ace)
743             if t is None:
744                 continue
745
746             if last_inherited_type is not None:
747                 if t != last_inherited_type:
748                     # if it inherited from more than
749                     # one type it's very likely to be broken
750                     #
751                     # If not the recalculation will calculate
752                     # the same result.
753                     broken = True
754                 continue
755
756             last_inherited_type = t
757
758         if broken:
759             return (sd_clean, sd)
760
761         if last_inherited_type is None:
762             # ok
763             return (sd, None)
764
765         cls = None
766         try:
767             cls = obj["objectClass"][-1]
768         except KeyError, e:
769             pass
770
771         if cls is None:
772             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
773                                     attrs=["isDeleted", "objectClass"],
774                                     controls=["show_recycled:1"])
775             o = res[0]
776             is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE'
777             if is_deleted:
778                 # we don't fix deleted objects
779                 return (sd, None)
780             cls = o["objectClass"][-1]
781
782         t = self.lookup_class_schemaIDGUID(cls)
783
784         if t != last_inherited_type:
785             # broken
786             return (sd_clean, sd)
787
788         # ok
789         return (sd, None)
790
791     def err_wrong_sd(self, dn, sd, sd_broken):
792         '''re-write the SD due to incorrect inherited ACEs'''
793         sd_attr = "nTSecurityDescriptor"
794         sd_val = ndr_pack(sd)
795         sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
796
797         if not self.confirm_all('Fix %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor'):
798             self.report('Not fixing %s on %s\n' % (sd_attr, dn))
799             return
800
801         nmsg = ldb.Message()
802         nmsg.dn = dn
803         nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
804         if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
805                           "Failed to fix attribute %s" % sd_attr):
806             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
807
808     def err_wrong_default_sd(self, dn, sd, sd_old, diff):
809         '''re-write the SD due to not matching the default (optional mode for fixing an incorrect provision)'''
810         sd_attr = "nTSecurityDescriptor"
811         sd_val = ndr_pack(sd)
812         sd_old_val = ndr_pack(sd_old)
813         sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
814         if sd.owner_sid is not None:
815             sd_flags |= security.SECINFO_OWNER
816         if sd.group_sid is not None:
817             sd_flags |= security.SECINFO_GROUP
818
819         if not self.confirm_all('Reset %s on %s back to provision default?\n%s' % (sd_attr, dn, diff), 'reset_all_well_known_acls'):
820             self.report('Not resetting %s on %s\n' % (sd_attr, dn))
821             return
822
823         m = ldb.Message()
824         m.dn = dn
825         m[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
826         if self.do_modify(m, ["sd_flags:1:%d" % sd_flags],
827                           "Failed to reset attribute %s" % sd_attr):
828             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
829
830     def err_missing_sd_owner(self, dn, sd):
831         '''re-write the SD due to a missing owner or group'''
832         sd_attr = "nTSecurityDescriptor"
833         sd_val = ndr_pack(sd)
834         sd_flags = security.SECINFO_OWNER | security.SECINFO_GROUP
835
836         if not self.confirm_all('Fix missing owner or group in %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor_owner_group'):
837             self.report('Not fixing missing owner or group %s on %s\n' % (sd_attr, dn))
838             return
839
840         nmsg = ldb.Message()
841         nmsg.dn = dn
842         nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
843
844         # By setting the session_info to admin_session_info and
845         # setting the security.SECINFO_OWNER | security.SECINFO_GROUP
846         # flags we cause the descriptor module to set the correct
847         # owner and group on the SD, replacing the None/NULL values
848         # for owner_sid and group_sid currently present.
849         #
850         # The admin_session_info matches that used in provision, and
851         # is the best guess we can make for an existing object that
852         # hasn't had something specifically set.
853         #
854         # This is important for the dns related naming contexts.
855         self.samdb.set_session_info(self.admin_session_info)
856         if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
857                           "Failed to fix metadata for attribute %s" % sd_attr):
858             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
859         self.samdb.set_session_info(self.system_session_info)
860
861
862     def has_replmetadata_zero_invocationid(self, dn, repl_meta_data):
863         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
864                           str(repl_meta_data))
865         ctr = repl.ctr
866         found = False
867         for o in ctr.array:
868             # Search for a zero invocationID
869             if o.originating_invocation_id != misc.GUID("00000000-0000-0000-0000-000000000000"):
870                 continue
871
872             found = True
873             self.report('''ERROR: on replPropertyMetaData of %s, the instanceType on attribute 0x%08x,
874                            version %d changed at %s is 00000000-0000-0000-0000-000000000000,
875                            but should be non-zero.  Proposed fix is to set to our invocationID (%s).'''
876                         % (dn, o.attid, o.version,
877                            time.ctime(samba.nttime2unix(o.originating_change_time)),
878                            self.samdb.get_invocation_id()))
879
880         return found
881
882
883     def err_replmetadata_zero_invocationid(self, dn, attr, repl_meta_data):
884         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
885                           str(repl_meta_data))
886         ctr = repl.ctr
887         now = samba.unix2nttime(int(time.time()))
888         found = False
889         for o in ctr.array:
890             # Search for a zero invocationID
891             if o.originating_invocation_id != misc.GUID("00000000-0000-0000-0000-000000000000"):
892                 continue
893
894             found = True
895             seq = self.samdb.sequence_number(ldb.SEQ_NEXT)
896             o.version = o.version + 1
897             o.originating_change_time = now
898             o.originating_invocation_id = misc.GUID(self.samdb.get_invocation_id())
899             o.originating_usn = seq
900             o.local_usn = seq
901
902         if found:
903             replBlob = ndr_pack(repl)
904             msg = ldb.Message()
905             msg.dn = dn
906
907             if not self.confirm_all('Fix %s on %s by setting originating_invocation_id on some elements to our invocationID %s?'
908                                     % (attr, dn, self.samdb.get_invocation_id()), 'fix_replmetadata_zero_invocationid'):
909                 self.report('Not fixing %s on %s\n' % (attr, dn))
910                 return
911
912             nmsg = ldb.Message()
913             nmsg.dn = dn
914             nmsg[attr] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, attr)
915             if self.do_modify(nmsg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"],
916                               "Failed to fix attribute %s" % attr):
917                 self.report("Fixed attribute '%s' of '%s'\n" % (attr, dn))
918
919
920     def is_deleted_deleted_objects(self, obj):
921         faulty = False
922         if "description" not in obj:
923             self.report("ERROR: description not present on Deleted Objects container %s" % obj.dn)
924             faulty = True
925         if "showInAdvancedViewOnly" not in obj:
926             self.report("ERROR: showInAdvancedViewOnly not present on Deleted Objects container %s" % obj.dn)
927             faulty = True
928         if "objectCategory" not in obj:
929             self.report("ERROR: objectCategory not present on Deleted Objects container %s" % obj.dn)
930             faulty = True
931         if "isCriticalSystemObject" not in obj:
932             self.report("ERROR: isCriticalSystemObject not present on Deleted Objects container %s" % obj.dn)
933             faulty = True
934         if "isRecycled" in obj:
935             self.report("ERROR: isRecycled present on Deleted Objects container %s" % obj.dn)
936             faulty = True
937         return faulty
938
939
940     def err_deleted_deleted_objects(self, obj):
941         nmsg = ldb.Message()
942         nmsg.dn = dn = obj.dn
943
944         if "description" not in obj:
945             nmsg["description"] = ldb.MessageElement("Container for deleted objects", ldb.FLAG_MOD_REPLACE, "description")
946         if "showInAdvancedViewOnly" not in obj:
947             nmsg["showInAdvancedViewOnly"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "showInAdvancedViewOnly")
948         if "objectCategory" not in obj:
949             nmsg["objectCategory"] = ldb.MessageElement("CN=Container,%s" % self.schema_dn, ldb.FLAG_MOD_REPLACE, "objectCategory")
950         if "isCriticalSystemObject" not in obj:
951             nmsg["isCriticalSystemObject"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isCriticalSystemObject")
952         if "isRecycled" in obj:
953             nmsg["isRecycled"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_DELETE, "isRecycled")
954
955         if not self.confirm_all('Fix Deleted Objects container %s by restoring default attributes?'
956                                 % (dn), 'fix_deleted_deleted_objects'):
957             self.report('Not fixing missing/incorrect attributes on %s\n' % (dn))
958             return
959
960         if self.do_modify(nmsg, ["relax:0"],
961                           "Failed to fix Deleted Objects container  %s" % dn):
962             self.report("Fixed Deleted Objects container '%s'\n" % (dn))
963
964
965     def is_fsmo_role(self, dn):
966         if dn == self.samdb.domain_dn:
967             return True
968         if dn == self.infrastructure_dn:
969             return True
970         if dn == self.naming_dn:
971             return True
972         if dn == self.schema_dn:
973             return True
974         if dn == self.rid_dn:
975             return True
976
977         return False
978
979     def calculate_instancetype(self, dn):
980         instancetype = 0
981         nc_root = self.samdb.get_nc_root(dn)
982         if dn == nc_root:
983             instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
984             try:
985                 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
986             except ldb.LdbError, (enum, estr):
987                 if enum != ldb.ERR_NO_SUCH_OBJECT:
988                     raise
989             else:
990                 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
991
992         if self.write_ncs is not None and str(nc_root) in self.write_ncs:
993             instancetype |= dsdb.INSTANCE_TYPE_WRITE
994
995         return instancetype
996
997     def get_wellknown_sd(self, dn):
998         for [sd_dn, descriptor_fn] in self.wellknown_sds:
999             if dn == sd_dn:
1000                 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1001                 return ndr_unpack(security.descriptor,
1002                                   descriptor_fn(domain_sid,
1003                                                 name_map=self.name_map))
1004
1005         raise KeyError
1006
1007     def check_object(self, dn, attrs=['*']):
1008         '''check one object'''
1009         if self.verbose:
1010             self.report("Checking object %s" % dn)
1011         if '*' in attrs:
1012             attrs.append("replPropertyMetaData")
1013
1014         try:
1015             sd_flags = 0
1016             sd_flags |= security.SECINFO_OWNER
1017             sd_flags |= security.SECINFO_GROUP
1018             sd_flags |= security.SECINFO_DACL
1019             sd_flags |= security.SECINFO_SACL
1020
1021             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
1022                                     controls=[
1023                                         "extended_dn:1:1",
1024                                         "show_recycled:1",
1025                                         "show_deleted:1",
1026                                         "sd_flags:1:%d" % sd_flags,
1027                                     ],
1028                                     attrs=attrs)
1029         except ldb.LdbError, (enum, estr):
1030             if enum == ldb.ERR_NO_SUCH_OBJECT:
1031                 if self.in_transaction:
1032                     self.report("ERROR: Object %s disappeared during check" % dn)
1033                     return 1
1034                 return 0
1035             raise
1036         if len(res) != 1:
1037             self.report("ERROR: Object %s failed to load during check" % dn)
1038             return 1
1039         obj = res[0]
1040         error_count = 0
1041         list_attrs_from_md = []
1042         list_attrs_seen = []
1043         got_repl_property_meta_data = False
1044         got_objectclass = False
1045
1046         for attrname in obj:
1047             if attrname == 'dn':
1048                 continue
1049
1050             if str(attrname).lower() == 'objectclass':
1051                 got_objectclass = True
1052
1053             if str(attrname).lower() == 'replpropertymetadata':
1054                 if self.has_replmetadata_zero_invocationid(dn, obj[attrname]):
1055                     error_count += 1
1056                     self.err_replmetadata_zero_invocationid(dn, attrname, obj[attrname])
1057                     # We don't continue, as we may also have other fixes for this attribute
1058                     # based on what other attributes we see.
1059
1060                 list_attrs_from_md = self.process_metadata(obj[attrname])
1061                 got_repl_property_meta_data = True
1062                 continue
1063
1064             if str(attrname).lower() == 'ntsecuritydescriptor':
1065                 (sd, sd_broken) = self.process_sd(dn, obj)
1066                 if sd_broken is not None:
1067                     self.err_wrong_sd(dn, sd, sd_broken)
1068                     error_count += 1
1069                     continue
1070
1071                 if sd.owner_sid is None or sd.group_sid is None:
1072                     self.err_missing_sd_owner(dn, sd)
1073                     error_count += 1
1074                     continue
1075
1076                 if self.reset_well_known_acls:
1077                     try:
1078                         well_known_sd = self.get_wellknown_sd(dn)
1079                     except KeyError:
1080                         continue
1081
1082                     current_sd = ndr_unpack(security.descriptor,
1083                                             str(obj[attrname][0]))
1084
1085                     diff = get_diff_sds(well_known_sd, current_sd, security.dom_sid(self.samdb.get_domain_sid()))
1086                     if diff != "":
1087                         self.err_wrong_default_sd(dn, well_known_sd, current_sd, diff)
1088                         error_count += 1
1089                         continue
1090                 continue
1091
1092             if str(attrname).lower() == 'objectclass':
1093                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
1094                 if list(normalised) != list(obj[attrname]):
1095                     self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
1096                     error_count += 1
1097                 continue
1098
1099             # check for empty attributes
1100             for val in obj[attrname]:
1101                 if val == '':
1102                     self.err_empty_attribute(dn, attrname)
1103                     error_count += 1
1104                     continue
1105
1106             # get the syntax oid for the attribute, so we can can have
1107             # special handling for some specific attribute types
1108             try:
1109                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
1110             except Exception, msg:
1111                 self.err_unknown_attribute(obj, attrname)
1112                 error_count += 1
1113                 continue
1114
1115             flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
1116             if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
1117                 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
1118                 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
1119                 list_attrs_seen.append(str(attrname).lower())
1120
1121             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
1122                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
1123                 # it's some form of DN, do specialised checking on those
1124                 error_count += self.check_dn(obj, attrname, syntax_oid)
1125
1126             # check for incorrectly normalised attributes
1127             for val in obj[attrname]:
1128                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
1129                 if len(normalised) != 1 or normalised[0] != val:
1130                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
1131                     error_count += 1
1132                     break
1133
1134             if str(attrname).lower() == "instancetype":
1135                 calculated_instancetype = self.calculate_instancetype(dn)
1136                 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
1137                     error_count += 1
1138                     self.err_wrong_instancetype(obj, calculated_instancetype)
1139
1140         if not got_objectclass and ("*" in attrs or "objectclass" in map(str.lower, attrs)):
1141             error_count += 1
1142             self.err_missing_objectclass(dn)
1143
1144         show_dn = True
1145         if got_repl_property_meta_data:
1146             rdn = (str(dn).split(","))[0]
1147             if rdn == "CN=Deleted Objects":
1148                 isDeletedAttId = 131120
1149                 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
1150
1151                 expectedTimeDo = 2650466015990000000
1152                 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
1153                 if originating != expectedTimeDo:
1154                     if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
1155                         nmsg = ldb.Message()
1156                         nmsg.dn = dn
1157                         nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
1158                         error_count += 1
1159                         self.samdb.modify(nmsg, controls=["provision:0"])
1160
1161                     else:
1162                         self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
1163             for att in list_attrs_seen:
1164                 if not att in list_attrs_from_md:
1165                     if show_dn:
1166                         self.report("On object %s" % dn)
1167                         show_dn = False
1168                     error_count += 1
1169                     self.report("ERROR: Attribute %s not present in replication metadata" % att)
1170                     if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
1171                         self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
1172                         continue
1173                     self.fix_metadata(dn, att)
1174
1175         if self.is_fsmo_role(dn):
1176             if "fSMORoleOwner" not in obj and ("*" in attrs or "fsmoroleowner" in map(str.lower, attrs)):
1177                 self.err_no_fsmoRoleOwner(obj)
1178                 error_count += 1
1179
1180         try:
1181             if dn != self.samdb.get_root_basedn():
1182                 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
1183                                         controls=["show_recycled:1", "show_deleted:1"])
1184         except ldb.LdbError, (enum, estr):
1185             if enum == ldb.ERR_NO_SUCH_OBJECT:
1186                 self.err_missing_parent(obj)
1187                 error_count += 1
1188             else:
1189                 raise
1190
1191         if dn in self.deleted_objects_containers and '*' in attrs:
1192             if self.is_deleted_deleted_objects(obj):
1193                 self.err_deleted_deleted_objects(obj)
1194                 error_count += 1
1195
1196         return error_count
1197
1198     ################################################################
1199     # check special @ROOTDSE attributes
1200     def check_rootdse(self):
1201         '''check the @ROOTDSE special object'''
1202         dn = ldb.Dn(self.samdb, '@ROOTDSE')
1203         if self.verbose:
1204             self.report("Checking object %s" % dn)
1205         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
1206         if len(res) != 1:
1207             self.report("Object %s disappeared during check" % dn)
1208             return 1
1209         obj = res[0]
1210         error_count = 0
1211
1212         # check that the dsServiceName is in GUID form
1213         if not 'dsServiceName' in obj:
1214             self.report('ERROR: dsServiceName missing in @ROOTDSE')
1215             return error_count+1
1216
1217         if not obj['dsServiceName'][0].startswith('<GUID='):
1218             self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
1219             error_count += 1
1220             if not self.confirm('Change dsServiceName to GUID form?'):
1221                 return error_count
1222             res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
1223                                     scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
1224             guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
1225             m = ldb.Message()
1226             m.dn = dn
1227             m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
1228                                                     ldb.FLAG_MOD_REPLACE, 'dsServiceName')
1229             if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
1230                 self.report("Changed dsServiceName to GUID form")
1231         return error_count
1232
1233
1234     ###############################################
1235     # re-index the database
1236     def reindex_database(self):
1237         '''re-index the whole database'''
1238         m = ldb.Message()
1239         m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
1240         m['add']    = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
1241         m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
1242         return self.do_modify(m, [], 're-indexed database', validate=False)
1243
1244     ###############################################
1245     # reset @MODULES
1246     def reset_modules(self):
1247         '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
1248         m = ldb.Message()
1249         m.dn = ldb.Dn(self.samdb, "@MODULES")
1250         m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
1251         return self.do_modify(m, [], 'reset @MODULES on database', validate=False)