3 # Samba4 AD database checker
5 # Copyright (C) Andrew Tridgell 2011
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import samba, ldb, sys
22 import samba.getopt as options
23 from samba.auth import system_session
24 from samba.samdb import SamDB
25 from samba.dcerpc import security
26 from samba.netcmd import (
32 def confirm(self, msg):
33 '''confirm an action with the user'''
35 print("%s [YES]" % msg)
37 v = raw_input(msg + ' [y/N] ')
38 return v.upper() in ['Y', 'YES']
44 def check_object(self, dn):
45 '''check one object'''
47 print("Checking object %s" % dn)
48 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"], attrs=['*', 'ntSecurityDescriptor'])
50 print("Object %s disappeared during check" % dn)
58 # check for empty attributes
59 for val in obj[attrname]:
61 empty_attribute(self, dn, attrname)
65 # check for incorrectly normalised attributes
66 for val in obj[attrname]:
67 normalised = self.samdb.dsdb_normalise_attributes(self.samdb, attrname, [val])
68 if len(normalised) != 1 or normalised[0] != val:
69 normalise_mismatch(self, dn, attrname, obj[attrname])
75 class cmd_dbcheck(Command):
76 """check local AD database for errors"""
77 synopsis = "dbcheck <DN> [options]"
79 takes_optiongroups = {
80 "sambaopts": options.SambaOptions,
81 "versionopts": options.VersionOptions,
82 "credopts": options.CredentialsOptionsDouble,
88 Option("--scope", dest="scope", default="SUB",
89 help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
90 Option("--fix", dest="fix", default=False, action='store_true',
91 help='Fix any errors found'),
92 Option("--yes", dest="yes", default=False, action='store_true',
93 help="don't confirm changes, just do them all"),
94 Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
95 help="cross naming context boundaries"),
96 Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
97 help="Print more details of checking"),
100 def run(self, DN=None, verbose=False, fix=False, yes=False, cross_ncs=False,
101 scope="SUB", credopts=None, sambaopts=None, versionopts=None):
102 self.lp = sambaopts.get_loadparm()
103 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
105 self.samdb = SamDB(session_info=system_session(), url=None,
106 credentials=self.creds, lp=self.lp)
107 self.verbose = verbose
111 scope_map = { "SUB": ldb.SCOPE_SUBTREE, "BASE":ldb.SCOPE_BASE, "ONE":ldb.SCOPE_ONELEVEL }
112 scope = scope.upper()
113 if not scope in scope_map:
114 raise CommandError("Unknown scope %s" % scope)
115 self.search_scope = scope_map[scope]
119 controls.append("search_options:1:2")
121 res = self.samdb.search(base=DN, scope=self.search_scope, attrs=['dn'], controls=controls)
122 print('Checking %u objects' % len(res))
125 error_count += self.check_object(self, object.dn)
126 if error_count != 0 and not self.fix:
127 print("Please use --fix to fix these errors")
128 print('Checked %u objects (%u errors)' % (len(res), error_count))
132 def empty_attribute(self, dn, attrname):
133 '''fix empty attributes'''
134 print("ERROR: Empty attribute %s in %s" % (attrname, dn))
137 if not confirm(self, 'Remove empty attribute %s from %s?' % (attrname, dn)):
138 print("Not fixing empty attribute %s" % attrname)
143 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
145 self.samdb.modify(m, controls=["relax:0"], validate=False)
146 except Exception, msg:
147 print("Failed to remove empty attribute %s : %s" % (attrname, msg))
149 print("Removed empty attribute %s" % attrname)
152 def normalise_mismatch(self, dn, attrname, values):
153 '''fix attribute normalisation errors'''
154 print("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
157 normalised = self.samdb.dsdb_normalise_attributes(self.samdb, attrname, [val])
158 if len(normalised) != 1:
159 print("Unable to normalise value '%s'" % val)
160 mod_list.append((val, ''))
161 elif (normalised[0] != val):
162 print("value '%s' should be '%s'" % (val, normalised[0]))
163 mod_list.append((val, normalised[0]))
166 if not confirm(self, 'Fix normalisation for %s from %s?' % (attrname, dn)):
167 print("Not fixing attribute %s" % attrname)
172 for i in range(0, len(mod_list)):
173 (val, nval) = mod_list[i]
174 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
176 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
179 self.samdb.modify(m, controls=["relax:0"], validate=False)
180 except Exception, msg:
181 print("Failed to normalise attribute %s : %s" % (attrname, msg))
183 print("Normalised attribute %s" % attrname)