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
))
264 filter = "(|%s)" % filter
268 def add_remove_group_members(self
, groupname
, members
,
269 add_members_operation
=True,
270 member_types
=[ 'user', 'group' ]):
271 """Adds or removes group members
273 :param groupname: Name of the target group
274 :param members: list of group members
275 :param add_members_operation: Defines if its an add or remove
279 groupfilter
= "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (
280 ldb
.binary_encode(groupname
), "CN=Group,CN=Schema,CN=Configuration", self
.domain_dn())
282 self
.transaction_start()
284 targetgroup
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
285 expression
=groupfilter
, attrs
=['member'])
286 if len(targetgroup
) == 0:
287 raise Exception('Unable to find group "%s"' % groupname
)
288 assert(len(targetgroup
) == 1)
292 addtargettogroup
= """
295 """ % (str(targetgroup
[0].dn
))
297 for member
in members
:
298 filter = self
.group_member_filter(member
, member_types
)
301 membersid
= security
.dom_sid(member
)
302 except TypeError as e
:
305 if membersid
is not None:
306 filter = '(objectSid=%s)' % str(membersid
)
307 dn_str
= "<SID=%s>" % str(membersid
)
308 foreign_msg
= ldb
.Message()
309 foreign_msg
.dn
= ldb
.Dn(self
, dn_str
)
311 targetmember
= self
.search(base
=self
.domain_dn(),
312 scope
=ldb
.SCOPE_SUBTREE
,
313 expression
="%s" % filter,
316 if len(targetmember
) == 0 and foreign_msg
is not None:
317 targetmember
= [foreign_msg
]
318 if len(targetmember
) != 1:
319 raise Exception('Unable to find "%s". Operation cancelled.' % member
)
320 targetmember_dn
= targetmember
[0].dn
.extended_str(1)
321 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']]):
323 addtargettogroup
+= """add: member
325 """ % (str(targetmember_dn
))
327 elif add_members_operation
is False and (targetgroup
[0].get('member') is not None and get_bytes(targetmember_dn
) in targetgroup
[0]['member']):
329 addtargettogroup
+= """delete: member
331 """ % (str(targetmember_dn
))
334 self
.modify_ldif(addtargettogroup
)
337 self
.transaction_cancel()
340 self
.transaction_commit()
342 def newuser(self
, username
, password
,
343 force_password_change_at_next_login_req
=False,
344 useusernameascn
=False, userou
=None, surname
=None, givenname
=None,
345 initials
=None, profilepath
=None, scriptpath
=None, homedrive
=None,
346 homedirectory
=None, jobtitle
=None, department
=None, company
=None,
347 description
=None, mailaddress
=None, internetaddress
=None,
348 telephonenumber
=None, physicaldeliveryoffice
=None, sd
=None,
349 setpassword
=True, uidnumber
=None, gidnumber
=None, gecos
=None,
350 loginshell
=None, uid
=None, nisdomain
=None, unixhome
=None,
351 smartcard_required
=False):
352 """Adds a new user with additional parameters
354 :param username: Name of the new user
355 :param password: Password for the new user
356 :param force_password_change_at_next_login_req: Force password change
357 :param useusernameascn: Use username as cn rather that firstname +
359 :param userou: Object container (without domainDN postfix) for new user
360 :param surname: Surname of the new user
361 :param givenname: First name of the new user
362 :param initials: Initials of the new user
363 :param profilepath: Profile path of the new user
364 :param scriptpath: Logon script path of the new user
365 :param homedrive: Home drive of the new user
366 :param homedirectory: Home directory of the new user
367 :param jobtitle: Job title of the new user
368 :param department: Department of the new user
369 :param company: Company of the new user
370 :param description: of the new user
371 :param mailaddress: Email address of the new user
372 :param internetaddress: Home page of the new user
373 :param telephonenumber: Phone number of the new user
374 :param physicaldeliveryoffice: Office location of the new user
375 :param sd: security descriptor of the object
376 :param setpassword: optionally disable password reset
377 :param uidnumber: RFC2307 Unix numeric UID of the new user
378 :param gidnumber: RFC2307 Unix primary GID of the new user
379 :param gecos: RFC2307 Unix GECOS field of the new user
380 :param loginshell: RFC2307 Unix login shell of the new user
381 :param uid: RFC2307 Unix username of the new user
382 :param nisdomain: RFC2307 Unix NIS domain of the new user
383 :param unixhome: RFC2307 Unix home directory of the new user
384 :param smartcard_required: set the UF_SMARTCARD_REQUIRED bit of the new user
388 if givenname
is not None:
389 displayname
+= givenname
391 if initials
is not None:
392 displayname
+= ' %s.' % initials
394 if surname
is not None:
395 displayname
+= ' %s' % surname
398 if useusernameascn
is None and displayname
!= "":
401 user_dn
= "CN=%s,%s,%s" % (cn
, (userou
or "CN=Users"), self
.domain_dn())
403 dnsdomain
= ldb
.Dn(self
, self
.domain_dn()).canonical_str().replace("/", "")
404 user_principal_name
= "%s@%s" % (username
, dnsdomain
)
405 # The new user record. Note the reliance on the SAMLDB module which
406 # fills in the default information
407 ldbmessage
= {"dn": user_dn
,
408 "sAMAccountName": username
,
409 "userPrincipalName": user_principal_name
,
410 "objectClass": "user"}
412 if smartcard_required
:
413 ldbmessage
["userAccountControl"] = str(dsdb
.UF_NORMAL_ACCOUNT |
414 dsdb
.UF_SMARTCARD_REQUIRED
)
417 if surname
is not None:
418 ldbmessage
["sn"] = surname
420 if givenname
is not None:
421 ldbmessage
["givenName"] = givenname
423 if displayname
!= "":
424 ldbmessage
["displayName"] = displayname
425 ldbmessage
["name"] = displayname
427 if initials
is not None:
428 ldbmessage
["initials"] = '%s.' % initials
430 if profilepath
is not None:
431 ldbmessage
["profilePath"] = profilepath
433 if scriptpath
is not None:
434 ldbmessage
["scriptPath"] = scriptpath
436 if homedrive
is not None:
437 ldbmessage
["homeDrive"] = homedrive
439 if homedirectory
is not None:
440 ldbmessage
["homeDirectory"] = homedirectory
442 if jobtitle
is not None:
443 ldbmessage
["title"] = jobtitle
445 if department
is not None:
446 ldbmessage
["department"] = department
448 if company
is not None:
449 ldbmessage
["company"] = company
451 if description
is not None:
452 ldbmessage
["description"] = description
454 if mailaddress
is not None:
455 ldbmessage
["mail"] = mailaddress
457 if internetaddress
is not None:
458 ldbmessage
["wWWHomePage"] = internetaddress
460 if telephonenumber
is not None:
461 ldbmessage
["telephoneNumber"] = telephonenumber
463 if physicaldeliveryoffice
is not None:
464 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
467 ldbmessage
["nTSecurityDescriptor"] = ndr_pack(sd
)
470 if any(map(lambda b
: b
is not None, (uid
, uidnumber
, gidnumber
, gecos
,
471 loginshell
, nisdomain
, unixhome
))):
472 ldbmessage2
= ldb
.Message()
473 ldbmessage2
.dn
= ldb
.Dn(self
, user_dn
)
475 ldbmessage2
["uid"] = ldb
.MessageElement(str(uid
), ldb
.FLAG_MOD_REPLACE
, 'uid')
476 if uidnumber
is not None:
477 ldbmessage2
["uidNumber"] = ldb
.MessageElement(str(uidnumber
), ldb
.FLAG_MOD_REPLACE
, 'uidNumber')
478 if gidnumber
is not None:
479 ldbmessage2
["gidNumber"] = ldb
.MessageElement(str(gidnumber
), ldb
.FLAG_MOD_REPLACE
, 'gidNumber')
480 if gecos
is not None:
481 ldbmessage2
["gecos"] = ldb
.MessageElement(str(gecos
), ldb
.FLAG_MOD_REPLACE
, 'gecos')
482 if loginshell
is not None:
483 ldbmessage2
["loginShell"] = ldb
.MessageElement(str(loginshell
), ldb
.FLAG_MOD_REPLACE
, 'loginShell')
484 if unixhome
is not None:
485 ldbmessage2
["unixHomeDirectory"] = ldb
.MessageElement(
486 str(unixhome
), ldb
.FLAG_MOD_REPLACE
, 'unixHomeDirectory')
487 if nisdomain
is not None:
488 ldbmessage2
["msSFU30NisDomain"] = ldb
.MessageElement(
489 str(nisdomain
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30NisDomain')
490 ldbmessage2
["msSFU30Name"] = ldb
.MessageElement(
491 str(username
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30Name')
492 ldbmessage2
["unixUserPassword"] = ldb
.MessageElement(
493 'ABCD!efgh12345$67890', ldb
.FLAG_MOD_REPLACE
,
496 self
.transaction_start()
500 self
.modify(ldbmessage2
)
502 # Sets the password for it
504 self
.setpassword(("(distinguishedName=%s)" %
505 ldb
.binary_encode(user_dn
)),
507 force_password_change_at_next_login_req
)
509 self
.transaction_cancel()
512 self
.transaction_commit()
515 fullcontactname
=None,
526 internetaddress
=None,
527 telephonenumber
=None,
529 physicaldeliveryoffice
=None):
530 """Adds a new contact with additional parameters
532 :param fullcontactname: Optional full name of the new contact
533 :param ou: Object container for new contact
534 :param surname: Surname of the new contact
535 :param givenname: First name of the new contact
536 :param initials: Initials of the new contact
537 :param displayname: displayName of the new contact
538 :param jobtitle: Job title of the new contact
539 :param department: Department of the new contact
540 :param company: Company of the new contact
541 :param description: Description of the new contact
542 :param mailaddress: Email address of the new contact
543 :param internetaddress: Home page of the new contact
544 :param telephonenumber: Phone number of the new contact
545 :param mobilenumber: Primary mobile number of the new contact
546 :param physicaldeliveryoffice: Office location of the new contact
549 # Prepare the contact name like the RSAT, using the name parts.
551 if givenname
is not None:
554 if initials
is not None:
555 cn
+= ' %s.' % initials
557 if surname
is not None:
558 cn
+= ' %s' % surname
560 # Use the specified fullcontactname instead of the previously prepared
561 # contact name, if it is specified.
562 # This is similar to the "Full name" value of the RSAT.
563 if fullcontactname
is not None:
566 if fullcontactname
is None and cn
== "":
567 raise Exception('No name for contact specified')
569 contactcontainer_dn
= self
.domain_dn()
571 contactcontainer_dn
= self
.normalize_dn_in_domain(ou
)
573 contact_dn
= "CN=%s,%s" % (cn
, contactcontainer_dn
)
575 ldbmessage
= {"dn": contact_dn
,
576 "objectClass": "contact",
579 if surname
is not None:
580 ldbmessage
["sn"] = surname
582 if givenname
is not None:
583 ldbmessage
["givenName"] = givenname
585 if displayname
is not None:
586 ldbmessage
["displayName"] = displayname
588 if initials
is not None:
589 ldbmessage
["initials"] = '%s.' % initials
591 if jobtitle
is not None:
592 ldbmessage
["title"] = jobtitle
594 if department
is not None:
595 ldbmessage
["department"] = department
597 if company
is not None:
598 ldbmessage
["company"] = company
600 if description
is not None:
601 ldbmessage
["description"] = description
603 if mailaddress
is not None:
604 ldbmessage
["mail"] = mailaddress
606 if internetaddress
is not None:
607 ldbmessage
["wWWHomePage"] = internetaddress
609 if telephonenumber
is not None:
610 ldbmessage
["telephoneNumber"] = telephonenumber
612 if mobilenumber
is not None:
613 ldbmessage
["mobile"] = mobilenumber
615 if physicaldeliveryoffice
is not None:
616 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
622 def newcomputer(self
, computername
, computerou
=None, description
=None,
623 prepare_oldjoin
=False, ip_address_list
=None,
624 service_principal_name_list
=None):
625 """Adds a new user with additional parameters
627 :param computername: Name of the new computer
628 :param computerou: Object container for new computer
629 :param description: Description of the new computer
630 :param prepare_oldjoin: Preset computer password for oldjoin mechanism
631 :param ip_address_list: ip address list for DNS A or AAAA record
632 :param service_principal_name_list: string list of servicePincipalName
635 cn
= re
.sub(r
"\$$", "", computername
)
637 raise Exception('Illegal computername "%s"' % computername
)
638 samaccountname
= "%s$" % cn
640 computercontainer_dn
= "CN=Computers,%s" % self
.domain_dn()
642 computercontainer_dn
= self
.normalize_dn_in_domain(computerou
)
644 computer_dn
= "CN=%s,%s" % (cn
, computercontainer_dn
)
646 ldbmessage
= {"dn": computer_dn
,
647 "sAMAccountName": samaccountname
,
648 "objectClass": "computer",
651 if description
is not None:
652 ldbmessage
["description"] = description
654 if service_principal_name_list
:
655 ldbmessage
["servicePrincipalName"] = service_principal_name_list
657 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
658 dsdb
.UF_ACCOUNTDISABLE
)
660 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT
)
661 ldbmessage
["userAccountControl"] = accountcontrol
664 ldbmessage
['dNSHostName'] = '{}.{}'.format(
665 cn
, self
.domain_dns_name())
667 self
.transaction_start()
672 password
= cn
.lower()
673 self
.setpassword(("(distinguishedName=%s)" %
674 ldb
.binary_encode(computer_dn
)),
677 self
.transaction_cancel()
680 self
.transaction_commit()
682 def deleteuser(self
, username
):
685 :param username: Name of the target user
688 filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb
.binary_encode(username
), "CN=Person,CN=Schema,CN=Configuration", self
.domain_dn())
689 self
.transaction_start()
691 target
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
692 expression
=filter, attrs
=[])
694 raise Exception('Unable to find user "%s"' % username
)
695 assert(len(target
) == 1)
696 self
.delete(target
[0].dn
)
698 self
.transaction_cancel()
701 self
.transaction_commit()
703 def setpassword(self
, search_filter
, password
,
704 force_change_at_next_login
=False, username
=None):
705 """Sets the password for a user
707 :param search_filter: LDAP filter to find the user (eg
709 :param password: Password for the user
710 :param force_change_at_next_login: Force password change
712 self
.transaction_start()
714 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
715 expression
=search_filter
, attrs
=[])
717 raise Exception('Unable to find user "%s"' % (username
or search_filter
))
719 raise Exception('Matched %u multiple users with filter "%s"' % (len(res
), search_filter
))
721 if not isinstance(password
, text_type
):
722 pw
= password
.decode('utf-8')
725 pw
= ('"' + pw
+ '"').encode('utf-16-le')
731 """ % (user_dn
, base64
.b64encode(pw
).decode('utf-8'))
733 self
.modify_ldif(setpw
)
735 if force_change_at_next_login
:
736 self
.force_password_change_at_next_login(
737 "(distinguishedName=" + str(user_dn
) + ")")
739 # modify the userAccountControl to remove the disabled bit
740 self
.enable_account(search_filter
)
742 self
.transaction_cancel()
745 self
.transaction_commit()
747 def setexpiry(self
, search_filter
, expiry_seconds
, no_expiry_req
=False):
748 """Sets the account expiry for a user
750 :param search_filter: LDAP filter to find the user (eg
752 :param expiry_seconds: expiry time from now in seconds
753 :param no_expiry_req: if set, then don't expire password
755 self
.transaction_start()
757 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
758 expression
=search_filter
,
759 attrs
=["userAccountControl", "accountExpires"])
761 raise Exception('Unable to find user "%s"' % search_filter
)
762 assert(len(res
) == 1)
765 userAccountControl
= int(res
[0]["userAccountControl"][0])
766 accountExpires
= int(res
[0]["accountExpires"][0])
768 userAccountControl
= userAccountControl |
0x10000
771 userAccountControl
= userAccountControl
& ~
0x10000
772 accountExpires
= samba
.unix2nttime(expiry_seconds
+ int(time
.time()))
777 replace: userAccountControl
778 userAccountControl: %u
779 replace: accountExpires
781 """ % (user_dn
, userAccountControl
, accountExpires
)
783 self
.modify_ldif(setexp
)
785 self
.transaction_cancel()
788 self
.transaction_commit()
790 def set_domain_sid(self
, sid
):
791 """Change the domain SID used by this LDB.
793 :param sid: The new domain sid to use.
795 dsdb
._samdb
_set
_domain
_sid
(self
, sid
)
797 def get_domain_sid(self
):
798 """Read the domain SID used by this LDB. """
799 return dsdb
._samdb
_get
_domain
_sid
(self
)
801 domain_sid
= property(get_domain_sid
, set_domain_sid
,
802 doc
="SID for the domain")
804 def set_invocation_id(self
, invocation_id
):
805 """Set the invocation id for this SamDB handle.
807 :param invocation_id: GUID of the invocation id.
809 dsdb
._dsdb
_set
_ntds
_invocation
_id
(self
, invocation_id
)
811 def get_invocation_id(self
):
812 """Get the invocation_id id"""
813 return dsdb
._samdb
_ntds
_invocation
_id
(self
)
815 invocation_id
= property(get_invocation_id
, set_invocation_id
,
816 doc
="Invocation ID GUID")
818 def get_oid_from_attid(self
, attid
):
819 return dsdb
._dsdb
_get
_oid
_from
_attid
(self
, attid
)
821 def get_attid_from_lDAPDisplayName(self
, ldap_display_name
,
823 '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
824 return dsdb
._dsdb
_get
_attid
_from
_lDAPDisplayName
(self
,
825 ldap_display_name
, is_schema_nc
)
827 def get_syntax_oid_from_lDAPDisplayName(self
, ldap_display_name
):
828 '''return the syntax OID for a LDAP attribute as a string'''
829 return dsdb
._dsdb
_get
_syntax
_oid
_from
_lDAPDisplayName
(self
, ldap_display_name
)
831 def get_systemFlags_from_lDAPDisplayName(self
, ldap_display_name
):
832 '''return the systemFlags for a LDAP attribute as a integer'''
833 return dsdb
._dsdb
_get
_systemFlags
_from
_lDAPDisplayName
(self
, ldap_display_name
)
835 def get_linkId_from_lDAPDisplayName(self
, ldap_display_name
):
836 '''return the linkID for a LDAP attribute as a integer'''
837 return dsdb
._dsdb
_get
_linkId
_from
_lDAPDisplayName
(self
, ldap_display_name
)
839 def get_lDAPDisplayName_by_attid(self
, attid
):
840 '''return the lDAPDisplayName from an integer DRS attribute ID'''
841 return dsdb
._dsdb
_get
_lDAPDisplayName
_by
_attid
(self
, attid
)
843 def get_backlink_from_lDAPDisplayName(self
, ldap_display_name
):
844 '''return the attribute name of the corresponding backlink from the name
845 of a forward link attribute. If there is no backlink return None'''
846 return dsdb
._dsdb
_get
_backlink
_from
_lDAPDisplayName
(self
, ldap_display_name
)
848 def set_ntds_settings_dn(self
, ntds_settings_dn
):
849 """Set the NTDS Settings DN, as would be returned on the dsServiceName
852 This allows the DN to be set before the database fully exists
854 :param ntds_settings_dn: The new DN to use
856 dsdb
._samdb
_set
_ntds
_settings
_dn
(self
, ntds_settings_dn
)
858 def get_ntds_GUID(self
):
859 """Get the NTDS objectGUID"""
860 return dsdb
._samdb
_ntds
_objectGUID
(self
)
862 def server_site_name(self
):
863 """Get the server site name"""
864 return dsdb
._samdb
_server
_site
_name
(self
)
866 def host_dns_name(self
):
867 """return the DNS name of this host"""
868 res
= self
.search(base
='', scope
=ldb
.SCOPE_BASE
, attrs
=['dNSHostName'])
869 return str(res
[0]['dNSHostName'][0])
871 def domain_dns_name(self
):
872 """return the DNS name of the domain root"""
873 domain_dn
= self
.get_default_basedn()
874 return domain_dn
.canonical_str().split('/')[0]
876 def forest_dns_name(self
):
877 """return the DNS name of the forest root"""
878 forest_dn
= self
.get_root_basedn()
879 return forest_dn
.canonical_str().split('/')[0]
881 def load_partition_usn(self
, base_dn
):
882 return dsdb
._dsdb
_load
_partition
_usn
(self
, base_dn
)
884 def set_schema(self
, schema
, write_indices_and_attributes
=True):
885 self
.set_schema_from_ldb(schema
.ldb
, write_indices_and_attributes
=write_indices_and_attributes
)
887 def set_schema_from_ldb(self
, ldb_conn
, write_indices_and_attributes
=True):
888 dsdb
._dsdb
_set
_schema
_from
_ldb
(self
, ldb_conn
, write_indices_and_attributes
)
890 def set_schema_update_now(self
):
897 self
.modify_ldif(ldif
)
899 def dsdb_DsReplicaAttribute(self
, ldb
, ldap_display_name
, ldif_elements
):
900 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
901 return dsdb
._dsdb
_DsReplicaAttribute
(ldb
, ldap_display_name
, ldif_elements
)
903 def dsdb_normalise_attributes(self
, ldb
, ldap_display_name
, ldif_elements
):
904 '''normalise a list of attribute values'''
905 return dsdb
._dsdb
_normalise
_attributes
(ldb
, ldap_display_name
, ldif_elements
)
907 def get_attribute_from_attid(self
, attid
):
908 """ Get from an attid the associated attribute
910 :param attid: The attribute id for searched attribute
911 :return: The name of the attribute associated with this id
913 if len(self
.hash_oid_name
.keys()) == 0:
914 self
._populate
_oid
_attid
()
915 if self
.get_oid_from_attid(attid
) in self
.hash_oid_name
:
916 return self
.hash_oid_name
[self
.get_oid_from_attid(attid
)]
920 def _populate_oid_attid(self
):
921 """Populate the hash hash_oid_name.
923 This hash contains the oid of the attribute as a key and
924 its display name as a value
926 self
.hash_oid_name
= {}
927 res
= self
.search(expression
="objectClass=attributeSchema",
928 controls
=["search_options:1:2"],
929 attrs
=["attributeID",
933 strDisplay
= str(e
.get("lDAPDisplayName"))
934 self
.hash_oid_name
[str(e
.get("attributeID"))] = strDisplay
936 def get_attribute_replmetadata_version(self
, dn
, att
):
937 """Get the version field trom the replPropertyMetaData for
940 :param dn: The on which we want to get the version
941 :param att: The name of the attribute
942 :return: The value of the version field in the replPropertyMetaData
943 for the given attribute. None if the attribute is not replicated
946 res
= self
.search(expression
="distinguishedName=%s" % dn
,
947 scope
=ldb
.SCOPE_SUBTREE
,
948 controls
=["search_options:1:2"],
949 attrs
=["replPropertyMetaData"])
953 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
954 res
[0]["replPropertyMetaData"][0])
956 if len(self
.hash_oid_name
.keys()) == 0:
957 self
._populate
_oid
_attid
()
959 # Search for Description
960 att_oid
= self
.get_oid_from_attid(o
.attid
)
961 if att_oid
in self
.hash_oid_name
and\
962 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
966 def set_attribute_replmetadata_version(self
, dn
, att
, value
,
967 addifnotexist
=False):
968 res
= self
.search(expression
="distinguishedName=%s" % dn
,
969 scope
=ldb
.SCOPE_SUBTREE
,
970 controls
=["search_options:1:2"],
971 attrs
=["replPropertyMetaData"])
975 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
976 res
[0]["replPropertyMetaData"][0])
978 now
= samba
.unix2nttime(int(time
.time()))
980 if len(self
.hash_oid_name
.keys()) == 0:
981 self
._populate
_oid
_attid
()
983 # Search for Description
984 att_oid
= self
.get_oid_from_attid(o
.attid
)
985 if att_oid
in self
.hash_oid_name
and\
986 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
988 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
990 o
.originating_change_time
= now
991 o
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
992 o
.originating_usn
= seq
995 if not found
and addifnotexist
and len(ctr
.array
) > 0:
996 o2
= drsblobs
.replPropertyMetaData1()
998 att_oid
= self
.get_oid_from_attid(o2
.attid
)
999 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
1001 o2
.originating_change_time
= now
1002 o2
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
1003 o2
.originating_usn
= seq
1008 ctr
.count
= ctr
.count
+ 1
1012 replBlob
= ndr_pack(repl
)
1015 msg
["replPropertyMetaData"] = \
1016 ldb
.MessageElement(replBlob
,
1017 ldb
.FLAG_MOD_REPLACE
,
1018 "replPropertyMetaData")
1019 self
.modify(msg
, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
1021 def write_prefixes_from_schema(self
):
1022 dsdb
._dsdb
_write
_prefixes
_from
_schema
_to
_ldb
(self
)
1024 def get_partitions_dn(self
):
1025 return dsdb
._dsdb
_get
_partitions
_dn
(self
)
1027 def get_nc_root(self
, dn
):
1028 return dsdb
._dsdb
_get
_nc
_root
(self
, dn
)
1030 def get_wellknown_dn(self
, nc_root
, wkguid
):
1031 h_nc
= self
.hash_well_known
.get(str(nc_root
))
1033 if h_nc
is not None:
1034 dn
= h_nc
.get(wkguid
)
1036 dn
= dsdb
._dsdb
_get
_wellknown
_dn
(self
, nc_root
, wkguid
)
1040 self
.hash_well_known
[str(nc_root
)] = {}
1041 h_nc
= self
.hash_well_known
[str(nc_root
)]
1045 def set_minPwdAge(self
, value
):
1046 if not isinstance(value
, binary_type
):
1047 value
= str(value
).encode('utf8')
1049 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1050 m
["minPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdAge")
1053 def get_minPwdAge(self
):
1054 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdAge"])
1057 elif "minPwdAge" not in res
[0]:
1060 return int(res
[0]["minPwdAge"][0])
1062 def set_maxPwdAge(self
, value
):
1063 if not isinstance(value
, binary_type
):
1064 value
= str(value
).encode('utf8')
1066 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1067 m
["maxPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "maxPwdAge")
1070 def get_maxPwdAge(self
):
1071 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["maxPwdAge"])
1074 elif "maxPwdAge" not in res
[0]:
1077 return int(res
[0]["maxPwdAge"][0])
1079 def set_minPwdLength(self
, value
):
1080 if not isinstance(value
, binary_type
):
1081 value
= str(value
).encode('utf8')
1083 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1084 m
["minPwdLength"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdLength")
1087 def get_minPwdLength(self
):
1088 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdLength"])
1091 elif "minPwdLength" not in res
[0]:
1094 return int(res
[0]["minPwdLength"][0])
1096 def set_pwdProperties(self
, value
):
1097 if not isinstance(value
, binary_type
):
1098 value
= str(value
).encode('utf8')
1100 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1101 m
["pwdProperties"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "pwdProperties")
1104 def get_pwdProperties(self
):
1105 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["pwdProperties"])
1108 elif "pwdProperties" not in res
[0]:
1111 return int(res
[0]["pwdProperties"][0])
1113 def set_dsheuristics(self
, dsheuristics
):
1115 m
.dn
= ldb
.Dn(self
, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
1116 % self
.get_config_basedn().get_linearized())
1117 if dsheuristics
is not None:
1118 m
["dSHeuristics"] = \
1119 ldb
.MessageElement(dsheuristics
,
1120 ldb
.FLAG_MOD_REPLACE
,
1123 m
["dSHeuristics"] = \
1124 ldb
.MessageElement([], ldb
.FLAG_MOD_DELETE
,
1128 def get_dsheuristics(self
):
1129 res
= self
.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
1130 % self
.get_config_basedn().get_linearized(),
1131 scope
=ldb
.SCOPE_BASE
, attrs
=["dSHeuristics"])
1134 elif "dSHeuristics" in res
[0]:
1135 dsheuristics
= res
[0]["dSHeuristics"][0]
1141 def create_ou(self
, ou_dn
, description
=None, name
=None, sd
=None):
1142 """Creates an organizationalUnit object
1143 :param ou_dn: dn of the new object
1144 :param description: description attribute
1145 :param name: name atttribute
1146 :param sd: security descriptor of the object, can be
1147 an SDDL string or security.descriptor type
1150 "objectClass": "organizationalUnit"}
1153 m
["description"] = description
1158 m
["nTSecurityDescriptor"] = ndr_pack(sd
)
1161 def sequence_number(self
, seq_type
):
1162 """Returns the value of the sequence number according to the requested type
1163 :param seq_type: type of sequence number
1165 self
.transaction_start()
1167 seq
= super(SamDB
, self
).sequence_number(seq_type
)
1169 self
.transaction_cancel()
1172 self
.transaction_commit()
1175 def get_dsServiceName(self
):
1176 '''get the NTDS DN from the rootDSE'''
1177 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
1178 return str(res
[0]["dsServiceName"][0])
1180 def get_serverName(self
):
1181 '''get the server DN from the rootDSE'''
1182 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["serverName"])
1183 return str(res
[0]["serverName"][0])
1185 def dns_lookup(self
, dns_name
, dns_partition
=None):
1186 '''Do a DNS lookup in the database, returns the NDR database structures'''
1187 if dns_partition
is None:
1188 return dsdb_dns
.lookup(self
, dns_name
)
1190 return dsdb_dns
.lookup(self
, dns_name
,
1191 dns_partition
=dns_partition
)
1193 def dns_extract(self
, el
):
1194 '''Return the NDR database structures from a dnsRecord element'''
1195 return dsdb_dns
.extract(self
, el
)
1197 def dns_replace(self
, dns_name
, new_records
):
1198 '''Do a DNS modification on the database, sets the NDR database
1199 structures on a DNS name
1201 return dsdb_dns
.replace(self
, dns_name
, new_records
)
1203 def dns_replace_by_dn(self
, dn
, new_records
):
1204 '''Do a DNS modification on the database, sets the NDR database
1205 structures on a LDB DN
1207 This routine is important because if the last record on the DN
1208 is removed, this routine will put a tombstone in the record.
1210 return dsdb_dns
.replace_by_dn(self
, dn
, new_records
)
1212 def garbage_collect_tombstones(self
, dn
, current_time
,
1213 tombstone_lifetime
=None):
1214 '''garbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
1215 -> (num_objects_expunged, num_links_expunged)'''
1217 if tombstone_lifetime
is None:
1218 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1221 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1225 def create_own_rid_set(self
):
1226 '''create a RID set for this DSA'''
1227 return dsdb
._dsdb
_create
_own
_rid
_set
(self
)
1229 def allocate_rid(self
):
1230 '''return a new RID from the RID Pool on this DSA'''
1231 return dsdb
._dsdb
_allocate
_rid
(self
)
1233 def normalize_dn_in_domain(self
, dn
):
1234 '''return a new DN expanded by adding the domain DN
1236 If the dn is already a child of the domain DN, just
1239 :param dn: relative dn
1241 domain_dn
= ldb
.Dn(self
, self
.domain_dn())
1243 if isinstance(dn
, ldb
.Dn
):
1246 full_dn
= ldb
.Dn(self
, dn
)
1247 if not full_dn
.is_child_of(domain_dn
):
1248 full_dn
.add_base(domain_dn
)