s4:gensec/gssapi: use gensec_gssapi_max_{input,wrapped}_size() for all backends
[Samba.git] / python / samba / samdb.py
blobe3a6292bb4a41d0a4ad2bdbe372f65db2a6709cc
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
3 # Copyright (C) Matthias Dieter Wallnoefer 2009
5 # Based on the original in EJS:
6 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
7 # Copyright (C) Giampaolo Lauria <lauria2@yahoo.com> 2011
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.
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.
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/>.
23 """Convenience functions for using the SAM."""
25 import samba
26 import ldb
27 import time
28 import base64
29 import os
30 from samba import dsdb
31 from samba.ndr import ndr_unpack, ndr_pack
32 from samba.dcerpc import drsblobs, misc
33 from samba.common import normalise_int32
35 __docformat__ = "restructuredText"
38 class SamDB(samba.Ldb):
39 """The SAM database."""
41 hash_oid_name = {}
43 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
44 credentials=None, flags=0, options=None, global_schema=True,
45 auto_connect=True, am_rodc=None):
46 self.lp = lp
47 if not auto_connect:
48 url = None
49 elif url is None and lp is not None:
50 url = lp.samdb_url()
52 self.url = url
54 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
55 session_info=session_info, credentials=credentials, flags=flags,
56 options=options)
58 if global_schema:
59 dsdb._dsdb_set_global_schema(self)
61 if am_rodc is not None:
62 dsdb._dsdb_set_am_rodc(self, am_rodc)
64 def connect(self, url=None, flags=0, options=None):
65 '''connect to the database'''
66 if self.lp is not None and not os.path.exists(url):
67 url = self.lp.private_path(url)
68 self.url = url
70 super(SamDB, self).connect(url=url, flags=flags,
71 options=options)
73 def am_rodc(self):
74 '''return True if we are an RODC'''
75 return dsdb._am_rodc(self)
77 def am_pdc(self):
78 '''return True if we are an PDC emulator'''
79 return dsdb._am_pdc(self)
81 def domain_dn(self):
82 '''return the domain DN'''
83 return str(self.get_default_basedn())
85 def disable_account(self, search_filter):
86 """Disables an account
88 :param search_filter: LDAP filter to find the user (eg
89 samccountname=name)
90 """
92 flags = samba.dsdb.UF_ACCOUNTDISABLE
93 self.toggle_userAccountFlags(search_filter, flags, on=True)
95 def enable_account(self, search_filter):
96 """Enables an account
98 :param search_filter: LDAP filter to find the user (eg
99 samccountname=name)
102 flags = samba.dsdb.UF_ACCOUNTDISABLE | samba.dsdb.UF_PASSWD_NOTREQD
103 self.toggle_userAccountFlags(search_filter, flags, on=False)
105 def toggle_userAccountFlags(self, search_filter, flags, flags_str=None,
106 on=True, strict=False):
107 """Toggle_userAccountFlags
109 :param search_filter: LDAP filter to find the user (eg
110 samccountname=name)
111 :param flags: samba.dsdb.UF_* flags
112 :param on: on=True (default) => set, on=False => unset
113 :param strict: strict=False (default) ignore if no action is needed
114 strict=True raises an Exception if...
116 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
117 expression=search_filter, attrs=["userAccountControl"])
118 if len(res) == 0:
119 raise Exception("Unable to find account where '%s'" % search_filter)
120 assert(len(res) == 1)
121 account_dn = res[0].dn
123 old_uac = int(res[0]["userAccountControl"][0])
124 if on:
125 if strict and (old_uac & flags):
126 error = "Account flag(s) '%s' already set" % flags_str
127 raise Exception(error)
129 new_uac = old_uac | flags
130 else:
131 if strict and not (old_uac & flags):
132 error = "Account flag(s) '%s' already unset" % flags_str
133 raise Exception(error)
135 new_uac = old_uac & ~flags
137 if old_uac == new_uac:
138 return
140 mod = """
141 dn: %s
142 changetype: modify
143 delete: userAccountControl
144 userAccountControl: %u
145 add: userAccountControl
146 userAccountControl: %u
147 """ % (account_dn, old_uac, new_uac)
148 self.modify_ldif(mod)
150 def force_password_change_at_next_login(self, search_filter):
151 """Forces a password change at next login
153 :param search_filter: LDAP filter to find the user (eg
154 samccountname=name)
156 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
157 expression=search_filter, attrs=[])
158 if len(res) == 0:
159 raise Exception('Unable to find user "%s"' % search_filter)
160 assert(len(res) == 1)
161 user_dn = res[0].dn
163 mod = """
164 dn: %s
165 changetype: modify
166 replace: pwdLastSet
167 pwdLastSet: 0
168 """ % (user_dn)
169 self.modify_ldif(mod)
171 def newgroup(self, groupname, groupou=None, grouptype=None,
172 description=None, mailaddress=None, notes=None, sd=None,
173 gidnumber=None, nisdomain=None):
174 """Adds a new group with additional parameters
176 :param groupname: Name of the new group
177 :param grouptype: Type of the new group
178 :param description: Description of the new group
179 :param mailaddress: Email address of the new group
180 :param notes: Notes of the new group
181 :param gidnumber: GID Number of the new group
182 :param nisdomain: NIS Domain Name of the new group
183 :param sd: security descriptor of the object
186 group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
188 # The new user record. Note the reliance on the SAMLDB module which
189 # fills in the default informations
190 ldbmessage = {"dn": group_dn,
191 "sAMAccountName": groupname,
192 "objectClass": "group"}
194 if grouptype is not None:
195 ldbmessage["groupType"] = normalise_int32(grouptype)
197 if description is not None:
198 ldbmessage["description"] = description
200 if mailaddress is not None:
201 ldbmessage["mail"] = mailaddress
203 if notes is not None:
204 ldbmessage["info"] = notes
206 if gidnumber is not None:
207 ldbmessage["gidNumber"] = normalise_int32(gidnumber)
209 if nisdomain is not None:
210 ldbmessage["msSFU30Name"] = groupname
211 ldbmessage["msSFU30NisDomain"] = nisdomain
213 if sd is not None:
214 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
216 self.add(ldbmessage)
218 def deletegroup(self, groupname):
219 """Deletes a group
221 :param groupname: Name of the target group
224 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(groupname), "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
225 self.transaction_start()
226 try:
227 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
228 expression=groupfilter, attrs=[])
229 if len(targetgroup) == 0:
230 raise Exception('Unable to find group "%s"' % groupname)
231 assert(len(targetgroup) == 1)
232 self.delete(targetgroup[0].dn)
233 except:
234 self.transaction_cancel()
235 raise
236 else:
237 self.transaction_commit()
239 def add_remove_group_members(self, groupname, members,
240 add_members_operation=True):
241 """Adds or removes group members
243 :param groupname: Name of the target group
244 :param members: list of group members
245 :param add_members_operation: Defines if its an add or remove
246 operation
249 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (
250 ldb.binary_encode(groupname), "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
252 self.transaction_start()
253 try:
254 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
255 expression=groupfilter, attrs=['member'])
256 if len(targetgroup) == 0:
257 raise Exception('Unable to find group "%s"' % groupname)
258 assert(len(targetgroup) == 1)
260 modified = False
262 addtargettogroup = """
263 dn: %s
264 changetype: modify
265 """ % (str(targetgroup[0].dn))
267 for member in members:
268 targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
269 expression="(|(sAMAccountName=%s)(CN=%s))" % (
270 ldb.binary_encode(member), ldb.binary_encode(member)), attrs=[])
272 if len(targetmember) != 1:
273 raise Exception('Unable to find "%s". Operation cancelled.' % member)
275 if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']):
276 modified = True
277 addtargettogroup += """add: member
278 member: %s
279 """ % (str(targetmember[0].dn))
281 elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']):
282 modified = True
283 addtargettogroup += """delete: member
284 member: %s
285 """ % (str(targetmember[0].dn))
287 if modified is True:
288 self.modify_ldif(addtargettogroup)
290 except:
291 self.transaction_cancel()
292 raise
293 else:
294 self.transaction_commit()
296 def newuser(self, username, password,
297 force_password_change_at_next_login_req=False,
298 useusernameascn=False, userou=None, surname=None, givenname=None,
299 initials=None, profilepath=None, scriptpath=None, homedrive=None,
300 homedirectory=None, jobtitle=None, department=None, company=None,
301 description=None, mailaddress=None, internetaddress=None,
302 telephonenumber=None, physicaldeliveryoffice=None, sd=None,
303 setpassword=True, uidnumber=None, gidnumber=None, gecos=None,
304 loginshell=None, uid=None, nisdomain=None, unixhome=None):
305 """Adds a new user with additional parameters
307 :param username: Name of the new user
308 :param password: Password for the new user
309 :param force_password_change_at_next_login_req: Force password change
310 :param useusernameascn: Use username as cn rather that firstname +
311 initials + lastname
312 :param userou: Object container (without domainDN postfix) for new user
313 :param surname: Surname of the new user
314 :param givenname: First name of the new user
315 :param initials: Initials of the new user
316 :param profilepath: Profile path of the new user
317 :param scriptpath: Logon script path of the new user
318 :param homedrive: Home drive of the new user
319 :param homedirectory: Home directory of the new user
320 :param jobtitle: Job title of the new user
321 :param department: Department of the new user
322 :param company: Company of the new user
323 :param description: of the new user
324 :param mailaddress: Email address of the new user
325 :param internetaddress: Home page of the new user
326 :param telephonenumber: Phone number of the new user
327 :param physicaldeliveryoffice: Office location of the new user
328 :param sd: security descriptor of the object
329 :param setpassword: optionally disable password reset
330 :param uidnumber: RFC2307 Unix numeric UID of the new user
331 :param gidnumber: RFC2307 Unix primary GID of the new user
332 :param gecos: RFC2307 Unix GECOS field of the new user
333 :param loginshell: RFC2307 Unix login shell of the new user
334 :param uid: RFC2307 Unix username of the new user
335 :param nisdomain: RFC2307 Unix NIS domain of the new user
336 :param unixhome: RFC2307 Unix home directory of the new user
339 displayname = ""
340 if givenname is not None:
341 displayname += givenname
343 if initials is not None:
344 displayname += ' %s.' % initials
346 if surname is not None:
347 displayname += ' %s' % surname
349 cn = username
350 if useusernameascn is None and displayname is not "":
351 cn = displayname
353 user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
355 dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "")
356 user_principal_name = "%s@%s" % (username, dnsdomain)
357 # The new user record. Note the reliance on the SAMLDB module which
358 # fills in the default informations
359 ldbmessage = {"dn": user_dn,
360 "sAMAccountName": username,
361 "userPrincipalName": user_principal_name,
362 "objectClass": "user"}
364 if surname is not None:
365 ldbmessage["sn"] = surname
367 if givenname is not None:
368 ldbmessage["givenName"] = givenname
370 if displayname is not "":
371 ldbmessage["displayName"] = displayname
372 ldbmessage["name"] = displayname
374 if initials is not None:
375 ldbmessage["initials"] = '%s.' % initials
377 if profilepath is not None:
378 ldbmessage["profilePath"] = profilepath
380 if scriptpath is not None:
381 ldbmessage["scriptPath"] = scriptpath
383 if homedrive is not None:
384 ldbmessage["homeDrive"] = homedrive
386 if homedirectory is not None:
387 ldbmessage["homeDirectory"] = homedirectory
389 if jobtitle is not None:
390 ldbmessage["title"] = jobtitle
392 if department is not None:
393 ldbmessage["department"] = department
395 if company is not None:
396 ldbmessage["company"] = company
398 if description is not None:
399 ldbmessage["description"] = description
401 if mailaddress is not None:
402 ldbmessage["mail"] = mailaddress
404 if internetaddress is not None:
405 ldbmessage["wWWHomePage"] = internetaddress
407 if telephonenumber is not None:
408 ldbmessage["telephoneNumber"] = telephonenumber
410 if physicaldeliveryoffice is not None:
411 ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
413 if sd is not None:
414 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
416 ldbmessage2 = None
417 if any(map(lambda b: b is not None, (uid, uidnumber, gidnumber, gecos,
418 loginshell, nisdomain, unixhome))):
419 ldbmessage2 = ldb.Message()
420 ldbmessage2.dn = ldb.Dn(self, user_dn)
421 ldbmessage2["objectClass"] = ldb.MessageElement('posixAccount', ldb.FLAG_MOD_ADD, 'objectClass')
422 if uid is not None:
423 ldbmessage2["uid"] = ldb.MessageElement(str(uid), ldb.FLAG_MOD_REPLACE, 'uid')
424 if uidnumber is not None:
425 ldbmessage2["uidNumber"] = ldb.MessageElement(str(uidnumber), ldb.FLAG_MOD_REPLACE, 'uidNumber')
426 if gidnumber is not None:
427 ldbmessage2["gidNumber"] = ldb.MessageElement(str(gidnumber), ldb.FLAG_MOD_REPLACE, 'gidNumber')
428 if gecos is not None:
429 ldbmessage2["gecos"] = ldb.MessageElement(str(gecos), ldb.FLAG_MOD_REPLACE, 'gecos')
430 if loginshell is not None:
431 ldbmessage2["loginShell"] = ldb.MessageElement(str(loginshell), ldb.FLAG_MOD_REPLACE, 'loginShell')
432 if unixhome is not None:
433 ldbmessage2["unixHomeDirectory"] = ldb.MessageElement(
434 str(unixhome), ldb.FLAG_MOD_REPLACE, 'unixHomeDirectory')
435 if nisdomain is not None:
436 ldbmessage2["msSFU30NisDomain"] = ldb.MessageElement(
437 str(nisdomain), ldb.FLAG_MOD_REPLACE, 'msSFU30NisDomain')
438 ldbmessage2["msSFU30Name"] = ldb.MessageElement(
439 str(username), ldb.FLAG_MOD_REPLACE, 'msSFU30Name')
440 ldbmessage2["unixUserPassword"] = ldb.MessageElement(
441 'ABCD!efgh12345$67890', ldb.FLAG_MOD_REPLACE,
442 'unixUserPassword')
444 self.transaction_start()
445 try:
446 self.add(ldbmessage)
447 if ldbmessage2:
448 self.modify(ldbmessage2)
450 # Sets the password for it
451 if setpassword:
452 self.setpassword("(samAccountName=%s)" % ldb.binary_encode(username), password,
453 force_password_change_at_next_login_req)
454 except:
455 self.transaction_cancel()
456 raise
457 else:
458 self.transaction_commit()
461 def deleteuser(self, username):
462 """Deletes a user
464 :param username: Name of the target user
467 filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(username), "CN=Person,CN=Schema,CN=Configuration", self.domain_dn())
468 self.transaction_start()
469 try:
470 target = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
471 expression=filter, attrs=[])
472 if len(target) == 0:
473 raise Exception('Unable to find user "%s"' % username)
474 assert(len(target) == 1)
475 self.delete(target[0].dn)
476 except:
477 self.transaction_cancel()
478 raise
479 else:
480 self.transaction_commit()
482 def setpassword(self, search_filter, password,
483 force_change_at_next_login=False, username=None):
484 """Sets the password for a user
486 :param search_filter: LDAP filter to find the user (eg
487 samccountname=name)
488 :param password: Password for the user
489 :param force_change_at_next_login: Force password change
491 self.transaction_start()
492 try:
493 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
494 expression=search_filter, attrs=[])
495 if len(res) == 0:
496 raise Exception('Unable to find user "%s"' % (username or search_filter))
497 if len(res) > 1:
498 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
499 user_dn = res[0].dn
500 pw = unicode('"' + password + '"', 'utf-8').encode('utf-16-le')
501 setpw = """
502 dn: %s
503 changetype: modify
504 replace: unicodePwd
505 unicodePwd:: %s
506 """ % (user_dn, base64.b64encode(pw))
508 self.modify_ldif(setpw)
510 if force_change_at_next_login:
511 self.force_password_change_at_next_login(
512 "(distinguishedName=" + str(user_dn) + ")")
514 # modify the userAccountControl to remove the disabled bit
515 self.enable_account(search_filter)
516 except:
517 self.transaction_cancel()
518 raise
519 else:
520 self.transaction_commit()
522 def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False):
523 """Sets the account expiry for a user
525 :param search_filter: LDAP filter to find the user (eg
526 samaccountname=name)
527 :param expiry_seconds: expiry time from now in seconds
528 :param no_expiry_req: if set, then don't expire password
530 self.transaction_start()
531 try:
532 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
533 expression=search_filter,
534 attrs=["userAccountControl", "accountExpires"])
535 if len(res) == 0:
536 raise Exception('Unable to find user "%s"' % search_filter)
537 assert(len(res) == 1)
538 user_dn = res[0].dn
540 userAccountControl = int(res[0]["userAccountControl"][0])
541 accountExpires = int(res[0]["accountExpires"][0])
542 if no_expiry_req:
543 userAccountControl = userAccountControl | 0x10000
544 accountExpires = 0
545 else:
546 userAccountControl = userAccountControl & ~0x10000
547 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
549 setexp = """
550 dn: %s
551 changetype: modify
552 replace: userAccountControl
553 userAccountControl: %u
554 replace: accountExpires
555 accountExpires: %u
556 """ % (user_dn, userAccountControl, accountExpires)
558 self.modify_ldif(setexp)
559 except:
560 self.transaction_cancel()
561 raise
562 else:
563 self.transaction_commit()
565 def set_domain_sid(self, sid):
566 """Change the domain SID used by this LDB.
568 :param sid: The new domain sid to use.
570 dsdb._samdb_set_domain_sid(self, sid)
572 def get_domain_sid(self):
573 """Read the domain SID used by this LDB. """
574 return dsdb._samdb_get_domain_sid(self)
576 domain_sid = property(get_domain_sid, set_domain_sid,
577 "SID for the domain")
579 def set_invocation_id(self, invocation_id):
580 """Set the invocation id for this SamDB handle.
582 :param invocation_id: GUID of the invocation id.
584 dsdb._dsdb_set_ntds_invocation_id(self, invocation_id)
586 def get_invocation_id(self):
587 """Get the invocation_id id"""
588 return dsdb._samdb_ntds_invocation_id(self)
590 invocation_id = property(get_invocation_id, set_invocation_id,
591 "Invocation ID GUID")
593 def get_oid_from_attid(self, attid):
594 return dsdb._dsdb_get_oid_from_attid(self, attid)
596 def get_attid_from_lDAPDisplayName(self, ldap_display_name,
597 is_schema_nc=False):
598 '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
599 return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
600 ldap_display_name, is_schema_nc)
602 def get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name):
603 '''return the syntax OID for a LDAP attribute as a string'''
604 return dsdb._dsdb_get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name)
606 def get_systemFlags_from_lDAPDisplayName(self, ldap_display_name):
607 '''return the systemFlags for a LDAP attribute as a integer'''
608 return dsdb._dsdb_get_systemFlags_from_lDAPDisplayName(self, ldap_display_name)
610 def get_linkId_from_lDAPDisplayName(self, ldap_display_name):
611 '''return the linkID for a LDAP attribute as a integer'''
612 return dsdb._dsdb_get_linkId_from_lDAPDisplayName(self, ldap_display_name)
614 def get_lDAPDisplayName_by_attid(self, attid):
615 '''return the lDAPDisplayName from an integer DRS attribute ID'''
616 return dsdb._dsdb_get_lDAPDisplayName_by_attid(self, attid)
618 def get_backlink_from_lDAPDisplayName(self, ldap_display_name):
619 '''return the attribute name of the corresponding backlink from the name
620 of a forward link attribute. If there is no backlink return None'''
621 return dsdb._dsdb_get_backlink_from_lDAPDisplayName(self, ldap_display_name)
623 def set_ntds_settings_dn(self, ntds_settings_dn):
624 """Set the NTDS Settings DN, as would be returned on the dsServiceName
625 rootDSE attribute.
627 This allows the DN to be set before the database fully exists
629 :param ntds_settings_dn: The new DN to use
631 dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn)
633 def get_ntds_GUID(self):
634 """Get the NTDS objectGUID"""
635 return dsdb._samdb_ntds_objectGUID(self)
637 def server_site_name(self):
638 """Get the server site name"""
639 return dsdb._samdb_server_site_name(self)
641 def host_dns_name(self):
642 """return the DNS name of this host"""
643 res = self.search(base='', scope=ldb.SCOPE_BASE, attrs=['dNSHostName'])
644 return res[0]['dNSHostName'][0]
646 def domain_dns_name(self):
647 """return the DNS name of the domain root"""
648 domain_dn = self.get_default_basedn()
649 return domain_dn.canonical_str().split('/')[0]
651 def forest_dns_name(self):
652 """return the DNS name of the forest root"""
653 forest_dn = self.get_root_basedn()
654 return forest_dn.canonical_str().split('/')[0]
656 def load_partition_usn(self, base_dn):
657 return dsdb._dsdb_load_partition_usn(self, base_dn)
659 def set_schema(self, schema, write_indices_and_attributes=True):
660 self.set_schema_from_ldb(schema.ldb, write_indices_and_attributes=write_indices_and_attributes)
662 def set_schema_from_ldb(self, ldb_conn, write_indices_and_attributes=True):
663 dsdb._dsdb_set_schema_from_ldb(self, ldb_conn, write_indices_and_attributes)
665 def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements):
666 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
667 return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements)
669 def dsdb_normalise_attributes(self, ldb, ldap_display_name, ldif_elements):
670 '''normalise a list of attribute values'''
671 return dsdb._dsdb_normalise_attributes(ldb, ldap_display_name, ldif_elements)
673 def get_attribute_from_attid(self, attid):
674 """ Get from an attid the associated attribute
676 :param attid: The attribute id for searched attribute
677 :return: The name of the attribute associated with this id
679 if len(self.hash_oid_name.keys()) == 0:
680 self._populate_oid_attid()
681 if self.hash_oid_name.has_key(self.get_oid_from_attid(attid)):
682 return self.hash_oid_name[self.get_oid_from_attid(attid)]
683 else:
684 return None
686 def _populate_oid_attid(self):
687 """Populate the hash hash_oid_name.
689 This hash contains the oid of the attribute as a key and
690 its display name as a value
692 self.hash_oid_name = {}
693 res = self.search(expression="objectClass=attributeSchema",
694 controls=["search_options:1:2"],
695 attrs=["attributeID",
696 "lDAPDisplayName"])
697 if len(res) > 0:
698 for e in res:
699 strDisplay = str(e.get("lDAPDisplayName"))
700 self.hash_oid_name[str(e.get("attributeID"))] = strDisplay
702 def get_attribute_replmetadata_version(self, dn, att):
703 """Get the version field trom the replPropertyMetaData for
704 the given field
706 :param dn: The on which we want to get the version
707 :param att: The name of the attribute
708 :return: The value of the version field in the replPropertyMetaData
709 for the given attribute. None if the attribute is not replicated
712 res = self.search(expression="distinguishedName=%s" % dn,
713 scope=ldb.SCOPE_SUBTREE,
714 controls=["search_options:1:2"],
715 attrs=["replPropertyMetaData"])
716 if len(res) == 0:
717 return None
719 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
720 str(res[0]["replPropertyMetaData"]))
721 ctr = repl.ctr
722 if len(self.hash_oid_name.keys()) == 0:
723 self._populate_oid_attid()
724 for o in ctr.array:
725 # Search for Description
726 att_oid = self.get_oid_from_attid(o.attid)
727 if self.hash_oid_name.has_key(att_oid) and\
728 att.lower() == self.hash_oid_name[att_oid].lower():
729 return o.version
730 return None
732 def set_attribute_replmetadata_version(self, dn, att, value,
733 addifnotexist=False):
734 res = self.search(expression="distinguishedName=%s" % dn,
735 scope=ldb.SCOPE_SUBTREE,
736 controls=["search_options:1:2"],
737 attrs=["replPropertyMetaData"])
738 if len(res) == 0:
739 return None
741 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
742 str(res[0]["replPropertyMetaData"]))
743 ctr = repl.ctr
744 now = samba.unix2nttime(int(time.time()))
745 found = False
746 if len(self.hash_oid_name.keys()) == 0:
747 self._populate_oid_attid()
748 for o in ctr.array:
749 # Search for Description
750 att_oid = self.get_oid_from_attid(o.attid)
751 if self.hash_oid_name.has_key(att_oid) and\
752 att.lower() == self.hash_oid_name[att_oid].lower():
753 found = True
754 seq = self.sequence_number(ldb.SEQ_NEXT)
755 o.version = value
756 o.originating_change_time = now
757 o.originating_invocation_id = misc.GUID(self.get_invocation_id())
758 o.originating_usn = seq
759 o.local_usn = seq
761 if not found and addifnotexist and len(ctr.array) >0:
762 o2 = drsblobs.replPropertyMetaData1()
763 o2.attid = 589914
764 att_oid = self.get_oid_from_attid(o2.attid)
765 seq = self.sequence_number(ldb.SEQ_NEXT)
766 o2.version = value
767 o2.originating_change_time = now
768 o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
769 o2.originating_usn = seq
770 o2.local_usn = seq
771 found = True
772 tab = ctr.array
773 tab.append(o2)
774 ctr.count = ctr.count + 1
775 ctr.array = tab
777 if found :
778 replBlob = ndr_pack(repl)
779 msg = ldb.Message()
780 msg.dn = res[0].dn
781 msg["replPropertyMetaData"] = ldb.MessageElement(replBlob,
782 ldb.FLAG_MOD_REPLACE,
783 "replPropertyMetaData")
784 self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
786 def write_prefixes_from_schema(self):
787 dsdb._dsdb_write_prefixes_from_schema_to_ldb(self)
789 def get_partitions_dn(self):
790 return dsdb._dsdb_get_partitions_dn(self)
792 def get_nc_root(self, dn):
793 return dsdb._dsdb_get_nc_root(self, dn)
795 def get_wellknown_dn(self, nc_root, wkguid):
796 return dsdb._dsdb_get_wellknown_dn(self, nc_root, wkguid)
798 def set_minPwdAge(self, value):
799 m = ldb.Message()
800 m.dn = ldb.Dn(self, self.domain_dn())
801 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
802 self.modify(m)
804 def get_minPwdAge(self):
805 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
806 if len(res) == 0:
807 return None
808 elif not "minPwdAge" in res[0]:
809 return None
810 else:
811 return res[0]["minPwdAge"][0]
813 def set_minPwdLength(self, value):
814 m = ldb.Message()
815 m.dn = ldb.Dn(self, self.domain_dn())
816 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
817 self.modify(m)
819 def get_minPwdLength(self):
820 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
821 if len(res) == 0:
822 return None
823 elif not "minPwdLength" in res[0]:
824 return None
825 else:
826 return res[0]["minPwdLength"][0]
828 def set_pwdProperties(self, value):
829 m = ldb.Message()
830 m.dn = ldb.Dn(self, self.domain_dn())
831 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
832 self.modify(m)
834 def get_pwdProperties(self):
835 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
836 if len(res) == 0:
837 return None
838 elif not "pwdProperties" in res[0]:
839 return None
840 else:
841 return res[0]["pwdProperties"][0]
843 def set_dsheuristics(self, dsheuristics):
844 m = ldb.Message()
845 m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
846 % self.get_config_basedn().get_linearized())
847 if dsheuristics is not None:
848 m["dSHeuristics"] = ldb.MessageElement(dsheuristics,
849 ldb.FLAG_MOD_REPLACE, "dSHeuristics")
850 else:
851 m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
852 "dSHeuristics")
853 self.modify(m)
855 def get_dsheuristics(self):
856 res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
857 % self.get_config_basedn().get_linearized(),
858 scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"])
859 if len(res) == 0:
860 dsheuristics = None
861 elif "dSHeuristics" in res[0]:
862 dsheuristics = res[0]["dSHeuristics"][0]
863 else:
864 dsheuristics = None
866 return dsheuristics
868 def create_ou(self, ou_dn, description=None, name=None, sd=None):
869 """Creates an organizationalUnit object
870 :param ou_dn: dn of the new object
871 :param description: description attribute
872 :param name: name atttribute
873 :param sd: security descriptor of the object, can be
874 an SDDL string or security.descriptor type
876 m = {"dn": ou_dn,
877 "objectClass": "organizationalUnit"}
879 if description:
880 m["description"] = description
881 if name:
882 m["name"] = name
884 if sd:
885 m["nTSecurityDescriptor"] = ndr_pack(sd)
886 self.add(m)
888 def sequence_number(self, seq_type):
889 """Returns the value of the sequence number according to the requested type
890 :param seq_type: type of sequence number
892 self.transaction_start()
893 try:
894 seq = super(SamDB, self).sequence_number(seq_type)
895 except:
896 self.transaction_cancel()
897 raise
898 else:
899 self.transaction_commit()
900 return seq
902 def get_dsServiceName(self):
903 '''get the NTDS DN from the rootDSE'''
904 res = self.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
905 return res[0]["dsServiceName"][0]
907 def get_serverName(self):
908 '''get the server DN from the rootDSE'''
909 res = self.search(base="", scope=ldb.SCOPE_BASE, attrs=["serverName"])
910 return res[0]["serverName"][0]