pytest:sddl debugging: should_fail test says how it failed
[Samba.git] / python / samba / __init__.py
blobc4ddf18da604c34a25e0d0b956fcca83d2c9c564
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
4 # Based on the original in EJS:
5 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
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 """Samba 4."""
23 __docformat__ = "restructuredText"
25 import os
26 import sys
27 import time
28 import ldb
29 import samba.param
30 from samba import _glue
31 from samba._ldb import Ldb as _Ldb
34 def source_tree_topdir():
35 """Return the top level source directory."""
36 paths = ["../../..", "../../../.."]
37 for p in paths:
38 topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
39 if os.path.exists(os.path.join(topdir, 'source4')):
40 return topdir
41 raise RuntimeError("unable to find top level source directory")
44 def in_source_tree():
45 """Return True if we are running from within the samba source tree"""
46 try:
47 topdir = source_tree_topdir()
48 except RuntimeError:
49 return False
50 return True
53 class Ldb(_Ldb):
54 """Simple Samba-specific LDB subclass that takes care
55 of setting up the modules dir, credentials pointers, etc.
57 Please note that this is intended to be for all Samba LDB files,
58 not necessarily the Sam database. For Sam-specific helper
59 functions see samdb.py.
60 """
62 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
63 credentials=None, flags=0, options=None):
64 """Opens a Samba Ldb file.
66 :param url: Optional LDB URL to open
67 :param lp: Optional loadparm object
68 :param modules_dir: Optional modules directory
69 :param session_info: Optional session information
70 :param credentials: Optional credentials, defaults to anonymous.
71 :param flags: Optional LDB flags
72 :param options: Additional options (optional)
74 This is different from a regular Ldb file in that the Samba-specific
75 modules-dir is used by default and that credentials and session_info
76 can be passed through (required by some modules).
77 """
79 if modules_dir is not None:
80 self.set_modules_dir(modules_dir)
81 else:
82 self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb"))
84 if session_info is not None:
85 self.set_session_info(session_info)
87 if credentials is not None:
88 self.set_credentials(credentials)
90 if lp is not None:
91 self.set_loadparm(lp)
93 # This must be done before we load the schema, as these handlers for
94 # objectSid and objectGUID etc must take precedence over the 'binary
95 # attribute' declaration in the schema
96 self.register_samba_handlers()
98 # TODO set debug
99 def msg(l, text):
100 print(text)
101 # self.set_debug(msg)
103 self.set_utf8_casefold()
105 # Allow admins to force non-sync ldb for all databases
106 if lp is not None:
107 nosync_p = lp.get("ldb:nosync")
108 if nosync_p is not None and nosync_p:
109 flags |= ldb.FLG_NOSYNC
111 self.set_create_perms(0o600)
113 if url is not None:
114 self.connect(url, flags, options)
116 def searchone(self, attribute, basedn=None, expression=None,
117 scope=ldb.SCOPE_BASE):
118 """Search for one attribute as a string.
120 :param basedn: BaseDN for the search.
121 :param attribute: Name of the attribute
122 :param expression: Optional search expression.
123 :param scope: Search scope (defaults to base).
124 :return: Value of attribute as a string or None if it wasn't found.
126 res = self.search(basedn, scope, expression, [attribute])
127 if len(res) != 1 or res[0][attribute] is None:
128 return None
129 values = set(res[0][attribute])
130 assert len(values) == 1
131 return self.schema_format_value(attribute, values.pop())
133 def erase_users_computers(self, dn):
134 """Erases user and computer objects from our AD.
136 This is needed since the 'samldb' module denies the deletion of primary
137 groups. Therefore all groups shouldn't be primary somewhere anymore.
140 try:
141 res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
142 expression="(|(objectclass=user)(objectclass=computer))")
143 except ldb.LdbError as error:
144 (errno, estr) = error.args
145 if errno == ldb.ERR_NO_SUCH_OBJECT:
146 # Ignore no such object errors
147 return
148 else:
149 raise
151 try:
152 for msg in res:
153 self.delete(msg.dn, ["relax:0"])
154 except ldb.LdbError as error:
155 (errno, estr) = error.args
156 if errno != ldb.ERR_NO_SUCH_OBJECT:
157 # Ignore no such object errors
158 raise
160 def erase_except_schema_controlled(self):
161 """Erase this ldb.
163 :note: Removes all records, except those that are controlled by
164 Samba4's schema.
167 basedn = ""
169 # Try to delete user/computer accounts to allow deletion of groups
170 self.erase_users_computers(basedn)
172 # Delete the 'visible' records, and the invisble 'deleted' records (if
173 # this DB supports it)
174 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
175 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
176 [], controls=["show_deleted:0", "show_recycled:0"]):
177 try:
178 self.delete(msg.dn, ["relax:0"])
179 except ldb.LdbError as error:
180 (errno, estr) = error.args
181 if errno != ldb.ERR_NO_SUCH_OBJECT:
182 # Ignore no such object errors
183 raise
185 res = self.search(basedn, ldb.SCOPE_SUBTREE,
186 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
187 [], controls=["show_deleted:0", "show_recycled:0"])
188 assert len(res) == 0
190 # delete the specials
191 for attr in ["@SUBCLASSES", "@MODULES",
192 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
193 try:
194 self.delete(attr, ["relax:0"])
195 except ldb.LdbError as error:
196 (errno, estr) = error.args
197 if errno != ldb.ERR_NO_SUCH_OBJECT:
198 # Ignore missing dn errors
199 raise
201 def erase(self):
202 """Erase this ldb, removing all records."""
203 self.erase_except_schema_controlled()
205 # delete the specials
206 for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
207 try:
208 self.delete(attr, ["relax:0"])
209 except ldb.LdbError as error:
210 (errno, estr) = error.args
211 if errno != ldb.ERR_NO_SUCH_OBJECT:
212 # Ignore missing dn errors
213 raise
215 def load_ldif_file_add(self, ldif_path):
216 """Load a LDIF file.
218 :param ldif_path: Path to LDIF file.
220 with open(ldif_path, 'r') as ldif_file:
221 self.add_ldif(ldif_file.read())
223 def add_ldif(self, ldif, controls=None):
224 """Add data based on a LDIF string.
226 :param ldif: LDIF text.
228 for changetype, msg in self.parse_ldif(ldif):
229 assert changetype == ldb.CHANGETYPE_NONE
230 self.add(msg, controls)
232 def modify_ldif(self, ldif, controls=None):
233 """Modify database based on a LDIF string.
235 :param ldif: LDIF text.
237 for changetype, msg in self.parse_ldif(ldif):
238 if changetype == ldb.CHANGETYPE_NONE:
239 changetype = ldb.CHANGETYPE_MODIFY
241 if changetype == ldb.CHANGETYPE_ADD:
242 self.add(msg, controls)
243 elif changetype == ldb.CHANGETYPE_MODIFY:
244 self.modify(msg, controls)
245 elif changetype == ldb.CHANGETYPE_DELETE:
246 deldn = msg
247 self.delete(deldn, controls)
248 elif changetype == ldb.CHANGETYPE_MODRDN:
249 olddn = msg["olddn"]
250 deleteoldrdn = msg["deleteoldrdn"]
251 newdn = msg["newdn"]
252 if deleteoldrdn is False:
253 raise ValueError("Invalid ldb.CHANGETYPE_MODRDN with deleteoldrdn=False")
254 self.rename(olddn, newdn, controls)
255 else:
256 raise ValueError("Invalid ldb.CHANGETYPE_%u: %s" % (changetype, msg))
259 def substitute_var(text, values):
260 """Substitute strings of the form ${NAME} in str, replacing
261 with substitutions from values.
263 :param text: Text in which to subsitute.
264 :param values: Dictionary with keys and values.
267 for (name, value) in values.items():
268 assert isinstance(name, str), "%r is not a string" % name
269 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
270 text = text.replace("${%s}" % name, value)
272 return text
275 def check_all_substituted(text):
276 """Check that all substitution variables in a string have been replaced.
278 If not, raise an exception.
280 :param text: The text to search for substitution variables
282 if "${" not in text:
283 return
285 var_start = text.find("${")
286 var_end = text.find("}", var_start)
288 raise Exception("Not all variables substituted: %s" %
289 text[var_start:var_end + 1])
292 def read_and_sub_file(file_name, subst_vars):
293 """Read a file and sub in variables found in it
295 :param file_name: File to be read (typically from setup directory)
296 param subst_vars: Optional variables to subsitute in the file.
298 with open(file_name, 'r', encoding="utf-8") as data_file:
299 data = data_file.read()
300 if subst_vars is not None:
301 data = substitute_var(data, subst_vars)
302 check_all_substituted(data)
303 return data
306 def setup_file(template, fname, subst_vars=None):
307 """Setup a file in the private dir.
309 :param template: Path of the template file.
310 :param fname: Path of the file to create.
311 :param subst_vars: Substitution variables.
313 if os.path.exists(fname):
314 os.unlink(fname)
316 data = read_and_sub_file(template, subst_vars)
317 f = open(fname, 'w')
318 try:
319 f.write(data)
320 finally:
321 f.close()
324 MAX_NETBIOS_NAME_LEN = 15
327 def is_valid_netbios_char(c):
328 return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
331 def valid_netbios_name(name):
332 """Check whether a name is valid as a NetBIOS name. """
333 # See crh's book (1.4.1.1)
334 if len(name) > MAX_NETBIOS_NAME_LEN:
335 return False
336 for x in name:
337 if not is_valid_netbios_char(x):
338 return False
339 return True
342 def dn_from_dns_name(dnsdomain):
343 """return a DN from a DNS name domain/forest root"""
344 return "DC=" + ",DC=".join(dnsdomain.split("."))
347 def current_unix_time():
348 return int(time.time())
351 def string_to_byte_array(string):
352 return [c if isinstance(c, int) else ord(c) for c in string]
355 def arcfour_encrypt(key, data):
356 from samba.crypto import arcfour_crypt_blob
357 return arcfour_crypt_blob(data, key)
360 def enable_net_export_keytab():
361 """This function modifies the samba.net.Net class to contain
362 an export_keytab() method."""
363 # This looks very strange because it is.
365 # The dckeytab modules contains nothing, but the act of importing
366 # it pushes a method into samba.net.Net. It ended up this way
367 # because Net.export_keytab() only works on Heimdal builds, and
368 # people sometimes want to compile Samba without Heimdal while
369 # still having a working samba-tool.
371 # There is probably a better way to do this than a magic module
372 # import (yes, that's a FIXME if you can be bothered).
373 from samba import net
374 from samba import dckeytab
377 version = _glue.version
378 interface_ips = _glue.interface_ips
379 fault_setup = _glue.fault_setup
380 set_debug_level = _glue.set_debug_level
381 get_debug_level = _glue.get_debug_level
382 float2nttime = _glue.float2nttime
383 nttime2float = _glue.nttime2float
384 nttime2string = _glue.nttime2string
385 nttime2unix = _glue.nttime2unix
386 unix2nttime = _glue.unix2nttime
387 generate_random_password = _glue.generate_random_password
388 generate_random_machine_password = _glue.generate_random_machine_password
389 check_password_quality = _glue.check_password_quality
390 generate_random_bytes = _glue.generate_random_bytes
391 strcasecmp_m = _glue.strcasecmp_m
392 strstr_m = _glue.strstr_m
393 is_ntvfs_fileserver_built = _glue.is_ntvfs_fileserver_built
394 is_heimdal_built = _glue.is_heimdal_built
395 is_ad_dc_built = _glue.is_ad_dc_built
396 is_selftest_enabled = _glue.is_selftest_enabled
398 NTSTATUSError = _glue.NTSTATUSError
399 HRESULTError = _glue.HRESULTError
400 WERRORError = _glue.WERRORError
401 DsExtendedError = _glue.DsExtendedError