samdb: added get_ntds_GUID() method
[samba.git] / source4 / scripting / python / samba / __init__.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
5 #
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 """Samba 4."""
24
25 __docformat__ = "restructuredText"
26
27 import os
28
29 def _in_source_tree():
30     """Check whether the script is being run from the source dir. """
31     return os.path.exists("%s/../../../selftest/skip" % os.path.dirname(__file__))
32
33
34 # When running, in-tree, make sure bin/python is in the PYTHONPATH
35 if _in_source_tree():
36     import sys
37     srcdir = "%s/../../.." % os.path.dirname(__file__)
38     sys.path.append("%s/bin/python" % srcdir)
39     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
40 else:
41     default_ldb_modules_dir = None
42
43
44 import ldb
45 import glue
46
47 class Ldb(ldb.Ldb):
48     """Simple Samba-specific LDB subclass that takes care
49     of setting up the modules dir, credentials pointers, etc.
50
51     Please note that this is intended to be for all Samba LDB files,
52     not necessarily the Sam database. For Sam-specific helper
53     functions see samdb.py.
54     """
55     def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
56                  credentials=None, flags=0, options=None):
57         """Opens a Samba Ldb file.
58
59         :param url: Optional LDB URL to open
60         :param lp: Optional loadparm object
61         :param modules_dir: Optional modules directory
62         :param session_info: Optional session information
63         :param credentials: Optional credentials, defaults to anonymous.
64         :param flags: Optional LDB flags
65         :param options: Additional options (optional)
66
67         This is different from a regular Ldb file in that the Samba-specific
68         modules-dir is used by default and that credentials and session_info
69         can be passed through (required by some modules).
70         """
71
72         if modules_dir is not None:
73             self.set_modules_dir(modules_dir)
74         elif default_ldb_modules_dir is not None:
75             self.set_modules_dir(default_ldb_modules_dir)
76         elif lp is not None:
77             self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
78
79         if session_info is not None:
80             self.set_session_info(session_info)
81
82         if credentials is not None:
83             self.set_credentials(credentials)
84
85         if lp is not None:
86             self.set_loadparm(lp)
87
88         # This must be done before we load the schema, as these handlers for
89         # objectSid and objectGUID etc must take precedence over the 'binary
90         # attribute' declaration in the schema
91         glue.ldb_register_samba_handlers(self)
92
93         # TODO set debug
94         def msg(l,text):
95             print text
96         #self.set_debug(msg)
97
98         glue.ldb_set_utf8_casefold(self)
99
100         # Allow admins to force non-sync ldb for all databases
101         if lp is not None:
102             nosync_p = lp.get("nosync", "ldb")
103             if nosync_p is not None and nosync_p == true:
104                 flags |= FLG_NOSYNC
105
106         self.set_create_perms()
107
108         if url is not None:
109             self.connect(url, flags, options)
110
111     def set_session_info(self, session_info):
112         glue.ldb_set_session_info(self, session_info)
113
114     def set_credentials(self, credentials):
115         glue.ldb_set_credentials(self, credentials)
116
117     def set_loadparm(self, lp_ctx):
118         glue.ldb_set_loadparm(self, lp_ctx)
119
120     def set_create_perms(self, perms=0600):
121         # we usually want Samba databases to be private. If we later find we
122         # need one public, we will have to change this here
123         super(Ldb, self).set_create_perms(perms)
124
125     def searchone(self, attribute, basedn=None, expression=None,
126                   scope=ldb.SCOPE_BASE):
127         """Search for one attribute as a string.
128
129         :param basedn: BaseDN for the search.
130         :param attribute: Name of the attribute
131         :param expression: Optional search expression.
132         :param scope: Search scope (defaults to base).
133         :return: Value of attribute as a string or None if it wasn't found.
134         """
135         res = self.search(basedn, scope, expression, [attribute])
136         if len(res) != 1 or res[0][attribute] is None:
137             return None
138         values = set(res[0][attribute])
139         assert len(values) == 1
140         return self.schema_format_value(attribute, values.pop())
141
142     def erase_users_computers(self, dn):
143         """Erases user and computer objects from our AD. This is needed since the 'samldb' module denies the deletion of primary groups. Therefore all groups shouldn't be primary somewhere anymore."""
144
145         try:
146             res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
147                       expression="(|(objectclass=user)(objectclass=computer))")
148         except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
149             # Ignore no such object errors
150             return
151             pass
152
153         try:
154             for msg in res:
155                 self.delete(msg.dn)
156         except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
157             # Ignore no such object errors
158             return
159
160     def erase_except_schema_controlled(self):
161         """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
162
163         basedn = ""
164
165         # Try to delete user/computer accounts to allow deletion of groups
166         self.erase_users_computers(basedn)
167
168         # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it)
169         for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
170                                "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
171                                [], controls=["show_deleted:0"]):
172             try:
173                 self.delete(msg.dn)
174             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
175                 # Ignore no such object errors
176                 pass
177
178         res = self.search(basedn, ldb.SCOPE_SUBTREE,
179                           "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
180                           [], controls=["show_deleted:0"])
181         assert len(res) == 0
182
183         # delete the specials
184         for attr in ["@SUBCLASSES", "@MODULES",
185                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
186             try:
187                 self.delete(attr)
188             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
189                 # Ignore missing dn errors
190                 pass
191
192     def erase(self):
193         """Erase this ldb, removing all records."""
194
195         self.erase_except_schema_controlled()
196
197         # delete the specials
198         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
199             try:
200                 self.delete(attr)
201             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
202                 # Ignore missing dn errors
203                 pass
204
205     def erase_partitions(self):
206         """Erase an ldb, removing all records."""
207
208         def erase_recursive(self, dn):
209             try:
210                 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[],
211                                   controls=["show_deleted:0"])
212             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
213                 # Ignore no such object errors
214                 return
215
216             for msg in res:
217                 erase_recursive(self, msg.dn)
218
219             try:
220                 self.delete(dn)
221             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
222                 # Ignore no such object errors
223                 pass
224
225         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
226                          ["namingContexts"])
227         assert len(res) == 1
228         if not "namingContexts" in res[0]:
229             return
230         for basedn in res[0]["namingContexts"]:
231             # Try to delete user/computer accounts to allow deletion of groups
232             self.erase_users_computers(basedn)
233             # Try and erase from the bottom-up in the tree
234             erase_recursive(self, basedn)
235
236     def load_ldif_file_add(self, ldif_path):
237         """Load a LDIF file.
238
239         :param ldif_path: Path to LDIF file.
240         """
241         self.add_ldif(open(ldif_path, 'r').read())
242
243     def add_ldif(self, ldif, controls=None):
244         """Add data based on a LDIF string.
245
246         :param ldif: LDIF text.
247         """
248         for changetype, msg in self.parse_ldif(ldif):
249             assert changetype == ldb.CHANGETYPE_NONE
250             self.add(msg,controls)
251
252     def modify_ldif(self, ldif, controls=None):
253         """Modify database based on a LDIF string.
254
255         :param ldif: LDIF text.
256         """
257         for changetype, msg in self.parse_ldif(ldif):
258             if (changetype == ldb.CHANGETYPE_ADD):
259                 self.add(msg, controls)
260             else:
261                 self.modify(msg, controls)
262
263     def set_domain_sid(self, sid):
264         """Change the domain SID used by this LDB.
265
266         :param sid: The new domain sid to use.
267         """
268         glue.samdb_set_domain_sid(self, sid)
269
270     def domain_sid(self):
271         """Read the domain SID used by this LDB.
272
273         """
274         glue.samdb_get_domain_sid(self)
275
276     def set_schema_from_ldif(self, pf, df):
277         glue.dsdb_set_schema_from_ldif(self, pf, df)
278
279     def set_schema_from_ldb(self, ldb):
280         glue.dsdb_set_schema_from_ldb(self, ldb)
281
282     def write_prefixes_from_schema(self):
283         glue.dsdb_write_prefixes_from_schema_to_ldb(self)
284
285     def convert_schema_to_openldap(self, target, mapping):
286         return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
287
288     def set_invocation_id(self, invocation_id):
289         """Set the invocation id for this SamDB handle.
290
291         :param invocation_id: GUID of the invocation id.
292         """
293         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
294
295     def get_invocation_id(self):
296         "Get the invocation_id id"
297         return glue.samdb_ntds_invocation_id(self)
298
299     def get_ntds_GUID(self):
300         "Get the NTDS objectGUID"
301         return glue.samdb_ntds_objectGUID(self)
302
303     def server_site_name(self):
304         "Get the server site name"
305         return glue.samdb_server_site_name(self)
306
307     def set_opaque_integer(self, name, value):
308         """Set an integer as an opaque (a flag or other value) value on the database
309
310         :param name: The name for the opaque value
311         :param value: The integer value
312         """
313         glue.dsdb_set_opaque_integer(self, name, value)
314
315
316 def substitute_var(text, values):
317     """substitute strings of the form ${NAME} in str, replacing
318     with substitutions from subobj.
319
320     :param text: Text in which to subsitute.
321     :param values: Dictionary with keys and values.
322     """
323
324     for (name, value) in values.items():
325         assert isinstance(name, str), "%r is not a string" % name
326         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
327         text = text.replace("${%s}" % name, value)
328
329     return text
330
331
332 def check_all_substituted(text):
333     """Make sure that all substitution variables in a string have been replaced.
334     If not, raise an exception.
335
336     :param text: The text to search for substitution variables
337     """
338     if not "${" in text:
339         return
340
341     var_start = text.find("${")
342     var_end = text.find("}", var_start)
343
344     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
345
346
347 def read_and_sub_file(file, subst_vars):
348     """Read a file and sub in variables found in it
349
350     :param file: File to be read (typically from setup directory)
351      param subst_vars: Optional variables to subsitute in the file.
352     """
353     data = open(file, 'r').read()
354     if subst_vars is not None:
355         data = substitute_var(data, subst_vars)
356     check_all_substituted(data)
357     return data
358
359
360 def setup_file(template, fname, subst_vars=None):
361     """Setup a file in the private dir.
362
363     :param template: Path of the template file.
364     :param fname: Path of the file to create.
365     :param subst_vars: Substitution variables.
366     """
367     f = fname
368
369     if os.path.exists(f):
370         os.unlink(f)
371
372     data = read_and_sub_file(template, subst_vars)
373     open(f, 'w').write(data)
374
375
376 def valid_netbios_name(name):
377     """Check whether a name is valid as a NetBIOS name. """
378     # See crh's book (1.4.1.1)
379     if len(name) > 15:
380         return False
381     for x in name:
382         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
383             return False
384     return True
385
386
387 version = glue.version
388
389 # "userAccountControl" flags
390 UF_NORMAL_ACCOUNT = glue.UF_NORMAL_ACCOUNT
391 UF_TEMP_DUPLICATE_ACCOUNT = glue.UF_TEMP_DUPLICATE_ACCOUNT
392 UF_SERVER_TRUST_ACCOUNT = glue.UF_SERVER_TRUST_ACCOUNT
393 UF_WORKSTATION_TRUST_ACCOUNT = glue.UF_WORKSTATION_TRUST_ACCOUNT
394 UF_INTERDOMAIN_TRUST_ACCOUNT = glue.UF_INTERDOMAIN_TRUST_ACCOUNT
395 UF_PASSWD_NOTREQD = glue.UF_PASSWD_NOTREQD
396 UF_ACCOUNTDISABLE = glue.UF_ACCOUNTDISABLE
397
398 # "groupType" flags
399 GTYPE_SECURITY_BUILTIN_LOCAL_GROUP = glue.GTYPE_SECURITY_BUILTIN_LOCAL_GROUP
400 GTYPE_SECURITY_GLOBAL_GROUP = glue.GTYPE_SECURITY_GLOBAL_GROUP
401 GTYPE_SECURITY_DOMAIN_LOCAL_GROUP = glue.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP
402 GTYPE_SECURITY_UNIVERSAL_GROUP = glue.GTYPE_SECURITY_UNIVERSAL_GROUP
403 GTYPE_DISTRIBUTION_GLOBAL_GROUP = glue.GTYPE_DISTRIBUTION_GLOBAL_GROUP
404 GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP = glue.GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP
405 GTYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.GTYPE_DISTRIBUTION_UNIVERSAL_GROUP
406
407 # "sAMAccountType" flags
408 ATYPE_NORMAL_ACCOUNT = glue.ATYPE_NORMAL_ACCOUNT
409 ATYPE_WORKSTATION_TRUST = glue.ATYPE_WORKSTATION_TRUST
410 ATYPE_INTERDOMAIN_TRUST = glue.ATYPE_INTERDOMAIN_TRUST
411 ATYPE_SECURITY_GLOBAL_GROUP = glue.ATYPE_SECURITY_GLOBAL_GROUP
412 ATYPE_SECURITY_LOCAL_GROUP = glue.ATYPE_SECURITY_LOCAL_GROUP
413 ATYPE_SECURITY_UNIVERSAL_GROUP = glue.ATYPE_SECURITY_UNIVERSAL_GROUP
414 ATYPE_DISTRIBUTION_GLOBAL_GROUP = glue.ATYPE_DISTRIBUTION_GLOBAL_GROUP
415 ATYPE_DISTRIBUTION_LOCAL_GROUP = glue.ATYPE_DISTRIBUTION_LOCAL_GROUP
416 ATYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.ATYPE_DISTRIBUTION_UNIVERSAL_GROUP
417
418 # "domainFunctionality", "forestFunctionality" flags in the rootDSE */
419 DS_DOMAIN_FUNCTION_2000 = glue.DS_DOMAIN_FUNCTION_2000
420 DS_DOMAIN_FUNCTION_2003_MIXED = glue.DS_DOMAIN_FUNCTION_2003_MIXED
421 DS_DOMAIN_FUNCTION_2003 = glue.DS_DOMAIN_FUNCTION_2003
422 DS_DOMAIN_FUNCTION_2008 = glue.DS_DOMAIN_FUNCTION_2008
423 DS_DOMAIN_FUNCTION_2008_R2 = glue.DS_DOMAIN_FUNCTION_2008_R2
424
425 # "domainControllerFunctionality" flags in the rootDSE */
426 DS_DC_FUNCTION_2000 = glue.DS_DC_FUNCTION_2000
427 DS_DC_FUNCTION_2003 = glue.DS_DC_FUNCTION_2003
428 DS_DC_FUNCTION_2008 = glue.DS_DC_FUNCTION_2008
429 DS_DC_FUNCTION_2008_R2 = glue.DS_DC_FUNCTION_2008_R2
430
431 #LDAP_SERVER_SD_FLAGS_OID flags
432 SECINFO_OWNER = glue.SECINFO_OWNER
433 SECINFO_GROUP = glue.SECINFO_GROUP
434 SECINFO_DACL  = glue.SECINFO_DACL
435 SECINFO_SACL  = glue.SECINFO_SACL
436