s3:libsmb: let cli_read_andx_create() accept any length
[Samba/gebeck_regimport.git] / python / samba / dbchecker.py
blobfd42a78df11a65e8cd8bd21572b927e9435abfe8
1 # Samba4 AD database checker
3 # Copyright (C) Andrew Tridgell 2011
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
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.
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.
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/>.
20 import ldb
21 from samba import dsdb
22 from samba import common
23 from samba.dcerpc import misc
24 from samba.ndr import ndr_unpack, ndr_pack
25 from samba.dcerpc import drsblobs
26 from samba.common import dsdb_Dn
27 from samba.dcerpc import security
30 class dbcheck(object):
31 """check a SAM database for errors"""
33 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
34 yes=False, quiet=False, in_transaction=False):
35 self.samdb = samdb
36 self.dict_oid_name = None
37 self.samdb_schema = (samdb_schema or samdb)
38 self.verbose = verbose
39 self.fix = fix
40 self.yes = yes
41 self.quiet = quiet
42 self.remove_all_unknown_attributes = False
43 self.remove_all_empty_attributes = False
44 self.fix_all_normalisation = False
45 self.fix_all_DN_GUIDs = False
46 self.fix_all_binary_dn = False
47 self.remove_all_deleted_DN_links = False
48 self.fix_all_target_mismatch = False
49 self.fix_all_metadata = False
50 self.fix_time_metadata = False
51 self.fix_all_missing_backlinks = False
52 self.fix_all_orphaned_backlinks = False
53 self.fix_rmd_flags = False
54 self.fix_ntsecuritydescriptor = False
55 self.seize_fsmo_role = False
56 self.move_to_lost_and_found = False
57 self.fix_instancetype = False
58 self.in_transaction = in_transaction
59 self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
60 self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
61 self.schema_dn = samdb.get_schema_basedn()
62 self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
63 self.ntds_dsa = ldb.Dn(samdb, samdb.get_dsServiceName())
64 self.class_schemaIDGUID = {}
66 res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs'])
67 if "msDS-hasMasterNCs" in res[0]:
68 self.write_ncs = res[0]["msDS-hasMasterNCs"]
69 else:
70 # If the Forest Level is less than 2003 then there is no
71 # msDS-hasMasterNCs, so we fall back to hasMasterNCs
72 # no need to merge as all the NCs that are in hasMasterNCs must
73 # also be in msDS-hasMasterNCs (but not the opposite)
74 if "hasMasterNCs" in res[0]:
75 self.write_ncs = res[0]["hasMasterNCs"]
76 else:
77 self.write_ncs = None
80 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
81 '''perform a database check, returning the number of errors found'''
83 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
84 self.report('Checking %u objects' % len(res))
85 error_count = 0
87 for object in res:
88 error_count += self.check_object(object.dn, attrs=attrs)
90 if DN is None:
91 error_count += self.check_rootdse()
93 if error_count != 0 and not self.fix:
94 self.report("Please use --fix to fix these errors")
96 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
97 return error_count
99 def report(self, msg):
100 '''print a message unless quiet is set'''
101 if not self.quiet:
102 print(msg)
104 def confirm(self, msg, allow_all=False, forced=False):
105 '''confirm a change'''
106 if not self.fix:
107 return False
108 if self.quiet:
109 return self.yes
110 if self.yes:
111 forced = True
112 return common.confirm(msg, forced=forced, allow_all=allow_all)
114 ################################################################
115 # a local confirm function with support for 'all'
116 def confirm_all(self, msg, all_attr):
117 '''confirm a change with support for "all" '''
118 if not self.fix:
119 return False
120 if self.quiet:
121 return self.yes
122 if getattr(self, all_attr) == 'NONE':
123 return False
124 if getattr(self, all_attr) == 'ALL':
125 forced = True
126 else:
127 forced = self.yes
128 c = common.confirm(msg, forced=forced, allow_all=True)
129 if c == 'ALL':
130 setattr(self, all_attr, 'ALL')
131 return True
132 if c == 'NONE':
133 setattr(self, all_attr, 'NONE')
134 return False
135 return c
137 def do_modify(self, m, controls, msg, validate=True):
138 '''perform a modify with optional verbose output'''
139 if self.verbose:
140 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
141 try:
142 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
143 self.samdb.modify(m, controls=controls, validate=validate)
144 except Exception, err:
145 self.report("%s : %s" % (msg, err))
146 return False
147 return True
149 def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
150 '''perform a modify with optional verbose output'''
151 if self.verbose:
152 self.report("""dn: %s
153 changeType: modrdn
154 newrdn: %s
155 deleteOldRdn: 1
156 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
157 try:
158 to_dn = to_rdn + to_base
159 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
160 self.samdb.rename(from_dn, to_dn, controls=controls)
161 except Exception, err:
162 self.report("%s : %s" % (msg, err))
163 return False
164 return True
166 def err_empty_attribute(self, dn, attrname):
167 '''fix empty attributes'''
168 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
169 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
170 self.report("Not fixing empty attribute %s" % attrname)
171 return
173 m = ldb.Message()
174 m.dn = dn
175 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
176 if self.do_modify(m, ["relax:0", "show_recycled:1"],
177 "Failed to remove empty attribute %s" % attrname, validate=False):
178 self.report("Removed empty attribute %s" % attrname)
180 def err_normalise_mismatch(self, dn, attrname, values):
181 '''fix attribute normalisation errors'''
182 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
183 mod_list = []
184 for val in values:
185 normalised = self.samdb.dsdb_normalise_attributes(
186 self.samdb_schema, attrname, [val])
187 if len(normalised) != 1:
188 self.report("Unable to normalise value '%s'" % val)
189 mod_list.append((val, ''))
190 elif (normalised[0] != val):
191 self.report("value '%s' should be '%s'" % (val, normalised[0]))
192 mod_list.append((val, normalised[0]))
193 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
194 self.report("Not fixing attribute %s" % attrname)
195 return
197 m = ldb.Message()
198 m.dn = dn
199 for i in range(0, len(mod_list)):
200 (val, nval) = mod_list[i]
201 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
202 if nval != '':
203 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
204 attrname)
206 if self.do_modify(m, ["relax:0", "show_recycled:1"],
207 "Failed to normalise attribute %s" % attrname,
208 validate=False):
209 self.report("Normalised attribute %s" % attrname)
211 def err_normalise_mismatch_replace(self, dn, attrname, values):
212 '''fix attribute normalisation errors'''
213 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
214 self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
215 self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
216 if list(normalised) == values:
217 return
218 if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
219 self.report("Not fixing attribute '%s'" % attrname)
220 return
222 m = ldb.Message()
223 m.dn = dn
224 m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
226 if self.do_modify(m, ["relax:0", "show_recycled:1"],
227 "Failed to normalise attribute %s" % attrname,
228 validate=False):
229 self.report("Normalised attribute %s" % attrname)
231 def is_deleted_objects_dn(self, dsdb_dn):
232 '''see if a dsdb_Dn is the special Deleted Objects DN'''
233 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
235 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
236 """handle a DN pointing to a deleted object"""
237 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
238 self.report("Target GUID points at deleted DN %s" % correct_dn)
239 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
240 self.report("Not removing")
241 return
242 m = ldb.Message()
243 m.dn = dn
244 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
245 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
246 "Failed to remove deleted DN attribute %s" % attrname):
247 self.report("Removed deleted DN on attribute %s" % attrname)
249 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
250 """handle a missing target DN (both GUID and DN string form are missing)"""
251 # check if its a backlink
252 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
253 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
254 self.report("Not removing dangling forward link")
255 return
256 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
258 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
259 """handle a missing GUID extended DN component"""
260 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
261 controls=["extended_dn:1:1", "show_recycled:1"]
262 try:
263 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
264 attrs=[], controls=controls)
265 except ldb.LdbError, (enum, estr):
266 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
267 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
268 return
269 if len(res) == 0:
270 self.report("unable to find object for DN %s" % dsdb_dn.dn)
271 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
272 return
273 dsdb_dn.dn = res[0].dn
275 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
276 self.report("Not fixing %s" % errstr)
277 return
278 m = ldb.Message()
279 m.dn = dn
280 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
281 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
283 if self.do_modify(m, ["show_recycled:1"],
284 "Failed to fix %s on attribute %s" % (errstr, attrname)):
285 self.report("Fixed %s on attribute %s" % (errstr, attrname))
287 def err_incorrect_binary_dn(self, dn, attrname, val, dsdb_dn, errstr):
288 """handle an incorrect binary DN component"""
289 self.report("ERROR: %s binary component for %s in object %s - %s" % (errstr, attrname, dn, val))
290 controls=["extended_dn:1:1", "show_recycled:1"]
292 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_binary_dn'):
293 self.report("Not fixing %s" % errstr)
294 return
295 m = ldb.Message()
296 m.dn = dn
297 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
298 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
300 if self.do_modify(m, ["show_recycled:1"],
301 "Failed to fix %s on attribute %s" % (errstr, attrname)):
302 self.report("Fixed %s on attribute %s" % (errstr, attrname))
304 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
305 """handle a DN string being incorrect"""
306 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
307 dsdb_dn.dn = correct_dn
309 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
310 self.report("Not fixing %s" % errstr)
311 return
312 m = ldb.Message()
313 m.dn = dn
314 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
315 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
316 if self.do_modify(m, ["show_recycled:1"],
317 "Failed to fix incorrect DN string on attribute %s" % attrname):
318 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
320 def err_unknown_attribute(self, obj, attrname):
321 '''handle an unknown attribute error'''
322 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
323 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
324 self.report("Not removing %s" % attrname)
325 return
326 m = ldb.Message()
327 m.dn = obj.dn
328 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
329 if self.do_modify(m, ["relax:0", "show_recycled:1"],
330 "Failed to remove unknown attribute %s" % attrname):
331 self.report("Removed unknown attribute %s" % (attrname))
333 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
334 '''handle a missing backlink value'''
335 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
336 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
337 self.report("Not fixing missing backlink %s" % backlink_name)
338 return
339 m = ldb.Message()
340 m.dn = obj.dn
341 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
342 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
343 if self.do_modify(m, ["show_recycled:1"],
344 "Failed to fix missing backlink %s" % backlink_name):
345 self.report("Fixed missing backlink %s" % (backlink_name))
347 def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
348 '''handle a incorrect RMD_FLAGS value'''
349 rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
350 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()))
351 if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
352 self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
353 return
354 m = ldb.Message()
355 m.dn = obj.dn
356 m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
357 if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
358 "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
359 self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
361 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
362 '''handle a orphaned backlink value'''
363 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
364 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
365 self.report("Not removing orphaned backlink %s" % link_name)
366 return
367 m = ldb.Message()
368 m.dn = obj.dn
369 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
370 if self.do_modify(m, ["show_recycled:1", "relax:0"],
371 "Failed to fix orphaned backlink %s" % link_name):
372 self.report("Fixed orphaned backlink %s" % (link_name))
374 def err_no_fsmoRoleOwner(self, obj):
375 '''handle a missing fSMORoleOwner'''
376 self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
377 res = self.samdb.search("",
378 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
379 assert len(res) == 1
380 serviceName = res[0]["dsServiceName"][0]
381 if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
382 self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
383 return
384 m = ldb.Message()
385 m.dn = obj.dn
386 m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
387 if self.do_modify(m, [],
388 "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
389 self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
391 def err_missing_parent(self, obj):
392 '''handle a missing parent'''
393 self.report("ERROR: parent object not found for %s" % (obj.dn))
394 if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
395 self.report('Not moving object %s into LostAndFound' % (obj.dn))
396 return
398 keep_transaction = True
399 self.samdb.transaction_start()
400 try:
401 nc_root = self.samdb.get_nc_root(obj.dn);
402 lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
403 new_dn = ldb.Dn(self.samdb, str(obj.dn))
404 new_dn.remove_base_components(len(new_dn) - 1)
405 if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
406 "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
407 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
409 m = ldb.Message()
410 m.dn = obj.dn
411 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
413 if self.do_modify(m, [],
414 "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
415 self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
416 keep_transaction = True
417 except:
418 self.samdb.transaction_cancel()
419 raise
421 if keep_transaction:
422 self.samdb.transaction_commit()
423 else:
424 self.samdb.transaction_cancel()
427 def err_wrong_instancetype(self, obj, calculated_instancetype):
428 '''handle a wrong instanceType'''
429 self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
430 if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
431 self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
432 return
434 m = ldb.Message()
435 m.dn = obj.dn
436 m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
437 if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
438 "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
439 self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
441 def find_revealed_link(self, dn, attrname, guid):
442 '''return a revealed link in an object'''
443 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
444 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
445 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
446 for val in res[0][attrname]:
447 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
448 guid2 = dsdb_dn.dn.get_extended_component("GUID")
449 if guid == guid2:
450 return dsdb_dn
451 return None
453 def check_dn(self, obj, attrname, syntax_oid):
454 '''check a DN attribute for correctness'''
455 error_count = 0
456 for val in obj[attrname]:
457 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
459 # all DNs should have a GUID component
460 guid = dsdb_dn.dn.get_extended_component("GUID")
461 if guid is None:
462 error_count += 1
463 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
464 "missing GUID")
465 continue
467 guidstr = str(misc.GUID(guid))
469 attrs = ['isDeleted']
471 if (str(attrname).lower() == 'msds-hasinstantiatedncs') and (obj.dn == self.ntds_dsa):
472 fixing_msDS_HasInstantiatedNCs = True
473 attrs.append("instanceType")
474 else:
475 fixing_msDS_HasInstantiatedNCs = False
477 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
478 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
479 if reverse_link_name is not None:
480 attrs.append(reverse_link_name)
482 # check its the right GUID
483 try:
484 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
485 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
486 except ldb.LdbError, (enum, estr):
487 error_count += 1
488 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
489 continue
491 if fixing_msDS_HasInstantiatedNCs:
492 dsdb_dn.prefix = "B:8:%08X:" % int(res[0]['instanceType'][0])
493 dsdb_dn.binary = "%08X" % int(res[0]['instanceType'][0])
495 if str(dsdb_dn) != val:
496 error_count +=1
497 self.err_incorrect_binary_dn(obj.dn, attrname, val, dsdb_dn, "incorrect instanceType part of Binary DN")
498 continue
500 # now we have two cases - the source object might or might not be deleted
501 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
502 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
504 # the target DN is not allowed to be deleted, unless the target DN is the
505 # special Deleted Objects container
506 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
507 error_count += 1
508 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
509 continue
511 # check the DN matches in string form
512 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
513 error_count += 1
514 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
515 res[0].dn, "incorrect string version of DN")
516 continue
518 if is_deleted and not target_is_deleted and reverse_link_name is not None:
519 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
520 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
521 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
522 # the RMD_FLAGS for this link should be 1, as the target is deleted
523 self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
524 continue
526 # check the reverse_link is correct if there should be one
527 if reverse_link_name is not None:
528 match_count = 0
529 if reverse_link_name in res[0]:
530 for v in res[0][reverse_link_name]:
531 if v == obj.dn.extended_str():
532 match_count += 1
533 if match_count != 1:
534 error_count += 1
535 if linkID & 1:
536 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
537 else:
538 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
539 continue
541 return error_count
544 def get_originating_time(self, val, attid):
545 '''Read metadata properties and return the originating time for
546 a given attributeId.
548 :return: the originating time or 0 if not found
551 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
552 obj = repl.ctr
554 for o in repl.ctr.array:
555 if o.attid == attid:
556 return o.originating_change_time
558 return 0
560 def process_metadata(self, val):
561 '''Read metadata properties and list attributes in it'''
563 list_att = []
565 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
566 obj = repl.ctr
568 for o in repl.ctr.array:
569 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
570 list_att.append(att.lower())
572 return list_att
575 def fix_metadata(self, dn, attr):
576 '''re-write replPropertyMetaData elements for a single attribute for a
577 object. This is used to fix missing replPropertyMetaData elements'''
578 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
579 controls = ["search_options:1:2", "show_recycled:1"])
580 msg = res[0]
581 nmsg = ldb.Message()
582 nmsg.dn = dn
583 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
584 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
585 "Failed to fix metadata for attribute %s" % attr):
586 self.report("Fixed metadata for attribute %s" % attr)
588 def ace_get_effective_inherited_type(self, ace):
589 if ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY:
590 return None
592 check = False
593 if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT:
594 check = True
595 elif ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT:
596 check = True
597 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT:
598 check = True
599 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT:
600 check = True
602 if not check:
603 return None
605 if not ace.object.flags & security.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT:
606 return None
608 return str(ace.object.inherited_type)
610 def lookup_class_schemaIDGUID(self, cls):
611 if cls in self.class_schemaIDGUID:
612 return self.class_schemaIDGUID[cls]
614 flt = "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
615 res = self.samdb.search(base=self.schema_dn,
616 expression=flt,
617 attrs=["schemaIDGUID"])
618 t = str(ndr_unpack(misc.GUID, res[0]["schemaIDGUID"][0]))
620 self.class_schemaIDGUID[cls] = t
621 return t
623 def process_sd(self, dn, obj):
624 sd_attr = "nTSecurityDescriptor"
625 sd_val = obj[sd_attr]
627 sd = ndr_unpack(security.descriptor, str(sd_val))
629 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
630 if is_deleted:
631 # we don't fix deleted objects
632 return (sd, None)
634 sd_clean = security.descriptor()
635 sd_clean.owner_sid = sd.owner_sid
636 sd_clean.group_sid = sd.group_sid
637 sd_clean.type = sd.type
638 sd_clean.revision = sd.revision
640 broken = False
641 last_inherited_type = None
643 aces = []
644 if sd.sacl is not None:
645 aces = sd.sacl.aces
646 for i in range(0, len(aces)):
647 ace = aces[i]
649 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
650 sd_clean.sacl_add(ace)
651 continue
653 t = self.ace_get_effective_inherited_type(ace)
654 if t is None:
655 continue
657 if last_inherited_type is not None:
658 if t != last_inherited_type:
659 # if it inherited from more than
660 # one type it's very likely to be broken
662 # If not the recalculation will calculate
663 # the same result.
664 broken = True
665 continue
667 last_inherited_type = t
669 aces = []
670 if sd.dacl is not None:
671 aces = sd.dacl.aces
672 for i in range(0, len(aces)):
673 ace = aces[i]
675 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
676 sd_clean.dacl_add(ace)
677 continue
679 t = self.ace_get_effective_inherited_type(ace)
680 if t is None:
681 continue
683 if last_inherited_type is not None:
684 if t != last_inherited_type:
685 # if it inherited from more than
686 # one type it's very likely to be broken
688 # If not the recalculation will calculate
689 # the same result.
690 broken = True
691 continue
693 last_inherited_type = t
695 if broken:
696 return (sd_clean, sd)
698 if last_inherited_type is None:
699 # ok
700 return (sd, None)
702 cls = None
703 try:
704 cls = obj["objectClass"][-1]
705 except KeyError, e:
706 pass
708 if cls is None:
709 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
710 attrs=["isDeleted", "objectClass"],
711 controls=["show_recycled:1"])
712 o = res[0]
713 is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE'
714 if is_deleted:
715 # we don't fix deleted objects
716 return (sd, None)
717 cls = o["objectClass"][-1]
719 t = self.lookup_class_schemaIDGUID(cls)
721 if t != last_inherited_type:
722 # broken
723 return (sd_clean, sd)
725 # ok
726 return (sd, None)
728 def err_wrong_sd(self, dn, sd, sd_broken):
729 '''re-write the SD due to incorrect inherited ACEs'''
730 sd_attr = "nTSecurityDescriptor"
731 sd_val = ndr_pack(sd)
732 sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
734 if not self.confirm_all('Fix %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor'):
735 self.report('Not fixing %s on %s\n' % (sd_attr, dn))
736 return
738 nmsg = ldb.Message()
739 nmsg.dn = dn
740 nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
741 if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
742 "Failed to fix metadata for attribute %s" % sd_attr):
743 self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
745 def is_fsmo_role(self, dn):
746 if dn == self.samdb.domain_dn:
747 return True
748 if dn == self.infrastructure_dn:
749 return True
750 if dn == self.naming_dn:
751 return True
752 if dn == self.schema_dn:
753 return True
754 if dn == self.rid_dn:
755 return True
757 return False
759 def calculate_instancetype(self, dn):
760 instancetype = 0
761 nc_root = self.samdb.get_nc_root(dn)
762 if dn == nc_root:
763 instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
764 try:
765 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
766 except ldb.LdbError, (enum, estr):
767 if enum != ldb.ERR_NO_SUCH_OBJECT:
768 raise
769 else:
770 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
772 if self.write_ncs is not None and str(nc_root) in self.write_ncs:
773 instancetype |= dsdb.INSTANCE_TYPE_WRITE
775 return instancetype
777 def check_object(self, dn, attrs=['*']):
778 '''check one object'''
779 if self.verbose:
780 self.report("Checking object %s" % dn)
781 if '*' in attrs:
782 attrs.append("replPropertyMetaData")
784 try:
785 sd_flags = 0
786 sd_flags |= security.SECINFO_OWNER
787 sd_flags |= security.SECINFO_GROUP
788 sd_flags |= security.SECINFO_DACL
789 sd_flags |= security.SECINFO_SACL
791 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
792 controls=[
793 "extended_dn:1:1",
794 "show_recycled:1",
795 "show_deleted:1",
796 "sd_flags:1:%d" % sd_flags,
798 attrs=attrs)
799 except ldb.LdbError, (enum, estr):
800 if enum == ldb.ERR_NO_SUCH_OBJECT:
801 if self.in_transaction:
802 self.report("ERROR: Object %s disappeared during check" % dn)
803 return 1
804 return 0
805 raise
806 if len(res) != 1:
807 self.report("ERROR: Object %s failed to load during check" % dn)
808 return 1
809 obj = res[0]
810 error_count = 0
811 list_attrs_from_md = []
812 list_attrs_seen = []
813 got_repl_property_meta_data = False
815 for attrname in obj:
816 if attrname == 'dn':
817 continue
819 if str(attrname).lower() == 'replpropertymetadata':
820 list_attrs_from_md = self.process_metadata(obj[attrname])
821 got_repl_property_meta_data = True
822 continue
824 if str(attrname).lower() == 'ntsecuritydescriptor':
825 (sd, sd_broken) = self.process_sd(dn, obj)
826 if sd_broken is not None:
827 self.err_wrong_sd(dn, sd, sd_broken)
828 error_count += 1
829 continue
831 if str(attrname).lower() == 'objectclass':
832 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
833 if list(normalised) != list(obj[attrname]):
834 self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
835 error_count += 1
836 continue
838 # check for empty attributes
839 for val in obj[attrname]:
840 if val == '':
841 self.err_empty_attribute(dn, attrname)
842 error_count += 1
843 continue
845 # get the syntax oid for the attribute, so we can can have
846 # special handling for some specific attribute types
847 try:
848 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
849 except Exception, msg:
850 self.err_unknown_attribute(obj, attrname)
851 error_count += 1
852 continue
854 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
855 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
856 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
857 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
858 list_attrs_seen.append(str(attrname).lower())
860 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
861 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
862 # it's some form of DN, do specialised checking on those
863 error_count += self.check_dn(obj, attrname, syntax_oid)
865 # check for incorrectly normalised attributes
866 for val in obj[attrname]:
867 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
868 if len(normalised) != 1 or normalised[0] != val:
869 self.err_normalise_mismatch(dn, attrname, obj[attrname])
870 error_count += 1
871 break
873 if str(attrname).lower() == "instancetype":
874 calculated_instancetype = self.calculate_instancetype(dn)
875 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
876 self.err_wrong_instancetype(obj, calculated_instancetype)
878 show_dn = True
879 if got_repl_property_meta_data:
880 rdn = (str(dn).split(","))[0]
881 if rdn == "CN=Deleted Objects":
882 isDeletedAttId = 131120
883 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
885 expectedTimeDo = 2650466015990000000
886 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
887 if originating != expectedTimeDo:
888 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
889 nmsg = ldb.Message()
890 nmsg.dn = dn
891 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
892 error_count += 1
893 self.samdb.modify(nmsg, controls=["provision:0"])
895 else:
896 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
897 for att in list_attrs_seen:
898 if not att in list_attrs_from_md:
899 if show_dn:
900 self.report("On object %s" % dn)
901 show_dn = False
902 error_count += 1
903 self.report("ERROR: Attribute %s not present in replication metadata" % att)
904 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
905 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
906 continue
907 self.fix_metadata(dn, att)
909 if self.is_fsmo_role(dn):
910 if "fSMORoleOwner" not in obj:
911 self.err_no_fsmoRoleOwner(obj)
912 error_count += 1
914 try:
915 if dn != self.samdb.get_root_basedn():
916 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
917 controls=["show_recycled:1", "show_deleted:1"])
918 except ldb.LdbError, (enum, estr):
919 if enum == ldb.ERR_NO_SUCH_OBJECT:
920 self.err_missing_parent(obj)
921 error_count += 1
922 else:
923 raise
925 return error_count
927 ################################################################
928 # check special @ROOTDSE attributes
929 def check_rootdse(self):
930 '''check the @ROOTDSE special object'''
931 dn = ldb.Dn(self.samdb, '@ROOTDSE')
932 if self.verbose:
933 self.report("Checking object %s" % dn)
934 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
935 if len(res) != 1:
936 self.report("Object %s disappeared during check" % dn)
937 return 1
938 obj = res[0]
939 error_count = 0
941 # check that the dsServiceName is in GUID form
942 if not 'dsServiceName' in obj:
943 self.report('ERROR: dsServiceName missing in @ROOTDSE')
944 return error_count+1
946 if not obj['dsServiceName'][0].startswith('<GUID='):
947 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
948 error_count += 1
949 if not self.confirm('Change dsServiceName to GUID form?'):
950 return error_count
951 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
952 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
953 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
954 m = ldb.Message()
955 m.dn = dn
956 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
957 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
958 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
959 self.report("Changed dsServiceName to GUID form")
960 return error_count
963 ###############################################
964 # re-index the database
965 def reindex_database(self):
966 '''re-index the whole database'''
967 m = ldb.Message()
968 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
969 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
970 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
971 return self.do_modify(m, [], 're-indexed database', validate=False)
973 ###############################################
974 # reset @MODULES
975 def reset_modules(self):
976 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
977 m = ldb.Message()
978 m.dn = ldb.Dn(self.samdb, "@MODULES")
979 m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
980 return self.do_modify(m, [], 'reset @MODULES on database', validate=False)