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
.compat
import binary_type
37 from samba
.compat
import get_bytes
38 from samba
.dcerpc
import security
40 __docformat__
= "restructuredText"
43 def get_default_backend_store():
47 class SamDB(samba
.Ldb
):
48 """The SAM database."""
53 def __init__(self
, url
=None, lp
=None, modules_dir
=None, session_info
=None,
54 credentials
=None, flags
=ldb
.FLG_DONT_CREATE_DB
,
55 options
=None, global_schema
=True,
56 auto_connect
=True, am_rodc
=None):
60 elif url
is None and lp
is not None:
65 super(SamDB
, self
).__init
__(url
=url
, lp
=lp
, modules_dir
=modules_dir
,
66 session_info
=session_info
, credentials
=credentials
, flags
=flags
,
70 dsdb
._dsdb
_set
_global
_schema
(self
)
72 if am_rodc
is not None:
73 dsdb
._dsdb
_set
_am
_rodc
(self
, am_rodc
)
75 def connect(self
, url
=None, flags
=0, options
=None):
76 '''connect to the database'''
77 if self
.lp
is not None and not os
.path
.exists(url
):
78 url
= self
.lp
.private_path(url
)
81 super(SamDB
, self
).connect(url
=url
, flags
=flags
,
85 '''return True if we are an RODC'''
86 return dsdb
._am
_rodc
(self
)
89 '''return True if we are an PDC emulator'''
90 return dsdb
._am
_pdc
(self
)
93 '''return the domain DN'''
94 return str(self
.get_default_basedn())
97 '''return the schema partition dn'''
98 return str(self
.get_schema_basedn())
100 def disable_account(self
, search_filter
):
101 """Disables an account
103 :param search_filter: LDAP filter to find the user (eg
107 flags
= samba
.dsdb
.UF_ACCOUNTDISABLE
108 self
.toggle_userAccountFlags(search_filter
, flags
, on
=True)
110 def enable_account(self
, search_filter
):
111 """Enables an account
113 :param search_filter: LDAP filter to find the user (eg
117 flags
= samba
.dsdb
.UF_ACCOUNTDISABLE | samba
.dsdb
.UF_PASSWD_NOTREQD
118 self
.toggle_userAccountFlags(search_filter
, flags
, on
=False)
120 def toggle_userAccountFlags(self
, search_filter
, flags
, flags_str
=None,
121 on
=True, strict
=False):
122 """Toggle_userAccountFlags
124 :param search_filter: LDAP filter to find the user (eg
126 :param flags: samba.dsdb.UF_* flags
127 :param on: on=True (default) => set, on=False => unset
128 :param strict: strict=False (default) ignore if no action is needed
129 strict=True raises an Exception if...
131 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
132 expression
=search_filter
, attrs
=["userAccountControl"])
134 raise Exception("Unable to find account where '%s'" % search_filter
)
135 assert(len(res
) == 1)
136 account_dn
= res
[0].dn
138 old_uac
= int(res
[0]["userAccountControl"][0])
140 if strict
and (old_uac
& flags
):
141 error
= "Account flag(s) '%s' already set" % flags_str
142 raise Exception(error
)
144 new_uac
= old_uac | flags
146 if strict
and not (old_uac
& flags
):
147 error
= "Account flag(s) '%s' already unset" % flags_str
148 raise Exception(error
)
150 new_uac
= old_uac
& ~flags
152 if old_uac
== new_uac
:
158 delete: userAccountControl
159 userAccountControl: %u
160 add: userAccountControl
161 userAccountControl: %u
162 """ % (account_dn
, old_uac
, new_uac
)
163 self
.modify_ldif(mod
)
165 def force_password_change_at_next_login(self
, search_filter
):
166 """Forces a password change at next login
168 :param search_filter: LDAP filter to find the user (eg
171 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
172 expression
=search_filter
, attrs
=[])
174 raise Exception('Unable to find user "%s"' % search_filter
)
175 assert(len(res
) == 1)
184 self
.modify_ldif(mod
)
186 def newgroup(self
, groupname
, groupou
=None, grouptype
=None,
187 description
=None, mailaddress
=None, notes
=None, sd
=None,
188 gidnumber
=None, nisdomain
=None):
189 """Adds a new group with additional parameters
191 :param groupname: Name of the new group
192 :param grouptype: Type of the new group
193 :param description: Description of the new group
194 :param mailaddress: Email address of the new group
195 :param notes: Notes of the new group
196 :param gidnumber: GID Number of the new group
197 :param nisdomain: NIS Domain Name of the new group
198 :param sd: security descriptor of the object
201 group_dn
= "CN=%s,%s,%s" % (groupname
, (groupou
or "CN=Users"), self
.domain_dn())
203 # The new user record. Note the reliance on the SAMLDB module which
204 # fills in the default information
205 ldbmessage
= {"dn": group_dn
,
206 "sAMAccountName": groupname
,
207 "objectClass": "group"}
209 if grouptype
is not None:
210 ldbmessage
["groupType"] = normalise_int32(grouptype
)
212 if description
is not None:
213 ldbmessage
["description"] = description
215 if mailaddress
is not None:
216 ldbmessage
["mail"] = mailaddress
218 if notes
is not None:
219 ldbmessage
["info"] = notes
221 if gidnumber
is not None:
222 ldbmessage
["gidNumber"] = normalise_int32(gidnumber
)
224 if nisdomain
is not None:
225 ldbmessage
["msSFU30Name"] = groupname
226 ldbmessage
["msSFU30NisDomain"] = nisdomain
229 ldbmessage
["nTSecurityDescriptor"] = ndr_pack(sd
)
233 def deletegroup(self
, groupname
):
236 :param groupname: Name of the target group
239 groupfilter
= "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb
.binary_encode(groupname
), "CN=Group,CN=Schema,CN=Configuration", self
.domain_dn())
240 self
.transaction_start()
242 targetgroup
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
243 expression
=groupfilter
, attrs
=[])
244 if len(targetgroup
) == 0:
245 raise Exception('Unable to find group "%s"' % groupname
)
246 assert(len(targetgroup
) == 1)
247 self
.delete(targetgroup
[0].dn
)
249 self
.transaction_cancel()
252 self
.transaction_commit()
254 def group_member_filter(self
, member
, member_types
):
257 if 'user' in member_types
:
258 filter += ('(&(sAMAccountName=%s)(objectclass=user))' %
259 ldb
.binary_encode(member
))
260 if 'group' in member_types
:
261 filter += ('(&(sAMAccountName=%s)(objectclass=group))' %
262 ldb
.binary_encode(member
))
263 if 'computer' in member_types
:
264 samaccountname
= member
265 if member
[-1] != '$':
266 samaccountname
= "%s$" % member
267 filter += ('(&(samAccountType=%d)'
268 '(!(objectCategory=msDS-ManagedServiceAccount))'
269 '(sAMAccountName=%s))' %
270 (dsdb
.ATYPE_WORKSTATION_TRUST
,
271 ldb
.binary_encode(samaccountname
)))
272 if 'serviceaccount' in member_types
:
273 samaccountname
= member
274 if member
[-1] != '$':
275 samaccountname
= "%s$" % member
276 filter += ('(&(samAccountType=%d)'
277 '(objectCategory=msDS-ManagedServiceAccount)'
278 '(sAMAccountName=%s))' %
279 (dsdb
.ATYPE_WORKSTATION_TRUST
,
280 ldb
.binary_encode(samaccountname
)))
281 if 'contact' in member_types
:
282 filter += ('(&(objectCategory=Person)(!(objectSid=*))(name=%s))' %
283 ldb
.binary_encode(member
))
285 filter = "(|%s)" % filter
289 def add_remove_group_members(self
, groupname
, members
,
290 add_members_operation
=True,
291 member_types
=[ 'user', 'group' ]):
292 """Adds or removes group members
294 :param groupname: Name of the target group
295 :param members: list of group members
296 :param add_members_operation: Defines if its an add or remove
300 groupfilter
= "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (
301 ldb
.binary_encode(groupname
), "CN=Group,CN=Schema,CN=Configuration", self
.domain_dn())
303 self
.transaction_start()
305 targetgroup
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
306 expression
=groupfilter
, attrs
=['member'])
307 if len(targetgroup
) == 0:
308 raise Exception('Unable to find group "%s"' % groupname
)
309 assert(len(targetgroup
) == 1)
313 addtargettogroup
= """
316 """ % (str(targetgroup
[0].dn
))
318 for member
in members
:
319 filter = self
.group_member_filter(member
, member_types
)
322 membersid
= security
.dom_sid(member
)
323 except TypeError as e
:
326 if membersid
is not None:
327 filter = '(objectSid=%s)' % str(membersid
)
328 dn_str
= "<SID=%s>" % str(membersid
)
329 foreign_msg
= ldb
.Message()
330 foreign_msg
.dn
= ldb
.Dn(self
, dn_str
)
332 targetmember
= self
.search(base
=self
.domain_dn(),
333 scope
=ldb
.SCOPE_SUBTREE
,
334 expression
="%s" % filter,
337 if len(targetmember
) > 1:
339 for msg
in targetmember
:
340 memberlist_str
+= "%s\n" % msg
.get("dn")
341 raise Exception('Found multiple results for "%s":\n%s' %
342 (member
, memberlist_str
))
343 if len(targetmember
) == 0 and foreign_msg
is not None:
344 targetmember
= [foreign_msg
]
345 if len(targetmember
) != 1:
346 raise Exception('Unable to find "%s". Operation cancelled.' % member
)
347 targetmember_dn
= targetmember
[0].dn
.extended_str(1)
348 if add_members_operation
is True and (targetgroup
[0].get('member') is None or get_bytes(targetmember_dn
) not in [str(x
) for x
in targetgroup
[0]['member']]):
350 addtargettogroup
+= """add: member
352 """ % (str(targetmember_dn
))
354 elif add_members_operation
is False and (targetgroup
[0].get('member') is not None and get_bytes(targetmember_dn
) in targetgroup
[0]['member']):
356 addtargettogroup
+= """delete: member
358 """ % (str(targetmember_dn
))
361 self
.modify_ldif(addtargettogroup
)
364 self
.transaction_cancel()
367 self
.transaction_commit()
369 def newuser(self
, username
, password
,
370 force_password_change_at_next_login_req
=False,
371 useusernameascn
=False, userou
=None, surname
=None, givenname
=None,
372 initials
=None, profilepath
=None, scriptpath
=None, homedrive
=None,
373 homedirectory
=None, jobtitle
=None, department
=None, company
=None,
374 description
=None, mailaddress
=None, internetaddress
=None,
375 telephonenumber
=None, physicaldeliveryoffice
=None, sd
=None,
376 setpassword
=True, uidnumber
=None, gidnumber
=None, gecos
=None,
377 loginshell
=None, uid
=None, nisdomain
=None, unixhome
=None,
378 smartcard_required
=False):
379 """Adds a new user with additional parameters
381 :param username: Name of the new user
382 :param password: Password for the new user
383 :param force_password_change_at_next_login_req: Force password change
384 :param useusernameascn: Use username as cn rather that firstname +
386 :param userou: Object container (without domainDN postfix) for new user
387 :param surname: Surname of the new user
388 :param givenname: First name of the new user
389 :param initials: Initials of the new user
390 :param profilepath: Profile path of the new user
391 :param scriptpath: Logon script path of the new user
392 :param homedrive: Home drive of the new user
393 :param homedirectory: Home directory of the new user
394 :param jobtitle: Job title of the new user
395 :param department: Department of the new user
396 :param company: Company of the new user
397 :param description: of the new user
398 :param mailaddress: Email address of the new user
399 :param internetaddress: Home page of the new user
400 :param telephonenumber: Phone number of the new user
401 :param physicaldeliveryoffice: Office location of the new user
402 :param sd: security descriptor of the object
403 :param setpassword: optionally disable password reset
404 :param uidnumber: RFC2307 Unix numeric UID of the new user
405 :param gidnumber: RFC2307 Unix primary GID of the new user
406 :param gecos: RFC2307 Unix GECOS field of the new user
407 :param loginshell: RFC2307 Unix login shell of the new user
408 :param uid: RFC2307 Unix username of the new user
409 :param nisdomain: RFC2307 Unix NIS domain of the new user
410 :param unixhome: RFC2307 Unix home directory of the new user
411 :param smartcard_required: set the UF_SMARTCARD_REQUIRED bit of the new user
415 if givenname
is not None:
416 displayname
+= givenname
418 if initials
is not None:
419 displayname
+= ' %s.' % initials
421 if surname
is not None:
422 displayname
+= ' %s' % surname
425 if useusernameascn
is None and displayname
!= "":
428 user_dn
= "CN=%s,%s,%s" % (cn
, (userou
or "CN=Users"), self
.domain_dn())
430 dnsdomain
= ldb
.Dn(self
, self
.domain_dn()).canonical_str().replace("/", "")
431 user_principal_name
= "%s@%s" % (username
, dnsdomain
)
432 # The new user record. Note the reliance on the SAMLDB module which
433 # fills in the default information
434 ldbmessage
= {"dn": user_dn
,
435 "sAMAccountName": username
,
436 "userPrincipalName": user_principal_name
,
437 "objectClass": "user"}
439 if smartcard_required
:
440 ldbmessage
["userAccountControl"] = str(dsdb
.UF_NORMAL_ACCOUNT |
441 dsdb
.UF_SMARTCARD_REQUIRED
)
444 if surname
is not None:
445 ldbmessage
["sn"] = surname
447 if givenname
is not None:
448 ldbmessage
["givenName"] = givenname
450 if displayname
!= "":
451 ldbmessage
["displayName"] = displayname
452 ldbmessage
["name"] = displayname
454 if initials
is not None:
455 ldbmessage
["initials"] = '%s.' % initials
457 if profilepath
is not None:
458 ldbmessage
["profilePath"] = profilepath
460 if scriptpath
is not None:
461 ldbmessage
["scriptPath"] = scriptpath
463 if homedrive
is not None:
464 ldbmessage
["homeDrive"] = homedrive
466 if homedirectory
is not None:
467 ldbmessage
["homeDirectory"] = homedirectory
469 if jobtitle
is not None:
470 ldbmessage
["title"] = jobtitle
472 if department
is not None:
473 ldbmessage
["department"] = department
475 if company
is not None:
476 ldbmessage
["company"] = company
478 if description
is not None:
479 ldbmessage
["description"] = description
481 if mailaddress
is not None:
482 ldbmessage
["mail"] = mailaddress
484 if internetaddress
is not None:
485 ldbmessage
["wWWHomePage"] = internetaddress
487 if telephonenumber
is not None:
488 ldbmessage
["telephoneNumber"] = telephonenumber
490 if physicaldeliveryoffice
is not None:
491 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
494 ldbmessage
["nTSecurityDescriptor"] = ndr_pack(sd
)
497 if any(map(lambda b
: b
is not None, (uid
, uidnumber
, gidnumber
, gecos
,
498 loginshell
, nisdomain
, unixhome
))):
499 ldbmessage2
= ldb
.Message()
500 ldbmessage2
.dn
= ldb
.Dn(self
, user_dn
)
502 ldbmessage2
["uid"] = ldb
.MessageElement(str(uid
), ldb
.FLAG_MOD_REPLACE
, 'uid')
503 if uidnumber
is not None:
504 ldbmessage2
["uidNumber"] = ldb
.MessageElement(str(uidnumber
), ldb
.FLAG_MOD_REPLACE
, 'uidNumber')
505 if gidnumber
is not None:
506 ldbmessage2
["gidNumber"] = ldb
.MessageElement(str(gidnumber
), ldb
.FLAG_MOD_REPLACE
, 'gidNumber')
507 if gecos
is not None:
508 ldbmessage2
["gecos"] = ldb
.MessageElement(str(gecos
), ldb
.FLAG_MOD_REPLACE
, 'gecos')
509 if loginshell
is not None:
510 ldbmessage2
["loginShell"] = ldb
.MessageElement(str(loginshell
), ldb
.FLAG_MOD_REPLACE
, 'loginShell')
511 if unixhome
is not None:
512 ldbmessage2
["unixHomeDirectory"] = ldb
.MessageElement(
513 str(unixhome
), ldb
.FLAG_MOD_REPLACE
, 'unixHomeDirectory')
514 if nisdomain
is not None:
515 ldbmessage2
["msSFU30NisDomain"] = ldb
.MessageElement(
516 str(nisdomain
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30NisDomain')
517 ldbmessage2
["msSFU30Name"] = ldb
.MessageElement(
518 str(username
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30Name')
519 ldbmessage2
["unixUserPassword"] = ldb
.MessageElement(
520 'ABCD!efgh12345$67890', ldb
.FLAG_MOD_REPLACE
,
523 self
.transaction_start()
527 self
.modify(ldbmessage2
)
529 # Sets the password for it
531 self
.setpassword(("(distinguishedName=%s)" %
532 ldb
.binary_encode(user_dn
)),
534 force_password_change_at_next_login_req
)
536 self
.transaction_cancel()
539 self
.transaction_commit()
542 fullcontactname
=None,
553 internetaddress
=None,
554 telephonenumber
=None,
556 physicaldeliveryoffice
=None):
557 """Adds a new contact with additional parameters
559 :param fullcontactname: Optional full name of the new contact
560 :param ou: Object container for new contact
561 :param surname: Surname of the new contact
562 :param givenname: First name of the new contact
563 :param initials: Initials of the new contact
564 :param displayname: displayName of the new contact
565 :param jobtitle: Job title of the new contact
566 :param department: Department of the new contact
567 :param company: Company of the new contact
568 :param description: Description of the new contact
569 :param mailaddress: Email address of the new contact
570 :param internetaddress: Home page of the new contact
571 :param telephonenumber: Phone number of the new contact
572 :param mobilenumber: Primary mobile number of the new contact
573 :param physicaldeliveryoffice: Office location of the new contact
576 # Prepare the contact name like the RSAT, using the name parts.
578 if givenname
is not None:
581 if initials
is not None:
582 cn
+= ' %s.' % initials
584 if surname
is not None:
585 cn
+= ' %s' % surname
587 # Use the specified fullcontactname instead of the previously prepared
588 # contact name, if it is specified.
589 # This is similar to the "Full name" value of the RSAT.
590 if fullcontactname
is not None:
593 if fullcontactname
is None and cn
== "":
594 raise Exception('No name for contact specified')
596 contactcontainer_dn
= self
.domain_dn()
598 contactcontainer_dn
= self
.normalize_dn_in_domain(ou
)
600 contact_dn
= "CN=%s,%s" % (cn
, contactcontainer_dn
)
602 ldbmessage
= {"dn": contact_dn
,
603 "objectClass": "contact",
606 if surname
is not None:
607 ldbmessage
["sn"] = surname
609 if givenname
is not None:
610 ldbmessage
["givenName"] = givenname
612 if displayname
is not None:
613 ldbmessage
["displayName"] = displayname
615 if initials
is not None:
616 ldbmessage
["initials"] = '%s.' % initials
618 if jobtitle
is not None:
619 ldbmessage
["title"] = jobtitle
621 if department
is not None:
622 ldbmessage
["department"] = department
624 if company
is not None:
625 ldbmessage
["company"] = company
627 if description
is not None:
628 ldbmessage
["description"] = description
630 if mailaddress
is not None:
631 ldbmessage
["mail"] = mailaddress
633 if internetaddress
is not None:
634 ldbmessage
["wWWHomePage"] = internetaddress
636 if telephonenumber
is not None:
637 ldbmessage
["telephoneNumber"] = telephonenumber
639 if mobilenumber
is not None:
640 ldbmessage
["mobile"] = mobilenumber
642 if physicaldeliveryoffice
is not None:
643 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
649 def newcomputer(self
, computername
, computerou
=None, description
=None,
650 prepare_oldjoin
=False, ip_address_list
=None,
651 service_principal_name_list
=None):
652 """Adds a new user with additional parameters
654 :param computername: Name of the new computer
655 :param computerou: Object container for new computer
656 :param description: Description of the new computer
657 :param prepare_oldjoin: Preset computer password for oldjoin mechanism
658 :param ip_address_list: ip address list for DNS A or AAAA record
659 :param service_principal_name_list: string list of servicePincipalName
662 cn
= re
.sub(r
"\$$", "", computername
)
664 raise Exception('Illegal computername "%s"' % computername
)
665 samaccountname
= "%s$" % cn
667 computercontainer_dn
= "CN=Computers,%s" % self
.domain_dn()
669 computercontainer_dn
= self
.normalize_dn_in_domain(computerou
)
671 computer_dn
= "CN=%s,%s" % (cn
, computercontainer_dn
)
673 ldbmessage
= {"dn": computer_dn
,
674 "sAMAccountName": samaccountname
,
675 "objectClass": "computer",
678 if description
is not None:
679 ldbmessage
["description"] = description
681 if service_principal_name_list
:
682 ldbmessage
["servicePrincipalName"] = service_principal_name_list
684 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
685 dsdb
.UF_ACCOUNTDISABLE
)
687 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT
)
688 ldbmessage
["userAccountControl"] = accountcontrol
691 ldbmessage
['dNSHostName'] = '{}.{}'.format(
692 cn
, self
.domain_dns_name())
694 self
.transaction_start()
699 password
= cn
.lower()
700 self
.setpassword(("(distinguishedName=%s)" %
701 ldb
.binary_encode(computer_dn
)),
704 self
.transaction_cancel()
707 self
.transaction_commit()
709 def deleteuser(self
, username
):
712 :param username: Name of the target user
715 filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb
.binary_encode(username
), "CN=Person,CN=Schema,CN=Configuration", self
.domain_dn())
716 self
.transaction_start()
718 target
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
719 expression
=filter, attrs
=[])
721 raise Exception('Unable to find user "%s"' % username
)
722 assert(len(target
) == 1)
723 self
.delete(target
[0].dn
)
725 self
.transaction_cancel()
728 self
.transaction_commit()
730 def setpassword(self
, search_filter
, password
,
731 force_change_at_next_login
=False, username
=None):
732 """Sets the password for a user
734 :param search_filter: LDAP filter to find the user (eg
736 :param password: Password for the user
737 :param force_change_at_next_login: Force password change
739 self
.transaction_start()
741 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
742 expression
=search_filter
, attrs
=[])
744 raise Exception('Unable to find user "%s"' % (username
or search_filter
))
746 raise Exception('Matched %u multiple users with filter "%s"' % (len(res
), search_filter
))
748 if not isinstance(password
, text_type
):
749 pw
= password
.decode('utf-8')
752 pw
= ('"' + pw
+ '"').encode('utf-16-le')
758 """ % (user_dn
, base64
.b64encode(pw
).decode('utf-8'))
760 self
.modify_ldif(setpw
)
762 if force_change_at_next_login
:
763 self
.force_password_change_at_next_login(
764 "(distinguishedName=" + str(user_dn
) + ")")
766 # modify the userAccountControl to remove the disabled bit
767 self
.enable_account(search_filter
)
769 self
.transaction_cancel()
772 self
.transaction_commit()
774 def setexpiry(self
, search_filter
, expiry_seconds
, no_expiry_req
=False):
775 """Sets the account expiry for a user
777 :param search_filter: LDAP filter to find the user (eg
779 :param expiry_seconds: expiry time from now in seconds
780 :param no_expiry_req: if set, then don't expire password
782 self
.transaction_start()
784 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
785 expression
=search_filter
,
786 attrs
=["userAccountControl", "accountExpires"])
788 raise Exception('Unable to find user "%s"' % search_filter
)
789 assert(len(res
) == 1)
792 userAccountControl
= int(res
[0]["userAccountControl"][0])
793 accountExpires
= int(res
[0]["accountExpires"][0])
795 userAccountControl
= userAccountControl |
0x10000
798 userAccountControl
= userAccountControl
& ~
0x10000
799 accountExpires
= samba
.unix2nttime(expiry_seconds
+ int(time
.time()))
804 replace: userAccountControl
805 userAccountControl: %u
806 replace: accountExpires
808 """ % (user_dn
, userAccountControl
, accountExpires
)
810 self
.modify_ldif(setexp
)
812 self
.transaction_cancel()
815 self
.transaction_commit()
817 def set_domain_sid(self
, sid
):
818 """Change the domain SID used by this LDB.
820 :param sid: The new domain sid to use.
822 dsdb
._samdb
_set
_domain
_sid
(self
, sid
)
824 def get_domain_sid(self
):
825 """Read the domain SID used by this LDB. """
826 return dsdb
._samdb
_get
_domain
_sid
(self
)
828 domain_sid
= property(get_domain_sid
, set_domain_sid
,
829 doc
="SID for the domain")
831 def set_invocation_id(self
, invocation_id
):
832 """Set the invocation id for this SamDB handle.
834 :param invocation_id: GUID of the invocation id.
836 dsdb
._dsdb
_set
_ntds
_invocation
_id
(self
, invocation_id
)
838 def get_invocation_id(self
):
839 """Get the invocation_id id"""
840 return dsdb
._samdb
_ntds
_invocation
_id
(self
)
842 invocation_id
= property(get_invocation_id
, set_invocation_id
,
843 doc
="Invocation ID GUID")
845 def get_oid_from_attid(self
, attid
):
846 return dsdb
._dsdb
_get
_oid
_from
_attid
(self
, attid
)
848 def get_attid_from_lDAPDisplayName(self
, ldap_display_name
,
850 '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
851 return dsdb
._dsdb
_get
_attid
_from
_lDAPDisplayName
(self
,
852 ldap_display_name
, is_schema_nc
)
854 def get_syntax_oid_from_lDAPDisplayName(self
, ldap_display_name
):
855 '''return the syntax OID for a LDAP attribute as a string'''
856 return dsdb
._dsdb
_get
_syntax
_oid
_from
_lDAPDisplayName
(self
, ldap_display_name
)
858 def get_systemFlags_from_lDAPDisplayName(self
, ldap_display_name
):
859 '''return the systemFlags for a LDAP attribute as a integer'''
860 return dsdb
._dsdb
_get
_systemFlags
_from
_lDAPDisplayName
(self
, ldap_display_name
)
862 def get_linkId_from_lDAPDisplayName(self
, ldap_display_name
):
863 '''return the linkID for a LDAP attribute as a integer'''
864 return dsdb
._dsdb
_get
_linkId
_from
_lDAPDisplayName
(self
, ldap_display_name
)
866 def get_lDAPDisplayName_by_attid(self
, attid
):
867 '''return the lDAPDisplayName from an integer DRS attribute ID'''
868 return dsdb
._dsdb
_get
_lDAPDisplayName
_by
_attid
(self
, attid
)
870 def get_backlink_from_lDAPDisplayName(self
, ldap_display_name
):
871 '''return the attribute name of the corresponding backlink from the name
872 of a forward link attribute. If there is no backlink return None'''
873 return dsdb
._dsdb
_get
_backlink
_from
_lDAPDisplayName
(self
, ldap_display_name
)
875 def set_ntds_settings_dn(self
, ntds_settings_dn
):
876 """Set the NTDS Settings DN, as would be returned on the dsServiceName
879 This allows the DN to be set before the database fully exists
881 :param ntds_settings_dn: The new DN to use
883 dsdb
._samdb
_set
_ntds
_settings
_dn
(self
, ntds_settings_dn
)
885 def get_ntds_GUID(self
):
886 """Get the NTDS objectGUID"""
887 return dsdb
._samdb
_ntds
_objectGUID
(self
)
889 def server_site_name(self
):
890 """Get the server site name"""
891 return dsdb
._samdb
_server
_site
_name
(self
)
893 def host_dns_name(self
):
894 """return the DNS name of this host"""
895 res
= self
.search(base
='', scope
=ldb
.SCOPE_BASE
, attrs
=['dNSHostName'])
896 return str(res
[0]['dNSHostName'][0])
898 def domain_dns_name(self
):
899 """return the DNS name of the domain root"""
900 domain_dn
= self
.get_default_basedn()
901 return domain_dn
.canonical_str().split('/')[0]
903 def forest_dns_name(self
):
904 """return the DNS name of the forest root"""
905 forest_dn
= self
.get_root_basedn()
906 return forest_dn
.canonical_str().split('/')[0]
908 def load_partition_usn(self
, base_dn
):
909 return dsdb
._dsdb
_load
_partition
_usn
(self
, base_dn
)
911 def set_schema(self
, schema
, write_indices_and_attributes
=True):
912 self
.set_schema_from_ldb(schema
.ldb
, write_indices_and_attributes
=write_indices_and_attributes
)
914 def set_schema_from_ldb(self
, ldb_conn
, write_indices_and_attributes
=True):
915 dsdb
._dsdb
_set
_schema
_from
_ldb
(self
, ldb_conn
, write_indices_and_attributes
)
917 def set_schema_update_now(self
):
924 self
.modify_ldif(ldif
)
926 def dsdb_DsReplicaAttribute(self
, ldb
, ldap_display_name
, ldif_elements
):
927 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
928 return dsdb
._dsdb
_DsReplicaAttribute
(ldb
, ldap_display_name
, ldif_elements
)
930 def dsdb_normalise_attributes(self
, ldb
, ldap_display_name
, ldif_elements
):
931 '''normalise a list of attribute values'''
932 return dsdb
._dsdb
_normalise
_attributes
(ldb
, ldap_display_name
, ldif_elements
)
934 def get_attribute_from_attid(self
, attid
):
935 """ Get from an attid the associated attribute
937 :param attid: The attribute id for searched attribute
938 :return: The name of the attribute associated with this id
940 if len(self
.hash_oid_name
.keys()) == 0:
941 self
._populate
_oid
_attid
()
942 if self
.get_oid_from_attid(attid
) in self
.hash_oid_name
:
943 return self
.hash_oid_name
[self
.get_oid_from_attid(attid
)]
947 def _populate_oid_attid(self
):
948 """Populate the hash hash_oid_name.
950 This hash contains the oid of the attribute as a key and
951 its display name as a value
953 self
.hash_oid_name
= {}
954 res
= self
.search(expression
="objectClass=attributeSchema",
955 controls
=["search_options:1:2"],
956 attrs
=["attributeID",
960 strDisplay
= str(e
.get("lDAPDisplayName"))
961 self
.hash_oid_name
[str(e
.get("attributeID"))] = strDisplay
963 def get_attribute_replmetadata_version(self
, dn
, att
):
964 """Get the version field trom the replPropertyMetaData for
967 :param dn: The on which we want to get the version
968 :param att: The name of the attribute
969 :return: The value of the version field in the replPropertyMetaData
970 for the given attribute. None if the attribute is not replicated
973 res
= self
.search(expression
="distinguishedName=%s" % dn
,
974 scope
=ldb
.SCOPE_SUBTREE
,
975 controls
=["search_options:1:2"],
976 attrs
=["replPropertyMetaData"])
980 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
981 res
[0]["replPropertyMetaData"][0])
983 if len(self
.hash_oid_name
.keys()) == 0:
984 self
._populate
_oid
_attid
()
986 # Search for Description
987 att_oid
= self
.get_oid_from_attid(o
.attid
)
988 if att_oid
in self
.hash_oid_name
and\
989 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
993 def set_attribute_replmetadata_version(self
, dn
, att
, value
,
994 addifnotexist
=False):
995 res
= self
.search(expression
="distinguishedName=%s" % dn
,
996 scope
=ldb
.SCOPE_SUBTREE
,
997 controls
=["search_options:1:2"],
998 attrs
=["replPropertyMetaData"])
1002 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
1003 res
[0]["replPropertyMetaData"][0])
1005 now
= samba
.unix2nttime(int(time
.time()))
1007 if len(self
.hash_oid_name
.keys()) == 0:
1008 self
._populate
_oid
_attid
()
1010 # Search for Description
1011 att_oid
= self
.get_oid_from_attid(o
.attid
)
1012 if att_oid
in self
.hash_oid_name
and\
1013 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
1015 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
1017 o
.originating_change_time
= now
1018 o
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
1019 o
.originating_usn
= seq
1022 if not found
and addifnotexist
and len(ctr
.array
) > 0:
1023 o2
= drsblobs
.replPropertyMetaData1()
1025 att_oid
= self
.get_oid_from_attid(o2
.attid
)
1026 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
1028 o2
.originating_change_time
= now
1029 o2
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
1030 o2
.originating_usn
= seq
1035 ctr
.count
= ctr
.count
+ 1
1039 replBlob
= ndr_pack(repl
)
1042 msg
["replPropertyMetaData"] = \
1043 ldb
.MessageElement(replBlob
,
1044 ldb
.FLAG_MOD_REPLACE
,
1045 "replPropertyMetaData")
1046 self
.modify(msg
, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
1048 def write_prefixes_from_schema(self
):
1049 dsdb
._dsdb
_write
_prefixes
_from
_schema
_to
_ldb
(self
)
1051 def get_partitions_dn(self
):
1052 return dsdb
._dsdb
_get
_partitions
_dn
(self
)
1054 def get_nc_root(self
, dn
):
1055 return dsdb
._dsdb
_get
_nc
_root
(self
, dn
)
1057 def get_wellknown_dn(self
, nc_root
, wkguid
):
1058 h_nc
= self
.hash_well_known
.get(str(nc_root
))
1060 if h_nc
is not None:
1061 dn
= h_nc
.get(wkguid
)
1063 dn
= dsdb
._dsdb
_get
_wellknown
_dn
(self
, nc_root
, wkguid
)
1067 self
.hash_well_known
[str(nc_root
)] = {}
1068 h_nc
= self
.hash_well_known
[str(nc_root
)]
1072 def set_minPwdAge(self
, value
):
1073 if not isinstance(value
, binary_type
):
1074 value
= str(value
).encode('utf8')
1076 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1077 m
["minPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdAge")
1080 def get_minPwdAge(self
):
1081 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdAge"])
1084 elif "minPwdAge" not in res
[0]:
1087 return int(res
[0]["minPwdAge"][0])
1089 def set_maxPwdAge(self
, value
):
1090 if not isinstance(value
, binary_type
):
1091 value
= str(value
).encode('utf8')
1093 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1094 m
["maxPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "maxPwdAge")
1097 def get_maxPwdAge(self
):
1098 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["maxPwdAge"])
1101 elif "maxPwdAge" not in res
[0]:
1104 return int(res
[0]["maxPwdAge"][0])
1106 def set_minPwdLength(self
, value
):
1107 if not isinstance(value
, binary_type
):
1108 value
= str(value
).encode('utf8')
1110 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1111 m
["minPwdLength"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdLength")
1114 def get_minPwdLength(self
):
1115 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdLength"])
1118 elif "minPwdLength" not in res
[0]:
1121 return int(res
[0]["minPwdLength"][0])
1123 def set_pwdProperties(self
, value
):
1124 if not isinstance(value
, binary_type
):
1125 value
= str(value
).encode('utf8')
1127 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1128 m
["pwdProperties"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "pwdProperties")
1131 def get_pwdProperties(self
):
1132 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["pwdProperties"])
1135 elif "pwdProperties" not in res
[0]:
1138 return int(res
[0]["pwdProperties"][0])
1140 def set_dsheuristics(self
, dsheuristics
):
1142 m
.dn
= ldb
.Dn(self
, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
1143 % self
.get_config_basedn().get_linearized())
1144 if dsheuristics
is not None:
1145 m
["dSHeuristics"] = \
1146 ldb
.MessageElement(dsheuristics
,
1147 ldb
.FLAG_MOD_REPLACE
,
1150 m
["dSHeuristics"] = \
1151 ldb
.MessageElement([], ldb
.FLAG_MOD_DELETE
,
1155 def get_dsheuristics(self
):
1156 res
= self
.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
1157 % self
.get_config_basedn().get_linearized(),
1158 scope
=ldb
.SCOPE_BASE
, attrs
=["dSHeuristics"])
1161 elif "dSHeuristics" in res
[0]:
1162 dsheuristics
= res
[0]["dSHeuristics"][0]
1168 def create_ou(self
, ou_dn
, description
=None, name
=None, sd
=None):
1169 """Creates an organizationalUnit object
1170 :param ou_dn: dn of the new object
1171 :param description: description attribute
1172 :param name: name atttribute
1173 :param sd: security descriptor of the object, can be
1174 an SDDL string or security.descriptor type
1177 "objectClass": "organizationalUnit"}
1180 m
["description"] = description
1185 m
["nTSecurityDescriptor"] = ndr_pack(sd
)
1188 def sequence_number(self
, seq_type
):
1189 """Returns the value of the sequence number according to the requested type
1190 :param seq_type: type of sequence number
1192 self
.transaction_start()
1194 seq
= super(SamDB
, self
).sequence_number(seq_type
)
1196 self
.transaction_cancel()
1199 self
.transaction_commit()
1202 def get_dsServiceName(self
):
1203 '''get the NTDS DN from the rootDSE'''
1204 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
1205 return str(res
[0]["dsServiceName"][0])
1207 def get_serverName(self
):
1208 '''get the server DN from the rootDSE'''
1209 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["serverName"])
1210 return str(res
[0]["serverName"][0])
1212 def dns_lookup(self
, dns_name
, dns_partition
=None):
1213 '''Do a DNS lookup in the database, returns the NDR database structures'''
1214 if dns_partition
is None:
1215 return dsdb_dns
.lookup(self
, dns_name
)
1217 return dsdb_dns
.lookup(self
, dns_name
,
1218 dns_partition
=dns_partition
)
1220 def dns_extract(self
, el
):
1221 '''Return the NDR database structures from a dnsRecord element'''
1222 return dsdb_dns
.extract(self
, el
)
1224 def dns_replace(self
, dns_name
, new_records
):
1225 '''Do a DNS modification on the database, sets the NDR database
1226 structures on a DNS name
1228 return dsdb_dns
.replace(self
, dns_name
, new_records
)
1230 def dns_replace_by_dn(self
, dn
, new_records
):
1231 '''Do a DNS modification on the database, sets the NDR database
1232 structures on a LDB DN
1234 This routine is important because if the last record on the DN
1235 is removed, this routine will put a tombstone in the record.
1237 return dsdb_dns
.replace_by_dn(self
, dn
, new_records
)
1239 def garbage_collect_tombstones(self
, dn
, current_time
,
1240 tombstone_lifetime
=None):
1241 '''garbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
1242 -> (num_objects_expunged, num_links_expunged)'''
1244 if tombstone_lifetime
is None:
1245 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1248 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1252 def create_own_rid_set(self
):
1253 '''create a RID set for this DSA'''
1254 return dsdb
._dsdb
_create
_own
_rid
_set
(self
)
1256 def allocate_rid(self
):
1257 '''return a new RID from the RID Pool on this DSA'''
1258 return dsdb
._dsdb
_allocate
_rid
(self
)
1260 def normalize_dn_in_domain(self
, dn
):
1261 '''return a new DN expanded by adding the domain DN
1263 If the dn is already a child of the domain DN, just
1266 :param dn: relative dn
1268 domain_dn
= ldb
.Dn(self
, self
.domain_dn())
1270 if isinstance(dn
, ldb
.Dn
):
1273 full_dn
= ldb
.Dn(self
, dn
)
1274 if not full_dn
.is_child_of(domain_dn
):
1275 full_dn
.add_base(domain_dn
)