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/>.
23 __docformat__
= "restructuredText"
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
= ["../../..", "../../../.."]
38 topdir
= os
.path
.normpath(os
.path
.join(os
.path
.dirname(__file__
), p
))
39 if os
.path
.exists(os
.path
.join(topdir
, 'source4')):
41 raise RuntimeError("unable to find top level source directory")
45 """Return True if we are running from within the samba source tree"""
47 topdir
= source_tree_topdir()
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.
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).
79 if modules_dir
is not None:
80 self
.set_modules_dir(modules_dir
)
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
)
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()
101 # self.set_debug(msg)
103 self
.set_utf8_casefold()
105 # Allow admins to force non-sync ldb for all databases
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)
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:
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.
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
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
160 def erase_except_schema_controlled(self
):
163 :note: Removes all records, except those that are controlled by
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 invisible '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"]):
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
185 res
= self
.search(basedn
, ldb
.SCOPE_SUBTREE
,
186 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
187 [], controls
=["show_deleted:0", "show_recycled:0"])
190 # delete the specials
191 for attr
in ["@SUBCLASSES", "@MODULES",
192 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
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
202 """Erase this ldb, removing all records."""
203 self
.erase_except_schema_controlled()
205 # delete the specials
206 for attr
in ["@INDEXLIST", "@ATTRIBUTES"]:
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
215 def load_ldif_file_add(self
, ldif_path
):
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
:
247 self
.delete(deldn
, controls
)
248 elif changetype
== ldb
.CHANGETYPE_MODRDN
:
250 deleteoldrdn
= msg
["deleteoldrdn"]
252 if deleteoldrdn
is False:
253 raise ValueError("Invalid ldb.CHANGETYPE_MODRDN with deleteoldrdn=False")
254 self
.rename(olddn
, newdn
, controls
)
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 substitute.
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
)
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
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 substitute 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
)
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
):
316 data
= read_and_sub_file(template
, subst_vars
)
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
:
337 if not is_valid_netbios_char(x
):
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 arcfour_encrypt(key
, data
):
352 from samba
.crypto
import arcfour_crypt_blob
353 return arcfour_crypt_blob(data
, key
)
356 def aead_aes_256_cbc_hmac_sha512(plaintext
, cek
, key_salt
, mac_salt
, iv
):
357 from samba
.crypto
import aead_aes_256_cbc_hmac_sha512_blob
358 return aead_aes_256_cbc_hmac_sha512_blob(
367 GUID_RE
= re
.compile(
368 "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
370 GUID_MIXCASE_RE
= re
.compile(
371 "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
372 flags
= re
.IGNORECASE
)
375 def string_is_guid(string
, lower_case_only
=False):
376 """Is the string an ordinary undecorated string GUID?
378 That is, like 12345678-abcd-1234-FEED-1234567890ab, and not like
379 variants which have surrounding curly brackets or lack hyphens.
381 If lower case_only is true, only lowercase hex characters are
382 accepted. This is tighter than we ever require, but matches what
385 # Note: it is rightly tempting to use misc.GUID() here and catch
386 # the error, but misc.GUID is more forgiving than we want,
387 # allowing all kinds of weird variants.
389 m
= GUID_RE
.fullmatch(string
)
391 m
= GUID_MIXCASE_RE
.fullmatch(string
)
398 def enable_net_export_keytab():
399 """This function modifies the samba.net.Net class to contain
400 an export_keytab() method."""
401 # This looks very strange because it is.
403 # The dckeytab modules contains nothing, but the act of importing
404 # it pushes a method into samba.net.Net. It ended up this way
405 # because Net.export_keytab() only works on AD DC builds, and
406 # people sometimes want to compile Samba without the AD DC while
407 # still having a working samba-tool.
409 # There is probably a better way to do this than a magic module
410 # import (yes, that's a FIXME if you can be bothered).
411 from samba
import net
412 from samba
import dckeytab
415 version
= _glue
.version
416 interface_ips
= _glue
.interface_ips
417 fault_setup
= _glue
.fault_setup
418 set_debug_level
= _glue
.set_debug_level
419 get_debug_level
= _glue
.get_debug_level
420 float2nttime
= _glue
.float2nttime
421 nttime2float
= _glue
.nttime2float
422 nttime2string
= _glue
.nttime2string
423 nttime2unix
= _glue
.nttime2unix
424 unix2nttime
= _glue
.unix2nttime
425 generate_random_password
= _glue
.generate_random_password
426 generate_random_machine_password
= _glue
.generate_random_machine_password
427 check_password_quality
= _glue
.check_password_quality
428 generate_random_bytes
= _glue
.generate_random_bytes
429 strcasecmp_m
= _glue
.strcasecmp_m
430 strstr_m
= _glue
.strstr_m
431 is_ntvfs_fileserver_built
= _glue
.is_ntvfs_fileserver_built
432 is_heimdal_built
= _glue
.is_heimdal_built
433 is_ad_dc_built
= _glue
.is_ad_dc_built
434 is_selftest_enabled
= _glue
.is_selftest_enabled
435 is_rust_built
= _glue
.is_rust_built
437 NTSTATUSError
= _glue
.NTSTATUSError
438 HRESULTError
= _glue
.HRESULTError
439 WERRORError
= _glue
.WERRORError
440 DsExtendedError
= _glue
.DsExtendedError