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 set_schema_update_now(self
):
772 self
.modify_ldif(ldif
)
774 def dsdb_DsReplicaAttribute(self
, ldb
, ldap_display_name
, ldif_elements
):
775 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
776 return dsdb
._dsdb
_DsReplicaAttribute
(ldb
, ldap_display_name
, ldif_elements
)
778 def dsdb_normalise_attributes(self
, ldb
, ldap_display_name
, ldif_elements
):
779 '''normalise a list of attribute values'''
780 return dsdb
._dsdb
_normalise
_attributes
(ldb
, ldap_display_name
, ldif_elements
)
782 def get_attribute_from_attid(self
, attid
):
783 """ Get from an attid the associated attribute
785 :param attid: The attribute id for searched attribute
786 :return: The name of the attribute associated with this id
788 if len(self
.hash_oid_name
.keys()) == 0:
789 self
._populate
_oid
_attid
()
790 if self
.get_oid_from_attid(attid
) in self
.hash_oid_name
:
791 return self
.hash_oid_name
[self
.get_oid_from_attid(attid
)]
795 def _populate_oid_attid(self
):
796 """Populate the hash hash_oid_name.
798 This hash contains the oid of the attribute as a key and
799 its display name as a value
801 self
.hash_oid_name
= {}
802 res
= self
.search(expression
="objectClass=attributeSchema",
803 controls
=["search_options:1:2"],
804 attrs
=["attributeID",
808 strDisplay
= str(e
.get("lDAPDisplayName"))
809 self
.hash_oid_name
[str(e
.get("attributeID"))] = strDisplay
811 def get_attribute_replmetadata_version(self
, dn
, att
):
812 """Get the version field trom the replPropertyMetaData for
815 :param dn: The on which we want to get the version
816 :param att: The name of the attribute
817 :return: The value of the version field in the replPropertyMetaData
818 for the given attribute. None if the attribute is not replicated
821 res
= self
.search(expression
="distinguishedName=%s" % dn
,
822 scope
=ldb
.SCOPE_SUBTREE
,
823 controls
=["search_options:1:2"],
824 attrs
=["replPropertyMetaData"])
828 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
829 res
[0]["replPropertyMetaData"][0])
831 if len(self
.hash_oid_name
.keys()) == 0:
832 self
._populate
_oid
_attid
()
834 # Search for Description
835 att_oid
= self
.get_oid_from_attid(o
.attid
)
836 if att_oid
in self
.hash_oid_name
and\
837 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
841 def set_attribute_replmetadata_version(self
, dn
, att
, value
,
842 addifnotexist
=False):
843 res
= self
.search(expression
="distinguishedName=%s" % dn
,
844 scope
=ldb
.SCOPE_SUBTREE
,
845 controls
=["search_options:1:2"],
846 attrs
=["replPropertyMetaData"])
850 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
851 res
[0]["replPropertyMetaData"][0])
853 now
= samba
.unix2nttime(int(time
.time()))
855 if len(self
.hash_oid_name
.keys()) == 0:
856 self
._populate
_oid
_attid
()
858 # Search for Description
859 att_oid
= self
.get_oid_from_attid(o
.attid
)
860 if att_oid
in self
.hash_oid_name
and\
861 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
863 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
865 o
.originating_change_time
= now
866 o
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
867 o
.originating_usn
= seq
870 if not found
and addifnotexist
and len(ctr
.array
) >0:
871 o2
= drsblobs
.replPropertyMetaData1()
873 att_oid
= self
.get_oid_from_attid(o2
.attid
)
874 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
876 o2
.originating_change_time
= now
877 o2
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
878 o2
.originating_usn
= seq
883 ctr
.count
= ctr
.count
+ 1
887 replBlob
= ndr_pack(repl
)
890 msg
["replPropertyMetaData"] = ldb
.MessageElement(replBlob
,
891 ldb
.FLAG_MOD_REPLACE
,
892 "replPropertyMetaData")
893 self
.modify(msg
, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
895 def write_prefixes_from_schema(self
):
896 dsdb
._dsdb
_write
_prefixes
_from
_schema
_to
_ldb
(self
)
898 def get_partitions_dn(self
):
899 return dsdb
._dsdb
_get
_partitions
_dn
(self
)
901 def get_nc_root(self
, dn
):
902 return dsdb
._dsdb
_get
_nc
_root
(self
, dn
)
904 def get_wellknown_dn(self
, nc_root
, wkguid
):
905 h_nc
= self
.hash_well_known
.get(str(nc_root
))
908 dn
= h_nc
.get(wkguid
)
910 dn
= dsdb
._dsdb
_get
_wellknown
_dn
(self
, nc_root
, wkguid
)
914 self
.hash_well_known
[str(nc_root
)] = {}
915 h_nc
= self
.hash_well_known
[str(nc_root
)]
919 def set_minPwdAge(self
, value
):
921 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
922 m
["minPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdAge")
925 def get_minPwdAge(self
):
926 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdAge"])
929 elif not "minPwdAge" in res
[0]:
932 return res
[0]["minPwdAge"][0]
934 def set_maxPwdAge(self
, value
):
936 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
937 m
["maxPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "maxPwdAge")
941 def get_maxPwdAge(self
):
942 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["maxPwdAge"])
945 elif not "maxPwdAge" in res
[0]:
948 return res
[0]["maxPwdAge"][0]
952 def set_minPwdLength(self
, value
):
954 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
955 m
["minPwdLength"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdLength")
958 def get_minPwdLength(self
):
959 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdLength"])
962 elif not "minPwdLength" in res
[0]:
965 return res
[0]["minPwdLength"][0]
967 def set_pwdProperties(self
, value
):
969 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
970 m
["pwdProperties"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "pwdProperties")
973 def get_pwdProperties(self
):
974 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["pwdProperties"])
977 elif not "pwdProperties" in res
[0]:
980 return res
[0]["pwdProperties"][0]
982 def set_dsheuristics(self
, dsheuristics
):
984 m
.dn
= ldb
.Dn(self
, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
985 % self
.get_config_basedn().get_linearized())
986 if dsheuristics
is not None:
987 m
["dSHeuristics"] = ldb
.MessageElement(dsheuristics
,
988 ldb
.FLAG_MOD_REPLACE
, "dSHeuristics")
990 m
["dSHeuristics"] = ldb
.MessageElement([], ldb
.FLAG_MOD_DELETE
,
994 def get_dsheuristics(self
):
995 res
= self
.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
996 % self
.get_config_basedn().get_linearized(),
997 scope
=ldb
.SCOPE_BASE
, attrs
=["dSHeuristics"])
1000 elif "dSHeuristics" in res
[0]:
1001 dsheuristics
= res
[0]["dSHeuristics"][0]
1007 def create_ou(self
, ou_dn
, description
=None, name
=None, sd
=None):
1008 """Creates an organizationalUnit object
1009 :param ou_dn: dn of the new object
1010 :param description: description attribute
1011 :param name: name atttribute
1012 :param sd: security descriptor of the object, can be
1013 an SDDL string or security.descriptor type
1016 "objectClass": "organizationalUnit"}
1019 m
["description"] = description
1024 m
["nTSecurityDescriptor"] = ndr_pack(sd
)
1027 def sequence_number(self
, seq_type
):
1028 """Returns the value of the sequence number according to the requested type
1029 :param seq_type: type of sequence number
1031 self
.transaction_start()
1033 seq
= super(SamDB
, self
).sequence_number(seq_type
)
1035 self
.transaction_cancel()
1038 self
.transaction_commit()
1041 def get_dsServiceName(self
):
1042 '''get the NTDS DN from the rootDSE'''
1043 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
1044 return res
[0]["dsServiceName"][0]
1046 def get_serverName(self
):
1047 '''get the server DN from the rootDSE'''
1048 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["serverName"])
1049 return res
[0]["serverName"][0]
1051 def dns_lookup(self
, dns_name
, dns_partition
=None):
1052 '''Do a DNS lookup in the database, returns the NDR database structures'''
1053 if dns_partition
is None:
1054 return dsdb_dns
.lookup(self
, dns_name
)
1056 return dsdb_dns
.lookup(self
, dns_name
,
1057 dns_partition
=dns_partition
)
1059 def dns_extract(self
, el
):
1060 '''Return the NDR database structures from a dnsRecord element'''
1061 return dsdb_dns
.extract(self
, el
)
1063 def dns_replace(self
, dns_name
, new_records
):
1064 '''Do a DNS modification on the database, sets the NDR database
1065 structures on a DNS name
1067 return dsdb_dns
.replace(self
, dns_name
, new_records
)
1069 def dns_replace_by_dn(self
, dn
, new_records
):
1070 '''Do a DNS modification on the database, sets the NDR database
1071 structures on a LDB DN
1073 This routine is important because if the last record on the DN
1074 is removed, this routine will put a tombstone in the record.
1076 return dsdb_dns
.replace_by_dn(self
, dn
, new_records
)
1078 def garbage_collect_tombstones(self
, dn
, current_time
,
1079 tombstone_lifetime
=None):
1080 '''garbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
1081 -> (num_objects_expunged, num_links_expunged)'''
1084 if tombstone_lifetime
is None:
1085 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1088 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1092 def create_own_rid_set(self
):
1093 '''create a RID set for this DSA'''
1094 return dsdb
._dsdb
_create
_own
_rid
_set
(self
)
1096 def allocate_rid(self
):
1097 '''return a new RID from the RID Pool on this DSA'''
1098 return dsdb
._dsdb
_allocate
_rid
(self
)
1100 def normalize_dn_in_domain(self
, dn
):
1101 '''return a new DN expanded by adding the domain DN
1103 If the dn is already a child of the domain DN, just
1106 :param dn: relative dn
1108 domain_dn
= ldb
.Dn(self
, self
.domain_dn())
1110 if isinstance(dn
, ldb
.Dn
):
1113 full_dn
= ldb
.Dn(self
, dn
)
1114 if not full_dn
.is_child_of(domain_dn
):
1115 full_dn
.add_base(domain_dn
)