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."""
31 from samba import dsdb, dsdb_dns
32 from samba.ndr import ndr_unpack, ndr_pack
33 from samba.dcerpc import drsblobs, misc
34 from samba.common import normalise_int32
35 from samba.compat import text_type
36 from samba.dcerpc import security
38 __docformat__ = "restructuredText"
41 def get_default_backend_store():
44 class SamDB(samba.Ldb):
45 """The SAM database."""
50 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
51 credentials=None, flags=ldb.FLG_DONT_CREATE_DB,
52 options=None, global_schema=True,
53 auto_connect=True, am_rodc=None):
57 elif url is None and lp is not None:
62 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
63 session_info=session_info, credentials=credentials, flags=flags,
67 dsdb._dsdb_set_global_schema(self)
69 if am_rodc is not None:
70 dsdb._dsdb_set_am_rodc(self, am_rodc)
72 def connect(self, url=None, flags=0, options=None):
73 '''connect to the database'''
74 if self.lp is not None and not os.path.exists(url):
75 url = self.lp.private_path(url)
78 super(SamDB, self).connect(url=url, flags=flags,
82 '''return True if we are an RODC'''
83 return dsdb._am_rodc(self)
86 '''return True if we are an PDC emulator'''
87 return dsdb._am_pdc(self)
90 '''return the domain DN'''
91 return str(self.get_default_basedn())
94 '''return the schema partition dn'''
95 return str(self.get_schema_basedn())
97 def disable_account(self, search_filter):
98 """Disables an account
100 :param search_filter: LDAP filter to find the user (eg
104 flags = samba.dsdb.UF_ACCOUNTDISABLE
105 self.toggle_userAccountFlags(search_filter, flags, on=True)
107 def enable_account(self, search_filter):
108 """Enables an account
110 :param search_filter: LDAP filter to find the user (eg
114 flags = samba.dsdb.UF_ACCOUNTDISABLE | samba.dsdb.UF_PASSWD_NOTREQD
115 self.toggle_userAccountFlags(search_filter, flags, on=False)
117 def toggle_userAccountFlags(self, search_filter, flags, flags_str=None,
118 on=True, strict=False):
119 """Toggle_userAccountFlags
121 :param search_filter: LDAP filter to find the user (eg
123 :param flags: samba.dsdb.UF_* flags
124 :param on: on=True (default) => set, on=False => unset
125 :param strict: strict=False (default) ignore if no action is needed
126 strict=True raises an Exception if...
128 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
129 expression=search_filter, attrs=["userAccountControl"])
131 raise Exception("Unable to find account where '%s'" % search_filter)
132 assert(len(res) == 1)
133 account_dn = res[0].dn
135 old_uac = int(res[0]["userAccountControl"][0])
137 if strict and (old_uac & flags):
138 error = "Account flag(s) '%s' already set" % flags_str
139 raise Exception(error)
141 new_uac = old_uac | flags
143 if strict and not (old_uac & flags):
144 error = "Account flag(s) '%s' already unset" % flags_str
145 raise Exception(error)
147 new_uac = old_uac & ~flags
149 if old_uac == new_uac:
155 delete: userAccountControl
156 userAccountControl: %u
157 add: userAccountControl
158 userAccountControl: %u
159 """ % (account_dn, old_uac, new_uac)
160 self.modify_ldif(mod)
162 def force_password_change_at_next_login(self, search_filter):
163 """Forces a password change at next login
165 :param search_filter: LDAP filter to find the user (eg
168 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
169 expression=search_filter, attrs=[])
171 raise Exception('Unable to find user "%s"' % search_filter)
172 assert(len(res) == 1)
181 self.modify_ldif(mod)
183 def newgroup(self, groupname, groupou=None, grouptype=None,
184 description=None, mailaddress=None, notes=None, sd=None,
185 gidnumber=None, nisdomain=None):
186 """Adds a new group with additional parameters
188 :param groupname: Name of the new group
189 :param grouptype: Type of the new group
190 :param description: Description of the new group
191 :param mailaddress: Email address of the new group
192 :param notes: Notes of the new group
193 :param gidnumber: GID Number of the new group
194 :param nisdomain: NIS Domain Name of the new group
195 :param sd: security descriptor of the object
198 group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
200 # The new user record. Note the reliance on the SAMLDB module which
201 # fills in the default informations
202 ldbmessage = {"dn": group_dn,
203 "sAMAccountName": groupname,
204 "objectClass": "group"}
206 if grouptype is not None:
207 ldbmessage["groupType"] = normalise_int32(grouptype)
209 if description is not None:
210 ldbmessage["description"] = description
212 if mailaddress is not None:
213 ldbmessage["mail"] = mailaddress
215 if notes is not None:
216 ldbmessage["info"] = notes
218 if gidnumber is not None:
219 ldbmessage["gidNumber"] = normalise_int32(gidnumber)
221 if nisdomain is not None:
222 ldbmessage["msSFU30Name"] = groupname
223 ldbmessage["msSFU30NisDomain"] = nisdomain
226 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
230 def deletegroup(self, groupname):
233 :param groupname: Name of the target group
236 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(groupname), "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
237 self.transaction_start()
239 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
240 expression=groupfilter, attrs=[])
241 if len(targetgroup) == 0:
242 raise Exception('Unable to find group "%s"' % groupname)
243 assert(len(targetgroup) == 1)
244 self.delete(targetgroup[0].dn)
246 self.transaction_cancel()
249 self.transaction_commit()
251 def add_remove_group_members(self, groupname, members,
252 add_members_operation=True):
253 """Adds or removes group members
255 :param groupname: Name of the target group
256 :param members: list of group members
257 :param add_members_operation: Defines if its an add or remove
261 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (
262 ldb.binary_encode(groupname), "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
264 self.transaction_start()
266 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
267 expression=groupfilter, attrs=['member'])
268 if len(targetgroup) == 0:
269 raise Exception('Unable to find group "%s"' % groupname)
270 assert(len(targetgroup) == 1)
274 addtargettogroup = """
277 """ % (str(targetgroup[0].dn))
279 for member in members:
280 filter = ('(&(sAMAccountName=%s)(|(objectclass=user)'
281 '(objectclass=group)))' % ldb.binary_encode(member))
284 membersid = security.dom_sid(member)
285 except TypeError as e:
288 if membersid is not None:
289 filter = '(objectSid=%s)' % str(membersid)
290 dn_str = "<SID=%s>" % str(membersid)
291 foreign_msg = ldb.Message()
292 foreign_msg.dn = ldb.Dn(self, dn_str)
294 targetmember = self.search(base=self.domain_dn(),
295 scope=ldb.SCOPE_SUBTREE,
296 expression="%s" % filter,
299 if len(targetmember) == 0 and foreign_msg is not None:
300 targetmember = [foreign_msg]
301 if len(targetmember) != 1:
302 raise Exception('Unable to find "%s". Operation cancelled.' % member)
303 targetmember_dn = targetmember[0].dn.extended_str(1)
305 if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember_dn) not in targetgroup[0]['member']):
307 addtargettogroup += """add: member
309 """ % (str(targetmember_dn))
311 elif add_members_operation is False and (targetgroup[0].get('member') is not None and targetmember_dn in targetgroup[0]['member']):
313 addtargettogroup += """delete: member
315 """ % (str(targetmember_dn))
318 self.modify_ldif(addtargettogroup)
321 self.transaction_cancel()
324 self.transaction_commit()
326 def newuser(self, username, password,
327 force_password_change_at_next_login_req=False,
328 useusernameascn=False, userou=None, surname=None, givenname=None,
329 initials=None, profilepath=None, scriptpath=None, homedrive=None,
330 homedirectory=None, jobtitle=None, department=None, company=None,
331 description=None, mailaddress=None, internetaddress=None,
332 telephonenumber=None, physicaldeliveryoffice=None, sd=None,
333 setpassword=True, uidnumber=None, gidnumber=None, gecos=None,
334 loginshell=None, uid=None, nisdomain=None, unixhome=None,
335 smartcard_required=False):
336 """Adds a new user with additional parameters
338 :param username: Name of the new user
339 :param password: Password for the new user
340 :param force_password_change_at_next_login_req: Force password change
341 :param useusernameascn: Use username as cn rather that firstname +
343 :param userou: Object container (without domainDN postfix) for new user
344 :param surname: Surname of the new user
345 :param givenname: First name of the new user
346 :param initials: Initials of the new user
347 :param profilepath: Profile path of the new user
348 :param scriptpath: Logon script path of the new user
349 :param homedrive: Home drive of the new user
350 :param homedirectory: Home directory of the new user
351 :param jobtitle: Job title of the new user
352 :param department: Department of the new user
353 :param company: Company of the new user
354 :param description: of the new user
355 :param mailaddress: Email address of the new user
356 :param internetaddress: Home page of the new user
357 :param telephonenumber: Phone number of the new user
358 :param physicaldeliveryoffice: Office location of the new user
359 :param sd: security descriptor of the object
360 :param setpassword: optionally disable password reset
361 :param uidnumber: RFC2307 Unix numeric UID of the new user
362 :param gidnumber: RFC2307 Unix primary GID of the new user
363 :param gecos: RFC2307 Unix GECOS field of the new user
364 :param loginshell: RFC2307 Unix login shell of the new user
365 :param uid: RFC2307 Unix username of the new user
366 :param nisdomain: RFC2307 Unix NIS domain of the new user
367 :param unixhome: RFC2307 Unix home directory of the new user
368 :param smartcard_required: set the UF_SMARTCARD_REQUIRED bit of the new user
372 if givenname is not None:
373 displayname += givenname
375 if initials is not None:
376 displayname += ' %s.' % initials
378 if surname is not None:
379 displayname += ' %s' % surname
382 if useusernameascn is None and displayname is not "":
385 user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
387 dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "")
388 user_principal_name = "%s@%s" % (username, dnsdomain)
389 # The new user record. Note the reliance on the SAMLDB module which
390 # fills in the default informations
391 ldbmessage = {"dn": user_dn,
392 "sAMAccountName": username,
393 "userPrincipalName": user_principal_name,
394 "objectClass": "user"}
396 if smartcard_required:
397 ldbmessage["userAccountControl"] = str(dsdb.UF_NORMAL_ACCOUNT|dsdb.UF_SMARTCARD_REQUIRED)
400 if surname is not None:
401 ldbmessage["sn"] = surname
403 if givenname is not None:
404 ldbmessage["givenName"] = givenname
406 if displayname is not "":
407 ldbmessage["displayName"] = displayname
408 ldbmessage["name"] = displayname
410 if initials is not None:
411 ldbmessage["initials"] = '%s.' % initials
413 if profilepath is not None:
414 ldbmessage["profilePath"] = profilepath
416 if scriptpath is not None:
417 ldbmessage["scriptPath"] = scriptpath
419 if homedrive is not None:
420 ldbmessage["homeDrive"] = homedrive
422 if homedirectory is not None:
423 ldbmessage["homeDirectory"] = homedirectory
425 if jobtitle is not None:
426 ldbmessage["title"] = jobtitle
428 if department is not None:
429 ldbmessage["department"] = department
431 if company is not None:
432 ldbmessage["company"] = company
434 if description is not None:
435 ldbmessage["description"] = description
437 if mailaddress is not None:
438 ldbmessage["mail"] = mailaddress
440 if internetaddress is not None:
441 ldbmessage["wWWHomePage"] = internetaddress
443 if telephonenumber is not None:
444 ldbmessage["telephoneNumber"] = telephonenumber
446 if physicaldeliveryoffice is not None:
447 ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
450 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
453 if any(map(lambda b: b is not None, (uid, uidnumber, gidnumber, gecos,
454 loginshell, nisdomain, unixhome))):
455 ldbmessage2 = ldb.Message()
456 ldbmessage2.dn = ldb.Dn(self, user_dn)
458 ldbmessage2["uid"] = ldb.MessageElement(str(uid), ldb.FLAG_MOD_REPLACE, 'uid')
459 if uidnumber is not None:
460 ldbmessage2["uidNumber"] = ldb.MessageElement(str(uidnumber), ldb.FLAG_MOD_REPLACE, 'uidNumber')
461 if gidnumber is not None:
462 ldbmessage2["gidNumber"] = ldb.MessageElement(str(gidnumber), ldb.FLAG_MOD_REPLACE, 'gidNumber')
463 if gecos is not None:
464 ldbmessage2["gecos"] = ldb.MessageElement(str(gecos), ldb.FLAG_MOD_REPLACE, 'gecos')
465 if loginshell is not None:
466 ldbmessage2["loginShell"] = ldb.MessageElement(str(loginshell), ldb.FLAG_MOD_REPLACE, 'loginShell')
467 if unixhome is not None:
468 ldbmessage2["unixHomeDirectory"] = ldb.MessageElement(
469 str(unixhome), ldb.FLAG_MOD_REPLACE, 'unixHomeDirectory')
470 if nisdomain is not None:
471 ldbmessage2["msSFU30NisDomain"] = ldb.MessageElement(
472 str(nisdomain), ldb.FLAG_MOD_REPLACE, 'msSFU30NisDomain')
473 ldbmessage2["msSFU30Name"] = ldb.MessageElement(
474 str(username), ldb.FLAG_MOD_REPLACE, 'msSFU30Name')
475 ldbmessage2["unixUserPassword"] = ldb.MessageElement(
476 'ABCD!efgh12345$67890', ldb.FLAG_MOD_REPLACE,
479 self.transaction_start()
483 self.modify(ldbmessage2)
485 # Sets the password for it
487 self.setpassword(("(distinguishedName=%s)" %
488 ldb.binary_encode(user_dn)),
490 force_password_change_at_next_login_req)
492 self.transaction_cancel()
495 self.transaction_commit()
497 def newcomputer(self, computername, computerou=None, description=None,
498 prepare_oldjoin=False, ip_address_list=None,
499 service_principal_name_list=None):
500 """Adds a new user with additional parameters
502 :param computername: Name of the new computer
503 :param computerou: Object container for new computer
504 :param description: Description of the new computer
505 :param prepare_oldjoin: Preset computer password for oldjoin mechanism
506 :param ip_address_list: ip address list for DNS A or AAAA record
507 :param service_principal_name_list: string list of servicePincipalName
510 cn = re.sub(r"\$$", "", computername)
512 raise Exception('Illegal computername "%s"' % computername)
513 samaccountname = "%s$" % cn
515 computercontainer_dn = "CN=Computers,%s" % self.domain_dn()
517 computercontainer_dn = self.normalize_dn_in_domain(computerou)
519 computer_dn = "CN=%s,%s" % (cn, computercontainer_dn)
521 ldbmessage = {"dn": computer_dn,
522 "sAMAccountName": samaccountname,
523 "objectClass": "computer",
526 if description is not None:
527 ldbmessage["description"] = description
529 if service_principal_name_list:
530 ldbmessage["servicePrincipalName"] = service_principal_name_list
532 accountcontrol = str(dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
533 dsdb.UF_ACCOUNTDISABLE)
535 accountcontrol = str(dsdb.UF_WORKSTATION_TRUST_ACCOUNT)
536 ldbmessage["userAccountControl"] = accountcontrol
539 ldbmessage['dNSHostName'] = '{}.{}'.format(
540 cn, self.domain_dns_name())
542 self.transaction_start()
547 password = cn.lower()
548 self.setpassword(("(distinguishedName=%s)" %
549 ldb.binary_encode(computer_dn)),
552 self.transaction_cancel()
555 self.transaction_commit()
557 def deleteuser(self, username):
560 :param username: Name of the target user
563 filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(username), "CN=Person,CN=Schema,CN=Configuration", self.domain_dn())
564 self.transaction_start()
566 target = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
567 expression=filter, attrs=[])
569 raise Exception('Unable to find user "%s"' % username)
570 assert(len(target) == 1)
571 self.delete(target[0].dn)
573 self.transaction_cancel()
576 self.transaction_commit()
578 def setpassword(self, search_filter, password,
579 force_change_at_next_login=False, username=None):
580 """Sets the password for a user
582 :param search_filter: LDAP filter to find the user (eg
584 :param password: Password for the user
585 :param force_change_at_next_login: Force password change
587 self.transaction_start()
589 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
590 expression=search_filter, attrs=[])
592 raise Exception('Unable to find user "%s"' % (username or search_filter))
594 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
596 if not isinstance(password, text_type):
597 pw = password.decode('utf-8')
600 pw = ('"' + pw + '"').encode('utf-16-le')
606 """ % (user_dn, base64.b64encode(pw).decode('utf-8'))
608 self.modify_ldif(setpw)
610 if force_change_at_next_login:
611 self.force_password_change_at_next_login(
612 "(distinguishedName=" + str(user_dn) + ")")
614 # modify the userAccountControl to remove the disabled bit
615 self.enable_account(search_filter)
617 self.transaction_cancel()
620 self.transaction_commit()
622 def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False):
623 """Sets the account expiry for a user
625 :param search_filter: LDAP filter to find the user (eg
627 :param expiry_seconds: expiry time from now in seconds
628 :param no_expiry_req: if set, then don't expire password
630 self.transaction_start()
632 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
633 expression=search_filter,
634 attrs=["userAccountControl", "accountExpires"])
636 raise Exception('Unable to find user "%s"' % search_filter)
637 assert(len(res) == 1)
640 userAccountControl = int(res[0]["userAccountControl"][0])
641 accountExpires = int(res[0]["accountExpires"][0])
643 userAccountControl = userAccountControl | 0x10000
646 userAccountControl = userAccountControl & ~0x10000
647 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
652 replace: userAccountControl
653 userAccountControl: %u
654 replace: accountExpires
656 """ % (user_dn, userAccountControl, accountExpires)
658 self.modify_ldif(setexp)
660 self.transaction_cancel()
663 self.transaction_commit()
665 def set_domain_sid(self, sid):
666 """Change the domain SID used by this LDB.
668 :param sid: The new domain sid to use.
670 dsdb._samdb_set_domain_sid(self, sid)
672 def get_domain_sid(self):
673 """Read the domain SID used by this LDB. """
674 return dsdb._samdb_get_domain_sid(self)
676 domain_sid = property(get_domain_sid, set_domain_sid,
677 "SID for the domain")
679 def set_invocation_id(self, invocation_id):
680 """Set the invocation id for this SamDB handle.
682 :param invocation_id: GUID of the invocation id.
684 dsdb._dsdb_set_ntds_invocation_id(self, invocation_id)
686 def get_invocation_id(self):
687 """Get the invocation_id id"""
688 return dsdb._samdb_ntds_invocation_id(self)
690 invocation_id = property(get_invocation_id, set_invocation_id,
691 "Invocation ID GUID")
693 def get_oid_from_attid(self, attid):
694 return dsdb._dsdb_get_oid_from_attid(self, attid)
696 def get_attid_from_lDAPDisplayName(self, ldap_display_name,
698 '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
699 return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
700 ldap_display_name, is_schema_nc)
702 def get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name):
703 '''return the syntax OID for a LDAP attribute as a string'''
704 return dsdb._dsdb_get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name)
706 def get_systemFlags_from_lDAPDisplayName(self, ldap_display_name):
707 '''return the systemFlags for a LDAP attribute as a integer'''
708 return dsdb._dsdb_get_systemFlags_from_lDAPDisplayName(self, ldap_display_name)
710 def get_linkId_from_lDAPDisplayName(self, ldap_display_name):
711 '''return the linkID for a LDAP attribute as a integer'''
712 return dsdb._dsdb_get_linkId_from_lDAPDisplayName(self, ldap_display_name)
714 def get_lDAPDisplayName_by_attid(self, attid):
715 '''return the lDAPDisplayName from an integer DRS attribute ID'''
716 return dsdb._dsdb_get_lDAPDisplayName_by_attid(self, attid)
718 def get_backlink_from_lDAPDisplayName(self, ldap_display_name):
719 '''return the attribute name of the corresponding backlink from the name
720 of a forward link attribute. If there is no backlink return None'''
721 return dsdb._dsdb_get_backlink_from_lDAPDisplayName(self, ldap_display_name)
723 def set_ntds_settings_dn(self, ntds_settings_dn):
724 """Set the NTDS Settings DN, as would be returned on the dsServiceName
727 This allows the DN to be set before the database fully exists
729 :param ntds_settings_dn: The new DN to use
731 dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn)
733 def get_ntds_GUID(self):
734 """Get the NTDS objectGUID"""
735 return dsdb._samdb_ntds_objectGUID(self)
737 def server_site_name(self):
738 """Get the server site name"""
739 return dsdb._samdb_server_site_name(self)
741 def host_dns_name(self):
742 """return the DNS name of this host"""
743 res = self.search(base='', scope=ldb.SCOPE_BASE, attrs=['dNSHostName'])
744 return res[0]['dNSHostName'][0]
746 def domain_dns_name(self):
747 """return the DNS name of the domain root"""
748 domain_dn = self.get_default_basedn()
749 return domain_dn.canonical_str().split('/')[0]
751 def forest_dns_name(self):
752 """return the DNS name of the forest root"""
753 forest_dn = self.get_root_basedn()
754 return forest_dn.canonical_str().split('/')[0]
756 def load_partition_usn(self, base_dn):
757 return dsdb._dsdb_load_partition_usn(self, base_dn)
759 def set_schema(self, schema, write_indices_and_attributes=True):
760 self.set_schema_from_ldb(schema.ldb, write_indices_and_attributes=write_indices_and_attributes)
762 def set_schema_from_ldb(self, ldb_conn, write_indices_and_attributes=True):
763 dsdb._dsdb_set_schema_from_ldb(self, ldb_conn, write_indices_and_attributes)
765 def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements):
766 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
767 return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements)
769 def dsdb_normalise_attributes(self, ldb, ldap_display_name, ldif_elements):
770 '''normalise a list of attribute values'''
771 return dsdb._dsdb_normalise_attributes(ldb, ldap_display_name, ldif_elements)
773 def get_attribute_from_attid(self, attid):
774 """ Get from an attid the associated attribute
776 :param attid: The attribute id for searched attribute
777 :return: The name of the attribute associated with this id
779 if len(self.hash_oid_name.keys()) == 0:
780 self._populate_oid_attid()
781 if self.get_oid_from_attid(attid) in self.hash_oid_name:
782 return self.hash_oid_name[self.get_oid_from_attid(attid)]
786 def _populate_oid_attid(self):
787 """Populate the hash hash_oid_name.
789 This hash contains the oid of the attribute as a key and
790 its display name as a value
792 self.hash_oid_name = {}
793 res = self.search(expression="objectClass=attributeSchema",
794 controls=["search_options:1:2"],
795 attrs=["attributeID",
799 strDisplay = str(e.get("lDAPDisplayName"))
800 self.hash_oid_name[str(e.get("attributeID"))] = strDisplay
802 def get_attribute_replmetadata_version(self, dn, att):
803 """Get the version field trom the replPropertyMetaData for
806 :param dn: The on which we want to get the version
807 :param att: The name of the attribute
808 :return: The value of the version field in the replPropertyMetaData
809 for the given attribute. None if the attribute is not replicated
812 res = self.search(expression="distinguishedName=%s" % dn,
813 scope=ldb.SCOPE_SUBTREE,
814 controls=["search_options:1:2"],
815 attrs=["replPropertyMetaData"])
819 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
820 res[0]["replPropertyMetaData"][0])
822 if len(self.hash_oid_name.keys()) == 0:
823 self._populate_oid_attid()
825 # Search for Description
826 att_oid = self.get_oid_from_attid(o.attid)
827 if att_oid in self.hash_oid_name and\
828 att.lower() == self.hash_oid_name[att_oid].lower():
832 def set_attribute_replmetadata_version(self, dn, att, value,
833 addifnotexist=False):
834 res = self.search(expression="distinguishedName=%s" % dn,
835 scope=ldb.SCOPE_SUBTREE,
836 controls=["search_options:1:2"],
837 attrs=["replPropertyMetaData"])
841 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
842 res[0]["replPropertyMetaData"][0])
844 now = samba.unix2nttime(int(time.time()))
846 if len(self.hash_oid_name.keys()) == 0:
847 self._populate_oid_attid()
849 # Search for Description
850 att_oid = self.get_oid_from_attid(o.attid)
851 if att_oid in self.hash_oid_name and\
852 att.lower() == self.hash_oid_name[att_oid].lower():
854 seq = self.sequence_number(ldb.SEQ_NEXT)
856 o.originating_change_time = now
857 o.originating_invocation_id = misc.GUID(self.get_invocation_id())
858 o.originating_usn = seq
861 if not found and addifnotexist and len(ctr.array) >0:
862 o2 = drsblobs.replPropertyMetaData1()
864 att_oid = self.get_oid_from_attid(o2.attid)
865 seq = self.sequence_number(ldb.SEQ_NEXT)
867 o2.originating_change_time = now
868 o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
869 o2.originating_usn = seq
874 ctr.count = ctr.count + 1
878 replBlob = ndr_pack(repl)
881 msg["replPropertyMetaData"] = ldb.MessageElement(replBlob,
882 ldb.FLAG_MOD_REPLACE,
883 "replPropertyMetaData")
884 self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
886 def write_prefixes_from_schema(self):
887 dsdb._dsdb_write_prefixes_from_schema_to_ldb(self)
889 def get_partitions_dn(self):
890 return dsdb._dsdb_get_partitions_dn(self)
892 def get_nc_root(self, dn):
893 return dsdb._dsdb_get_nc_root(self, dn)
895 def get_wellknown_dn(self, nc_root, wkguid):
896 h_nc = self.hash_well_known.get(str(nc_root))
899 dn = h_nc.get(wkguid)
901 dn = dsdb._dsdb_get_wellknown_dn(self, nc_root, wkguid)
905 self.hash_well_known[str(nc_root)] = {}
906 h_nc = self.hash_well_known[str(nc_root)]
910 def set_minPwdAge(self, value):
912 m.dn = ldb.Dn(self, self.domain_dn())
913 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
916 def get_minPwdAge(self):
917 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
920 elif not "minPwdAge" in res[0]:
923 return res[0]["minPwdAge"][0]
925 def set_maxPwdAge(self, value):
927 m.dn = ldb.Dn(self, self.domain_dn())
928 m["maxPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "maxPwdAge")
932 def get_maxPwdAge(self):
933 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["maxPwdAge"])
936 elif not "maxPwdAge" in res[0]:
939 return res[0]["maxPwdAge"][0]
943 def set_minPwdLength(self, value):
945 m.dn = ldb.Dn(self, self.domain_dn())
946 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
949 def get_minPwdLength(self):
950 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
953 elif not "minPwdLength" in res[0]:
956 return res[0]["minPwdLength"][0]
958 def set_pwdProperties(self, value):
960 m.dn = ldb.Dn(self, self.domain_dn())
961 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
964 def get_pwdProperties(self):
965 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
968 elif not "pwdProperties" in res[0]:
971 return res[0]["pwdProperties"][0]
973 def set_dsheuristics(self, dsheuristics):
975 m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
976 % self.get_config_basedn().get_linearized())
977 if dsheuristics is not None:
978 m["dSHeuristics"] = ldb.MessageElement(dsheuristics,
979 ldb.FLAG_MOD_REPLACE, "dSHeuristics")
981 m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
985 def get_dsheuristics(self):
986 res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
987 % self.get_config_basedn().get_linearized(),
988 scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"])
991 elif "dSHeuristics" in res[0]:
992 dsheuristics = res[0]["dSHeuristics"][0]
998 def create_ou(self, ou_dn, description=None, name=None, sd=None):
999 """Creates an organizationalUnit object
1000 :param ou_dn: dn of the new object
1001 :param description: description attribute
1002 :param name: name atttribute
1003 :param sd: security descriptor of the object, can be
1004 an SDDL string or security.descriptor type
1007 "objectClass": "organizationalUnit"}
1010 m["description"] = description
1015 m["nTSecurityDescriptor"] = ndr_pack(sd)
1018 def sequence_number(self, seq_type):
1019 """Returns the value of the sequence number according to the requested type
1020 :param seq_type: type of sequence number
1022 self.transaction_start()
1024 seq = super(SamDB, self).sequence_number(seq_type)
1026 self.transaction_cancel()
1029 self.transaction_commit()
1032 def get_dsServiceName(self):
1033 '''get the NTDS DN from the rootDSE'''
1034 res = self.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
1035 return res[0]["dsServiceName"][0]
1037 def get_serverName(self):
1038 '''get the server DN from the rootDSE'''
1039 res = self.search(base="", scope=ldb.SCOPE_BASE, attrs=["serverName"])
1040 return res[0]["serverName"][0]
1042 def dns_lookup(self, dns_name, dns_partition=None):
1043 '''Do a DNS lookup in the database, returns the NDR database structures'''
1044 if dns_partition is None:
1045 return dsdb_dns.lookup(self, dns_name)
1047 return dsdb_dns.lookup(self, dns_name,
1048 dns_partition=dns_partition)
1050 def dns_extract(self, el):
1051 '''Return the NDR database structures from a dnsRecord element'''
1052 return dsdb_dns.extract(self, el)
1054 def dns_replace(self, dns_name, new_records):
1055 '''Do a DNS modification on the database, sets the NDR database
1056 structures on a DNS name
1058 return dsdb_dns.replace(self, dns_name, new_records)
1060 def dns_replace_by_dn(self, dn, new_records):
1061 '''Do a DNS modification on the database, sets the NDR database
1062 structures on a LDB DN
1064 This routine is important because if the last record on the DN
1065 is removed, this routine will put a tombstone in the record.
1067 return dsdb_dns.replace_by_dn(self, dn, new_records)
1069 def garbage_collect_tombstones(self, dn, current_time,
1070 tombstone_lifetime=None):
1071 '''garbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
1072 -> (num_objects_expunged, num_links_expunged)'''
1075 if tombstone_lifetime is None:
1076 return dsdb._dsdb_garbage_collect_tombstones(self, dn,
1079 return dsdb._dsdb_garbage_collect_tombstones(self, dn,
1083 def create_own_rid_set(self):
1084 '''create a RID set for this DSA'''
1085 return dsdb._dsdb_create_own_rid_set(self)
1087 def allocate_rid(self):
1088 '''return a new RID from the RID Pool on this DSA'''
1089 return dsdb._dsdb_allocate_rid(self)
1091 def normalize_dn_in_domain(self, dn):
1092 '''return a new DN expanded by adding the domain DN
1094 If the dn is already a child of the domain DN, just
1097 :param dn: relative dn
1099 domain_dn = ldb.Dn(self, self.domain_dn())
1101 if isinstance(dn, ldb.Dn):
1104 full_dn = ldb.Dn(self, dn)
1105 if not full_dn.is_child_of(domain_dn):
1106 full_dn.add_base(domain_dn)