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 add_remove_group_members(self
, groupname
, members
,
255 add_members_operation
=True):
256 """Adds or removes group members
258 :param groupname: Name of the target group
259 :param members: list of group members
260 :param add_members_operation: Defines if its an add or remove
264 groupfilter
= "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (
265 ldb
.binary_encode(groupname
), "CN=Group,CN=Schema,CN=Configuration", self
.domain_dn())
267 self
.transaction_start()
269 targetgroup
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
270 expression
=groupfilter
, attrs
=['member'])
271 if len(targetgroup
) == 0:
272 raise Exception('Unable to find group "%s"' % groupname
)
273 assert(len(targetgroup
) == 1)
277 addtargettogroup
= """
280 """ % (str(targetgroup
[0].dn
))
282 for member
in members
:
283 filter = ('(&(sAMAccountName=%s)(|(objectclass=user)'
284 '(objectclass=group)))' % ldb
.binary_encode(member
))
287 membersid
= security
.dom_sid(member
)
288 except TypeError as e
:
291 if membersid
is not None:
292 filter = '(objectSid=%s)' % str(membersid
)
293 dn_str
= "<SID=%s>" % str(membersid
)
294 foreign_msg
= ldb
.Message()
295 foreign_msg
.dn
= ldb
.Dn(self
, dn_str
)
297 targetmember
= self
.search(base
=self
.domain_dn(),
298 scope
=ldb
.SCOPE_SUBTREE
,
299 expression
="%s" % filter,
302 if len(targetmember
) == 0 and foreign_msg
is not None:
303 targetmember
= [foreign_msg
]
304 if len(targetmember
) != 1:
305 raise Exception('Unable to find "%s". Operation cancelled.' % member
)
306 targetmember_dn
= targetmember
[0].dn
.extended_str(1)
307 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']]):
309 addtargettogroup
+= """add: member
311 """ % (str(targetmember_dn
))
313 elif add_members_operation
is False and (targetgroup
[0].get('member') is not None and get_bytes(targetmember_dn
) in targetgroup
[0]['member']):
315 addtargettogroup
+= """delete: member
317 """ % (str(targetmember_dn
))
320 self
.modify_ldif(addtargettogroup
)
323 self
.transaction_cancel()
326 self
.transaction_commit()
328 def newuser(self
, username
, password
,
329 force_password_change_at_next_login_req
=False,
330 useusernameascn
=False, userou
=None, surname
=None, givenname
=None,
331 initials
=None, profilepath
=None, scriptpath
=None, homedrive
=None,
332 homedirectory
=None, jobtitle
=None, department
=None, company
=None,
333 description
=None, mailaddress
=None, internetaddress
=None,
334 telephonenumber
=None, physicaldeliveryoffice
=None, sd
=None,
335 setpassword
=True, uidnumber
=None, gidnumber
=None, gecos
=None,
336 loginshell
=None, uid
=None, nisdomain
=None, unixhome
=None,
337 smartcard_required
=False):
338 """Adds a new user with additional parameters
340 :param username: Name of the new user
341 :param password: Password for the new user
342 :param force_password_change_at_next_login_req: Force password change
343 :param useusernameascn: Use username as cn rather that firstname +
345 :param userou: Object container (without domainDN postfix) for new user
346 :param surname: Surname of the new user
347 :param givenname: First name of the new user
348 :param initials: Initials of the new user
349 :param profilepath: Profile path of the new user
350 :param scriptpath: Logon script path of the new user
351 :param homedrive: Home drive of the new user
352 :param homedirectory: Home directory of the new user
353 :param jobtitle: Job title of the new user
354 :param department: Department of the new user
355 :param company: Company of the new user
356 :param description: of the new user
357 :param mailaddress: Email address of the new user
358 :param internetaddress: Home page of the new user
359 :param telephonenumber: Phone number of the new user
360 :param physicaldeliveryoffice: Office location of the new user
361 :param sd: security descriptor of the object
362 :param setpassword: optionally disable password reset
363 :param uidnumber: RFC2307 Unix numeric UID of the new user
364 :param gidnumber: RFC2307 Unix primary GID of the new user
365 :param gecos: RFC2307 Unix GECOS field of the new user
366 :param loginshell: RFC2307 Unix login shell of the new user
367 :param uid: RFC2307 Unix username of the new user
368 :param nisdomain: RFC2307 Unix NIS domain of the new user
369 :param unixhome: RFC2307 Unix home directory of the new user
370 :param smartcard_required: set the UF_SMARTCARD_REQUIRED bit of the new user
374 if givenname
is not None:
375 displayname
+= givenname
377 if initials
is not None:
378 displayname
+= ' %s.' % initials
380 if surname
is not None:
381 displayname
+= ' %s' % surname
384 if useusernameascn
is None and displayname
!= "":
387 user_dn
= "CN=%s,%s,%s" % (cn
, (userou
or "CN=Users"), self
.domain_dn())
389 dnsdomain
= ldb
.Dn(self
, self
.domain_dn()).canonical_str().replace("/", "")
390 user_principal_name
= "%s@%s" % (username
, dnsdomain
)
391 # The new user record. Note the reliance on the SAMLDB module which
392 # fills in the default information
393 ldbmessage
= {"dn": user_dn
,
394 "sAMAccountName": username
,
395 "userPrincipalName": user_principal_name
,
396 "objectClass": "user"}
398 if smartcard_required
:
399 ldbmessage
["userAccountControl"] = str(dsdb
.UF_NORMAL_ACCOUNT |
400 dsdb
.UF_SMARTCARD_REQUIRED
)
403 if surname
is not None:
404 ldbmessage
["sn"] = surname
406 if givenname
is not None:
407 ldbmessage
["givenName"] = givenname
409 if displayname
!= "":
410 ldbmessage
["displayName"] = displayname
411 ldbmessage
["name"] = displayname
413 if initials
is not None:
414 ldbmessage
["initials"] = '%s.' % initials
416 if profilepath
is not None:
417 ldbmessage
["profilePath"] = profilepath
419 if scriptpath
is not None:
420 ldbmessage
["scriptPath"] = scriptpath
422 if homedrive
is not None:
423 ldbmessage
["homeDrive"] = homedrive
425 if homedirectory
is not None:
426 ldbmessage
["homeDirectory"] = homedirectory
428 if jobtitle
is not None:
429 ldbmessage
["title"] = jobtitle
431 if department
is not None:
432 ldbmessage
["department"] = department
434 if company
is not None:
435 ldbmessage
["company"] = company
437 if description
is not None:
438 ldbmessage
["description"] = description
440 if mailaddress
is not None:
441 ldbmessage
["mail"] = mailaddress
443 if internetaddress
is not None:
444 ldbmessage
["wWWHomePage"] = internetaddress
446 if telephonenumber
is not None:
447 ldbmessage
["telephoneNumber"] = telephonenumber
449 if physicaldeliveryoffice
is not None:
450 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
453 ldbmessage
["nTSecurityDescriptor"] = ndr_pack(sd
)
456 if any(map(lambda b
: b
is not None, (uid
, uidnumber
, gidnumber
, gecos
,
457 loginshell
, nisdomain
, unixhome
))):
458 ldbmessage2
= ldb
.Message()
459 ldbmessage2
.dn
= ldb
.Dn(self
, user_dn
)
461 ldbmessage2
["uid"] = ldb
.MessageElement(str(uid
), ldb
.FLAG_MOD_REPLACE
, 'uid')
462 if uidnumber
is not None:
463 ldbmessage2
["uidNumber"] = ldb
.MessageElement(str(uidnumber
), ldb
.FLAG_MOD_REPLACE
, 'uidNumber')
464 if gidnumber
is not None:
465 ldbmessage2
["gidNumber"] = ldb
.MessageElement(str(gidnumber
), ldb
.FLAG_MOD_REPLACE
, 'gidNumber')
466 if gecos
is not None:
467 ldbmessage2
["gecos"] = ldb
.MessageElement(str(gecos
), ldb
.FLAG_MOD_REPLACE
, 'gecos')
468 if loginshell
is not None:
469 ldbmessage2
["loginShell"] = ldb
.MessageElement(str(loginshell
), ldb
.FLAG_MOD_REPLACE
, 'loginShell')
470 if unixhome
is not None:
471 ldbmessage2
["unixHomeDirectory"] = ldb
.MessageElement(
472 str(unixhome
), ldb
.FLAG_MOD_REPLACE
, 'unixHomeDirectory')
473 if nisdomain
is not None:
474 ldbmessage2
["msSFU30NisDomain"] = ldb
.MessageElement(
475 str(nisdomain
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30NisDomain')
476 ldbmessage2
["msSFU30Name"] = ldb
.MessageElement(
477 str(username
), ldb
.FLAG_MOD_REPLACE
, 'msSFU30Name')
478 ldbmessage2
["unixUserPassword"] = ldb
.MessageElement(
479 'ABCD!efgh12345$67890', ldb
.FLAG_MOD_REPLACE
,
482 self
.transaction_start()
486 self
.modify(ldbmessage2
)
488 # Sets the password for it
490 self
.setpassword(("(distinguishedName=%s)" %
491 ldb
.binary_encode(user_dn
)),
493 force_password_change_at_next_login_req
)
495 self
.transaction_cancel()
498 self
.transaction_commit()
501 fullcontactname
=None,
512 internetaddress
=None,
513 telephonenumber
=None,
515 physicaldeliveryoffice
=None):
516 """Adds a new contact with additional parameters
518 :param fullcontactname: Optional full name of the new contact
519 :param ou: Object container for new contact
520 :param surname: Surname of the new contact
521 :param givenname: First name of the new contact
522 :param initials: Initials of the new contact
523 :param displayname: displayName of the new contact
524 :param jobtitle: Job title of the new contact
525 :param department: Department of the new contact
526 :param company: Company of the new contact
527 :param description: Description of the new contact
528 :param mailaddress: Email address of the new contact
529 :param internetaddress: Home page of the new contact
530 :param telephonenumber: Phone number of the new contact
531 :param mobilenumber: Primary mobile number of the new contact
532 :param physicaldeliveryoffice: Office location of the new contact
535 # Prepare the contact name like the RSAT, using the name parts.
537 if givenname
is not None:
540 if initials
is not None:
541 cn
+= ' %s.' % initials
543 if surname
is not None:
544 cn
+= ' %s' % surname
546 # Use the specified fullcontactname instead of the previously prepared
547 # contact name, if it is specified.
548 # This is similar to the "Full name" value of the RSAT.
549 if fullcontactname
is not None:
552 if fullcontactname
is None and cn
== "":
553 raise Exception('No name for contact specified')
555 contactcontainer_dn
= self
.domain_dn()
557 contactcontainer_dn
= self
.normalize_dn_in_domain(ou
)
559 contact_dn
= "CN=%s,%s" % (cn
, contactcontainer_dn
)
561 ldbmessage
= {"dn": contact_dn
,
562 "objectClass": "contact",
565 if surname
is not None:
566 ldbmessage
["sn"] = surname
568 if givenname
is not None:
569 ldbmessage
["givenName"] = givenname
571 if displayname
is not None:
572 ldbmessage
["displayName"] = displayname
574 if initials
is not None:
575 ldbmessage
["initials"] = '%s.' % initials
577 if jobtitle
is not None:
578 ldbmessage
["title"] = jobtitle
580 if department
is not None:
581 ldbmessage
["department"] = department
583 if company
is not None:
584 ldbmessage
["company"] = company
586 if description
is not None:
587 ldbmessage
["description"] = description
589 if mailaddress
is not None:
590 ldbmessage
["mail"] = mailaddress
592 if internetaddress
is not None:
593 ldbmessage
["wWWHomePage"] = internetaddress
595 if telephonenumber
is not None:
596 ldbmessage
["telephoneNumber"] = telephonenumber
598 if mobilenumber
is not None:
599 ldbmessage
["mobile"] = mobilenumber
601 if physicaldeliveryoffice
is not None:
602 ldbmessage
["physicalDeliveryOfficeName"] = physicaldeliveryoffice
608 def newcomputer(self
, computername
, computerou
=None, description
=None,
609 prepare_oldjoin
=False, ip_address_list
=None,
610 service_principal_name_list
=None):
611 """Adds a new user with additional parameters
613 :param computername: Name of the new computer
614 :param computerou: Object container for new computer
615 :param description: Description of the new computer
616 :param prepare_oldjoin: Preset computer password for oldjoin mechanism
617 :param ip_address_list: ip address list for DNS A or AAAA record
618 :param service_principal_name_list: string list of servicePincipalName
621 cn
= re
.sub(r
"\$$", "", computername
)
623 raise Exception('Illegal computername "%s"' % computername
)
624 samaccountname
= "%s$" % cn
626 computercontainer_dn
= "CN=Computers,%s" % self
.domain_dn()
628 computercontainer_dn
= self
.normalize_dn_in_domain(computerou
)
630 computer_dn
= "CN=%s,%s" % (cn
, computercontainer_dn
)
632 ldbmessage
= {"dn": computer_dn
,
633 "sAMAccountName": samaccountname
,
634 "objectClass": "computer",
637 if description
is not None:
638 ldbmessage
["description"] = description
640 if service_principal_name_list
:
641 ldbmessage
["servicePrincipalName"] = service_principal_name_list
643 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
644 dsdb
.UF_ACCOUNTDISABLE
)
646 accountcontrol
= str(dsdb
.UF_WORKSTATION_TRUST_ACCOUNT
)
647 ldbmessage
["userAccountControl"] = accountcontrol
650 ldbmessage
['dNSHostName'] = '{}.{}'.format(
651 cn
, self
.domain_dns_name())
653 self
.transaction_start()
658 password
= cn
.lower()
659 self
.setpassword(("(distinguishedName=%s)" %
660 ldb
.binary_encode(computer_dn
)),
663 self
.transaction_cancel()
666 self
.transaction_commit()
668 def deleteuser(self
, username
):
671 :param username: Name of the target user
674 filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb
.binary_encode(username
), "CN=Person,CN=Schema,CN=Configuration", self
.domain_dn())
675 self
.transaction_start()
677 target
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
678 expression
=filter, attrs
=[])
680 raise Exception('Unable to find user "%s"' % username
)
681 assert(len(target
) == 1)
682 self
.delete(target
[0].dn
)
684 self
.transaction_cancel()
687 self
.transaction_commit()
689 def setpassword(self
, search_filter
, password
,
690 force_change_at_next_login
=False, username
=None):
691 """Sets the password for a user
693 :param search_filter: LDAP filter to find the user (eg
695 :param password: Password for the user
696 :param force_change_at_next_login: Force password change
698 self
.transaction_start()
700 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
701 expression
=search_filter
, attrs
=[])
703 raise Exception('Unable to find user "%s"' % (username
or search_filter
))
705 raise Exception('Matched %u multiple users with filter "%s"' % (len(res
), search_filter
))
707 if not isinstance(password
, text_type
):
708 pw
= password
.decode('utf-8')
711 pw
= ('"' + pw
+ '"').encode('utf-16-le')
717 """ % (user_dn
, base64
.b64encode(pw
).decode('utf-8'))
719 self
.modify_ldif(setpw
)
721 if force_change_at_next_login
:
722 self
.force_password_change_at_next_login(
723 "(distinguishedName=" + str(user_dn
) + ")")
725 # modify the userAccountControl to remove the disabled bit
726 self
.enable_account(search_filter
)
728 self
.transaction_cancel()
731 self
.transaction_commit()
733 def setexpiry(self
, search_filter
, expiry_seconds
, no_expiry_req
=False):
734 """Sets the account expiry for a user
736 :param search_filter: LDAP filter to find the user (eg
738 :param expiry_seconds: expiry time from now in seconds
739 :param no_expiry_req: if set, then don't expire password
741 self
.transaction_start()
743 res
= self
.search(base
=self
.domain_dn(), scope
=ldb
.SCOPE_SUBTREE
,
744 expression
=search_filter
,
745 attrs
=["userAccountControl", "accountExpires"])
747 raise Exception('Unable to find user "%s"' % search_filter
)
748 assert(len(res
) == 1)
751 userAccountControl
= int(res
[0]["userAccountControl"][0])
752 accountExpires
= int(res
[0]["accountExpires"][0])
754 userAccountControl
= userAccountControl |
0x10000
757 userAccountControl
= userAccountControl
& ~
0x10000
758 accountExpires
= samba
.unix2nttime(expiry_seconds
+ int(time
.time()))
763 replace: userAccountControl
764 userAccountControl: %u
765 replace: accountExpires
767 """ % (user_dn
, userAccountControl
, accountExpires
)
769 self
.modify_ldif(setexp
)
771 self
.transaction_cancel()
774 self
.transaction_commit()
776 def set_domain_sid(self
, sid
):
777 """Change the domain SID used by this LDB.
779 :param sid: The new domain sid to use.
781 dsdb
._samdb
_set
_domain
_sid
(self
, sid
)
783 def get_domain_sid(self
):
784 """Read the domain SID used by this LDB. """
785 return dsdb
._samdb
_get
_domain
_sid
(self
)
787 domain_sid
= property(get_domain_sid
, set_domain_sid
,
788 doc
="SID for the domain")
790 def set_invocation_id(self
, invocation_id
):
791 """Set the invocation id for this SamDB handle.
793 :param invocation_id: GUID of the invocation id.
795 dsdb
._dsdb
_set
_ntds
_invocation
_id
(self
, invocation_id
)
797 def get_invocation_id(self
):
798 """Get the invocation_id id"""
799 return dsdb
._samdb
_ntds
_invocation
_id
(self
)
801 invocation_id
= property(get_invocation_id
, set_invocation_id
,
802 doc
="Invocation ID GUID")
804 def get_oid_from_attid(self
, attid
):
805 return dsdb
._dsdb
_get
_oid
_from
_attid
(self
, attid
)
807 def get_attid_from_lDAPDisplayName(self
, ldap_display_name
,
809 '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
810 return dsdb
._dsdb
_get
_attid
_from
_lDAPDisplayName
(self
,
811 ldap_display_name
, is_schema_nc
)
813 def get_syntax_oid_from_lDAPDisplayName(self
, ldap_display_name
):
814 '''return the syntax OID for a LDAP attribute as a string'''
815 return dsdb
._dsdb
_get
_syntax
_oid
_from
_lDAPDisplayName
(self
, ldap_display_name
)
817 def get_systemFlags_from_lDAPDisplayName(self
, ldap_display_name
):
818 '''return the systemFlags for a LDAP attribute as a integer'''
819 return dsdb
._dsdb
_get
_systemFlags
_from
_lDAPDisplayName
(self
, ldap_display_name
)
821 def get_linkId_from_lDAPDisplayName(self
, ldap_display_name
):
822 '''return the linkID for a LDAP attribute as a integer'''
823 return dsdb
._dsdb
_get
_linkId
_from
_lDAPDisplayName
(self
, ldap_display_name
)
825 def get_lDAPDisplayName_by_attid(self
, attid
):
826 '''return the lDAPDisplayName from an integer DRS attribute ID'''
827 return dsdb
._dsdb
_get
_lDAPDisplayName
_by
_attid
(self
, attid
)
829 def get_backlink_from_lDAPDisplayName(self
, ldap_display_name
):
830 '''return the attribute name of the corresponding backlink from the name
831 of a forward link attribute. If there is no backlink return None'''
832 return dsdb
._dsdb
_get
_backlink
_from
_lDAPDisplayName
(self
, ldap_display_name
)
834 def set_ntds_settings_dn(self
, ntds_settings_dn
):
835 """Set the NTDS Settings DN, as would be returned on the dsServiceName
838 This allows the DN to be set before the database fully exists
840 :param ntds_settings_dn: The new DN to use
842 dsdb
._samdb
_set
_ntds
_settings
_dn
(self
, ntds_settings_dn
)
844 def get_ntds_GUID(self
):
845 """Get the NTDS objectGUID"""
846 return dsdb
._samdb
_ntds
_objectGUID
(self
)
848 def server_site_name(self
):
849 """Get the server site name"""
850 return dsdb
._samdb
_server
_site
_name
(self
)
852 def host_dns_name(self
):
853 """return the DNS name of this host"""
854 res
= self
.search(base
='', scope
=ldb
.SCOPE_BASE
, attrs
=['dNSHostName'])
855 return str(res
[0]['dNSHostName'][0])
857 def domain_dns_name(self
):
858 """return the DNS name of the domain root"""
859 domain_dn
= self
.get_default_basedn()
860 return domain_dn
.canonical_str().split('/')[0]
862 def forest_dns_name(self
):
863 """return the DNS name of the forest root"""
864 forest_dn
= self
.get_root_basedn()
865 return forest_dn
.canonical_str().split('/')[0]
867 def load_partition_usn(self
, base_dn
):
868 return dsdb
._dsdb
_load
_partition
_usn
(self
, base_dn
)
870 def set_schema(self
, schema
, write_indices_and_attributes
=True):
871 self
.set_schema_from_ldb(schema
.ldb
, write_indices_and_attributes
=write_indices_and_attributes
)
873 def set_schema_from_ldb(self
, ldb_conn
, write_indices_and_attributes
=True):
874 dsdb
._dsdb
_set
_schema
_from
_ldb
(self
, ldb_conn
, write_indices_and_attributes
)
876 def set_schema_update_now(self
):
883 self
.modify_ldif(ldif
)
885 def dsdb_DsReplicaAttribute(self
, ldb
, ldap_display_name
, ldif_elements
):
886 '''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
887 return dsdb
._dsdb
_DsReplicaAttribute
(ldb
, ldap_display_name
, ldif_elements
)
889 def dsdb_normalise_attributes(self
, ldb
, ldap_display_name
, ldif_elements
):
890 '''normalise a list of attribute values'''
891 return dsdb
._dsdb
_normalise
_attributes
(ldb
, ldap_display_name
, ldif_elements
)
893 def get_attribute_from_attid(self
, attid
):
894 """ Get from an attid the associated attribute
896 :param attid: The attribute id for searched attribute
897 :return: The name of the attribute associated with this id
899 if len(self
.hash_oid_name
.keys()) == 0:
900 self
._populate
_oid
_attid
()
901 if self
.get_oid_from_attid(attid
) in self
.hash_oid_name
:
902 return self
.hash_oid_name
[self
.get_oid_from_attid(attid
)]
906 def _populate_oid_attid(self
):
907 """Populate the hash hash_oid_name.
909 This hash contains the oid of the attribute as a key and
910 its display name as a value
912 self
.hash_oid_name
= {}
913 res
= self
.search(expression
="objectClass=attributeSchema",
914 controls
=["search_options:1:2"],
915 attrs
=["attributeID",
919 strDisplay
= str(e
.get("lDAPDisplayName"))
920 self
.hash_oid_name
[str(e
.get("attributeID"))] = strDisplay
922 def get_attribute_replmetadata_version(self
, dn
, att
):
923 """Get the version field trom the replPropertyMetaData for
926 :param dn: The on which we want to get the version
927 :param att: The name of the attribute
928 :return: The value of the version field in the replPropertyMetaData
929 for the given attribute. None if the attribute is not replicated
932 res
= self
.search(expression
="distinguishedName=%s" % dn
,
933 scope
=ldb
.SCOPE_SUBTREE
,
934 controls
=["search_options:1:2"],
935 attrs
=["replPropertyMetaData"])
939 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
940 res
[0]["replPropertyMetaData"][0])
942 if len(self
.hash_oid_name
.keys()) == 0:
943 self
._populate
_oid
_attid
()
945 # Search for Description
946 att_oid
= self
.get_oid_from_attid(o
.attid
)
947 if att_oid
in self
.hash_oid_name
and\
948 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
952 def set_attribute_replmetadata_version(self
, dn
, att
, value
,
953 addifnotexist
=False):
954 res
= self
.search(expression
="distinguishedName=%s" % dn
,
955 scope
=ldb
.SCOPE_SUBTREE
,
956 controls
=["search_options:1:2"],
957 attrs
=["replPropertyMetaData"])
961 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
962 res
[0]["replPropertyMetaData"][0])
964 now
= samba
.unix2nttime(int(time
.time()))
966 if len(self
.hash_oid_name
.keys()) == 0:
967 self
._populate
_oid
_attid
()
969 # Search for Description
970 att_oid
= self
.get_oid_from_attid(o
.attid
)
971 if att_oid
in self
.hash_oid_name
and\
972 att
.lower() == self
.hash_oid_name
[att_oid
].lower():
974 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
976 o
.originating_change_time
= now
977 o
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
978 o
.originating_usn
= seq
981 if not found
and addifnotexist
and len(ctr
.array
) > 0:
982 o2
= drsblobs
.replPropertyMetaData1()
984 att_oid
= self
.get_oid_from_attid(o2
.attid
)
985 seq
= self
.sequence_number(ldb
.SEQ_NEXT
)
987 o2
.originating_change_time
= now
988 o2
.originating_invocation_id
= misc
.GUID(self
.get_invocation_id())
989 o2
.originating_usn
= seq
994 ctr
.count
= ctr
.count
+ 1
998 replBlob
= ndr_pack(repl
)
1001 msg
["replPropertyMetaData"] = \
1002 ldb
.MessageElement(replBlob
,
1003 ldb
.FLAG_MOD_REPLACE
,
1004 "replPropertyMetaData")
1005 self
.modify(msg
, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
1007 def write_prefixes_from_schema(self
):
1008 dsdb
._dsdb
_write
_prefixes
_from
_schema
_to
_ldb
(self
)
1010 def get_partitions_dn(self
):
1011 return dsdb
._dsdb
_get
_partitions
_dn
(self
)
1013 def get_nc_root(self
, dn
):
1014 return dsdb
._dsdb
_get
_nc
_root
(self
, dn
)
1016 def get_wellknown_dn(self
, nc_root
, wkguid
):
1017 h_nc
= self
.hash_well_known
.get(str(nc_root
))
1019 if h_nc
is not None:
1020 dn
= h_nc
.get(wkguid
)
1022 dn
= dsdb
._dsdb
_get
_wellknown
_dn
(self
, nc_root
, wkguid
)
1026 self
.hash_well_known
[str(nc_root
)] = {}
1027 h_nc
= self
.hash_well_known
[str(nc_root
)]
1031 def set_minPwdAge(self
, value
):
1032 if not isinstance(value
, binary_type
):
1033 value
= str(value
).encode('utf8')
1035 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1036 m
["minPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdAge")
1039 def get_minPwdAge(self
):
1040 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdAge"])
1043 elif "minPwdAge" not in res
[0]:
1046 return int(res
[0]["minPwdAge"][0])
1048 def set_maxPwdAge(self
, value
):
1049 if not isinstance(value
, binary_type
):
1050 value
= str(value
).encode('utf8')
1052 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1053 m
["maxPwdAge"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "maxPwdAge")
1056 def get_maxPwdAge(self
):
1057 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["maxPwdAge"])
1060 elif "maxPwdAge" not in res
[0]:
1063 return int(res
[0]["maxPwdAge"][0])
1065 def set_minPwdLength(self
, value
):
1066 if not isinstance(value
, binary_type
):
1067 value
= str(value
).encode('utf8')
1069 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1070 m
["minPwdLength"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "minPwdLength")
1073 def get_minPwdLength(self
):
1074 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["minPwdLength"])
1077 elif "minPwdLength" not in res
[0]:
1080 return int(res
[0]["minPwdLength"][0])
1082 def set_pwdProperties(self
, value
):
1083 if not isinstance(value
, binary_type
):
1084 value
= str(value
).encode('utf8')
1086 m
.dn
= ldb
.Dn(self
, self
.domain_dn())
1087 m
["pwdProperties"] = ldb
.MessageElement(value
, ldb
.FLAG_MOD_REPLACE
, "pwdProperties")
1090 def get_pwdProperties(self
):
1091 res
= self
.search(self
.domain_dn(), scope
=ldb
.SCOPE_BASE
, attrs
=["pwdProperties"])
1094 elif "pwdProperties" not in res
[0]:
1097 return int(res
[0]["pwdProperties"][0])
1099 def set_dsheuristics(self
, dsheuristics
):
1101 m
.dn
= ldb
.Dn(self
, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
1102 % self
.get_config_basedn().get_linearized())
1103 if dsheuristics
is not None:
1104 m
["dSHeuristics"] = \
1105 ldb
.MessageElement(dsheuristics
,
1106 ldb
.FLAG_MOD_REPLACE
,
1109 m
["dSHeuristics"] = \
1110 ldb
.MessageElement([], ldb
.FLAG_MOD_DELETE
,
1114 def get_dsheuristics(self
):
1115 res
= self
.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
1116 % self
.get_config_basedn().get_linearized(),
1117 scope
=ldb
.SCOPE_BASE
, attrs
=["dSHeuristics"])
1120 elif "dSHeuristics" in res
[0]:
1121 dsheuristics
= res
[0]["dSHeuristics"][0]
1127 def create_ou(self
, ou_dn
, description
=None, name
=None, sd
=None):
1128 """Creates an organizationalUnit object
1129 :param ou_dn: dn of the new object
1130 :param description: description attribute
1131 :param name: name atttribute
1132 :param sd: security descriptor of the object, can be
1133 an SDDL string or security.descriptor type
1136 "objectClass": "organizationalUnit"}
1139 m
["description"] = description
1144 m
["nTSecurityDescriptor"] = ndr_pack(sd
)
1147 def sequence_number(self
, seq_type
):
1148 """Returns the value of the sequence number according to the requested type
1149 :param seq_type: type of sequence number
1151 self
.transaction_start()
1153 seq
= super(SamDB
, self
).sequence_number(seq_type
)
1155 self
.transaction_cancel()
1158 self
.transaction_commit()
1161 def get_dsServiceName(self
):
1162 '''get the NTDS DN from the rootDSE'''
1163 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
1164 return str(res
[0]["dsServiceName"][0])
1166 def get_serverName(self
):
1167 '''get the server DN from the rootDSE'''
1168 res
= self
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["serverName"])
1169 return str(res
[0]["serverName"][0])
1171 def dns_lookup(self
, dns_name
, dns_partition
=None):
1172 '''Do a DNS lookup in the database, returns the NDR database structures'''
1173 if dns_partition
is None:
1174 return dsdb_dns
.lookup(self
, dns_name
)
1176 return dsdb_dns
.lookup(self
, dns_name
,
1177 dns_partition
=dns_partition
)
1179 def dns_extract(self
, el
):
1180 '''Return the NDR database structures from a dnsRecord element'''
1181 return dsdb_dns
.extract(self
, el
)
1183 def dns_replace(self
, dns_name
, new_records
):
1184 '''Do a DNS modification on the database, sets the NDR database
1185 structures on a DNS name
1187 return dsdb_dns
.replace(self
, dns_name
, new_records
)
1189 def dns_replace_by_dn(self
, dn
, new_records
):
1190 '''Do a DNS modification on the database, sets the NDR database
1191 structures on a LDB DN
1193 This routine is important because if the last record on the DN
1194 is removed, this routine will put a tombstone in the record.
1196 return dsdb_dns
.replace_by_dn(self
, dn
, new_records
)
1198 def garbage_collect_tombstones(self
, dn
, current_time
,
1199 tombstone_lifetime
=None):
1200 '''garbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
1201 -> (num_objects_expunged, num_links_expunged)'''
1203 if tombstone_lifetime
is None:
1204 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1207 return dsdb
._dsdb
_garbage
_collect
_tombstones
(self
, dn
,
1211 def create_own_rid_set(self
):
1212 '''create a RID set for this DSA'''
1213 return dsdb
._dsdb
_create
_own
_rid
_set
(self
)
1215 def allocate_rid(self
):
1216 '''return a new RID from the RID Pool on this DSA'''
1217 return dsdb
._dsdb
_allocate
_rid
(self
)
1219 def normalize_dn_in_domain(self
, dn
):
1220 '''return a new DN expanded by adding the domain DN
1222 If the dn is already a child of the domain DN, just
1225 :param dn: relative dn
1227 domain_dn
= ldb
.Dn(self
, self
.domain_dn())
1229 if isinstance(dn
, ldb
.Dn
):
1232 full_dn
= ldb
.Dn(self
, dn
)
1233 if not full_dn
.is_child_of(domain_dn
):
1234 full_dn
.add_base(domain_dn
)