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 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"]):
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 self
.add_ldif(open(ldif_path
, 'r').read())
222 def add_ldif(self
, ldif
, controls
=None):
223 """Add data based on a LDIF string.
225 :param ldif: LDIF text.
227 for changetype
, msg
in self
.parse_ldif(ldif
):
228 assert changetype
== ldb
.CHANGETYPE_NONE
229 self
.add(msg
, controls
)
231 def modify_ldif(self
, ldif
, controls
=None):
232 """Modify database based on a LDIF string.
234 :param ldif: LDIF text.
236 for changetype
, msg
in self
.parse_ldif(ldif
):
237 if changetype
== ldb
.CHANGETYPE_ADD
:
238 self
.add(msg
, controls
)
240 self
.modify(msg
, controls
)
243 def substitute_var(text
, values
):
244 """Substitute strings of the form ${NAME} in str, replacing
245 with substitutions from values.
247 :param text: Text in which to subsitute.
248 :param values: Dictionary with keys and values.
251 for (name
, value
) in values
.items():
252 assert isinstance(name
, str), "%r is not a string" % name
253 assert isinstance(value
, str), "Value %r for %s is not a string" % (value
, name
)
254 text
= text
.replace("${%s}" % name
, value
)
259 def check_all_substituted(text
):
260 """Check that all substitution variables in a string have been replaced.
262 If not, raise an exception.
264 :param text: The text to search for substitution variables
269 var_start
= text
.find("${")
270 var_end
= text
.find("}", var_start
)
272 raise Exception("Not all variables substituted: %s" %
273 text
[var_start
:var_end
+ 1])
276 def read_and_sub_file(file_name
, subst_vars
):
277 """Read a file and sub in variables found in it
279 :param file_name: File to be read (typically from setup directory)
280 param subst_vars: Optional variables to subsitute in the file.
282 data
= open(file_name
, 'r', encoding
="utf-8").read()
283 if subst_vars
is not None:
284 data
= substitute_var(data
, subst_vars
)
285 check_all_substituted(data
)
289 def setup_file(template
, fname
, subst_vars
=None):
290 """Setup a file in the private dir.
292 :param template: Path of the template file.
293 :param fname: Path of the file to create.
294 :param subst_vars: Substitution variables.
296 if os
.path
.exists(fname
):
299 data
= read_and_sub_file(template
, subst_vars
)
307 MAX_NETBIOS_NAME_LEN
= 15
310 def is_valid_netbios_char(c
):
311 return (c
.isalnum() or c
in " !#$%&'()-.@^_{}~")
314 def valid_netbios_name(name
):
315 """Check whether a name is valid as a NetBIOS name. """
316 # See crh's book (1.4.1.1)
317 if len(name
) > MAX_NETBIOS_NAME_LEN
:
320 if not is_valid_netbios_char(x
):
325 def dn_from_dns_name(dnsdomain
):
326 """return a DN from a DNS name domain/forest root"""
327 return "DC=" + ",DC=".join(dnsdomain
.split("."))
330 def current_unix_time():
331 return int(time
.time())
334 def string_to_byte_array(string
):
335 blob
= [0] * len(string
)
337 for i
in range(len(string
)):
338 blob
[i
] = string
[i
] if isinstance(string
[i
], int) else ord(string
[i
])
343 def arcfour_encrypt(key
, data
):
344 from samba
.crypto
import arcfour_crypt_blob
345 return arcfour_crypt_blob(data
, key
)
348 def enable_net_export_keytab():
349 """This function modifies the samba.net.Net class to contain
350 an export_keytab() method."""
351 # This looks very strange because it is.
353 # The dckeytab modules contains nothing, but the act of importing
354 # it pushes a method into samba.net.Net. It ended up this way
355 # because Net.export_keytab() only works on Heimdal builds, and
356 # people sometimes want to compile Samba without Heimdal while
357 # still having a working samba-tool.
359 # There is probably a better way to do this than a magic module
360 # import (yes, that's a FIXME if you can be bothered).
361 from samba
import net
362 from samba
import dckeytab
365 version
= _glue
.version
366 interface_ips
= _glue
.interface_ips
367 fault_setup
= _glue
.fault_setup
368 set_debug_level
= _glue
.set_debug_level
369 get_debug_level
= _glue
.get_debug_level
370 unix2nttime
= _glue
.unix2nttime
371 nttime2string
= _glue
.nttime2string
372 nttime2unix
= _glue
.nttime2unix
373 unix2nttime
= _glue
.unix2nttime
374 generate_random_password
= _glue
.generate_random_password
375 generate_random_machine_password
= _glue
.generate_random_machine_password
376 check_password_quality
= _glue
.check_password_quality
377 generate_random_bytes
= _glue
.generate_random_bytes
378 strcasecmp_m
= _glue
.strcasecmp_m
379 strstr_m
= _glue
.strstr_m
380 is_ntvfs_fileserver_built
= _glue
.is_ntvfs_fileserver_built
381 is_heimdal_built
= _glue
.is_heimdal_built
382 is_ad_dc_built
= _glue
.is_ad_dc_built
384 NTSTATUSError
= _glue
.NTSTATUSError
385 HRESULTError
= _glue
.HRESULTError
386 WERRORError
= _glue
.WERRORError
387 DsExtendedError
= _glue
.DsExtendedError