python/samdb: fetch specific error if there are more than one search results
[Samba.git] / python / samba / samdb.py
blobec4affa24b7e3b9a073c2598f3ff422aa2a7e84a
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."""
25 import samba
26 import ldb
27 import time
28 import base64
29 import os
30 import re
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():
44 return "tdb"
47 class SamDB(samba.Ldb):
48 """The SAM database."""
50 hash_oid_name = {}
51 hash_well_known = {}
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):
57 self.lp = lp
58 if not auto_connect:
59 url = None
60 elif url is None and lp is not None:
61 url = lp.samdb_url()
63 self.url = url
65 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
66 session_info=session_info, credentials=credentials, flags=flags,
67 options=options)
69 if global_schema:
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)
79 self.url = url
81 super(SamDB, self).connect(url=url, flags=flags,
82 options=options)
84 def am_rodc(self):
85 '''return True if we are an RODC'''
86 return dsdb._am_rodc(self)
88 def am_pdc(self):
89 '''return True if we are an PDC emulator'''
90 return dsdb._am_pdc(self)
92 def domain_dn(self):
93 '''return the domain DN'''
94 return str(self.get_default_basedn())
96 def schema_dn(self):
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
104 samccountname=name)
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
114 samccountname=name)
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
125 samccountname=name)
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"])
133 if len(res) == 0:
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])
139 if on:
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
145 else:
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:
153 return
155 mod = """
156 dn: %s
157 changetype: modify
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
169 samccountname=name)
171 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
172 expression=search_filter, attrs=[])
173 if len(res) == 0:
174 raise Exception('Unable to find user "%s"' % search_filter)
175 assert(len(res) == 1)
176 user_dn = res[0].dn
178 mod = """
179 dn: %s
180 changetype: modify
181 replace: pwdLastSet
182 pwdLastSet: 0
183 """ % (user_dn)
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
228 if sd is not None:
229 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
231 self.add(ldbmessage)
233 def deletegroup(self, groupname):
234 """Deletes a group
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()
241 try:
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)
248 except:
249 self.transaction_cancel()
250 raise
251 else:
252 self.transaction_commit()
254 def group_member_filter(self, member, member_types):
255 filter = ""
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
287 return 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
297 operation
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()
304 try:
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)
311 modified = False
313 addtargettogroup = """
314 dn: %s
315 changetype: modify
316 """ % (str(targetgroup[0].dn))
318 for member in members:
319 filter = self.group_member_filter(member, member_types)
320 foreign_msg = None
321 try:
322 membersid = security.dom_sid(member)
323 except TypeError as e:
324 membersid = None
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,
335 attrs=[])
337 if len(targetmember) > 1:
338 memberlist_str = ""
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']]):
349 modified = True
350 addtargettogroup += """add: member
351 member: %s
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']):
355 modified = True
356 addtargettogroup += """delete: member
357 member: %s
358 """ % (str(targetmember_dn))
360 if modified is True:
361 self.modify_ldif(addtargettogroup)
363 except:
364 self.transaction_cancel()
365 raise
366 else:
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 +
385 initials + lastname
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
414 displayname = ""
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
424 cn = username
425 if useusernameascn is None and displayname != "":
426 cn = 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)
442 setpassword = False
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
493 if sd is not None:
494 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
496 ldbmessage2 = None
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)
501 if uid is not None:
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,
521 'unixUserPassword')
523 self.transaction_start()
524 try:
525 self.add(ldbmessage)
526 if ldbmessage2:
527 self.modify(ldbmessage2)
529 # Sets the password for it
530 if setpassword:
531 self.setpassword(("(distinguishedName=%s)" %
532 ldb.binary_encode(user_dn)),
533 password,
534 force_password_change_at_next_login_req)
535 except:
536 self.transaction_cancel()
537 raise
538 else:
539 self.transaction_commit()
541 def newcontact(self,
542 fullcontactname=None,
543 ou=None,
544 surname=None,
545 givenname=None,
546 initials=None,
547 displayname=None,
548 jobtitle=None,
549 department=None,
550 company=None,
551 description=None,
552 mailaddress=None,
553 internetaddress=None,
554 telephonenumber=None,
555 mobilenumber=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.
577 cn = ""
578 if givenname is not None:
579 cn += givenname
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:
591 cn = fullcontactname
593 if fullcontactname is None and cn == "":
594 raise Exception('No name for contact specified')
596 contactcontainer_dn = self.domain_dn()
597 if ou:
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
645 self.add(ldbmessage)
647 return cn
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)
663 if cn.count('$'):
664 raise Exception('Illegal computername "%s"' % computername)
665 samaccountname = "%s$" % cn
667 computercontainer_dn = "CN=Computers,%s" % self.domain_dn()
668 if computerou:
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)
686 if prepare_oldjoin:
687 accountcontrol = str(dsdb.UF_WORKSTATION_TRUST_ACCOUNT)
688 ldbmessage["userAccountControl"] = accountcontrol
690 if ip_address_list:
691 ldbmessage['dNSHostName'] = '{}.{}'.format(
692 cn, self.domain_dns_name())
694 self.transaction_start()
695 try:
696 self.add(ldbmessage)
698 if prepare_oldjoin:
699 password = cn.lower()
700 self.setpassword(("(distinguishedName=%s)" %
701 ldb.binary_encode(computer_dn)),
702 password, False)
703 except:
704 self.transaction_cancel()
705 raise
706 else:
707 self.transaction_commit()
709 def deleteuser(self, username):
710 """Deletes a user
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()
717 try:
718 target = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
719 expression=filter, attrs=[])
720 if len(target) == 0:
721 raise Exception('Unable to find user "%s"' % username)
722 assert(len(target) == 1)
723 self.delete(target[0].dn)
724 except:
725 self.transaction_cancel()
726 raise
727 else:
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
735 samccountname=name)
736 :param password: Password for the user
737 :param force_change_at_next_login: Force password change
739 self.transaction_start()
740 try:
741 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
742 expression=search_filter, attrs=[])
743 if len(res) == 0:
744 raise Exception('Unable to find user "%s"' % (username or search_filter))
745 if len(res) > 1:
746 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
747 user_dn = res[0].dn
748 if not isinstance(password, text_type):
749 pw = password.decode('utf-8')
750 else:
751 pw = password
752 pw = ('"' + pw + '"').encode('utf-16-le')
753 setpw = """
754 dn: %s
755 changetype: modify
756 replace: unicodePwd
757 unicodePwd:: %s
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)
768 except:
769 self.transaction_cancel()
770 raise
771 else:
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
778 samaccountname=name)
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()
783 try:
784 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
785 expression=search_filter,
786 attrs=["userAccountControl", "accountExpires"])
787 if len(res) == 0:
788 raise Exception('Unable to find user "%s"' % search_filter)
789 assert(len(res) == 1)
790 user_dn = res[0].dn
792 userAccountControl = int(res[0]["userAccountControl"][0])
793 accountExpires = int(res[0]["accountExpires"][0])
794 if no_expiry_req:
795 userAccountControl = userAccountControl | 0x10000
796 accountExpires = 0
797 else:
798 userAccountControl = userAccountControl & ~0x10000
799 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
801 setexp = """
802 dn: %s
803 changetype: modify
804 replace: userAccountControl
805 userAccountControl: %u
806 replace: accountExpires
807 accountExpires: %u
808 """ % (user_dn, userAccountControl, accountExpires)
810 self.modify_ldif(setexp)
811 except:
812 self.transaction_cancel()
813 raise
814 else:
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,
849 is_schema_nc=False):
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
877 rootDSE attribute.
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):
918 ldif = """
920 changetype: modify
921 add: schemaUpdateNow
922 schemaUpdateNow: 1
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)]
944 else:
945 return None
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",
957 "lDAPDisplayName"])
958 if len(res) > 0:
959 for e in res:
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
965 the given field
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"])
977 if len(res) == 0:
978 return None
980 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
981 res[0]["replPropertyMetaData"][0])
982 ctr = repl.ctr
983 if len(self.hash_oid_name.keys()) == 0:
984 self._populate_oid_attid()
985 for o in ctr.array:
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():
990 return o.version
991 return None
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"])
999 if len(res) == 0:
1000 return None
1002 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
1003 res[0]["replPropertyMetaData"][0])
1004 ctr = repl.ctr
1005 now = samba.unix2nttime(int(time.time()))
1006 found = False
1007 if len(self.hash_oid_name.keys()) == 0:
1008 self._populate_oid_attid()
1009 for o in ctr.array:
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():
1014 found = True
1015 seq = self.sequence_number(ldb.SEQ_NEXT)
1016 o.version = value
1017 o.originating_change_time = now
1018 o.originating_invocation_id = misc.GUID(self.get_invocation_id())
1019 o.originating_usn = seq
1020 o.local_usn = seq
1022 if not found and addifnotexist and len(ctr.array) > 0:
1023 o2 = drsblobs.replPropertyMetaData1()
1024 o2.attid = 589914
1025 att_oid = self.get_oid_from_attid(o2.attid)
1026 seq = self.sequence_number(ldb.SEQ_NEXT)
1027 o2.version = value
1028 o2.originating_change_time = now
1029 o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
1030 o2.originating_usn = seq
1031 o2.local_usn = seq
1032 found = True
1033 tab = ctr.array
1034 tab.append(o2)
1035 ctr.count = ctr.count + 1
1036 ctr.array = tab
1038 if found:
1039 replBlob = ndr_pack(repl)
1040 msg = ldb.Message()
1041 msg.dn = res[0].dn
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))
1059 dn = None
1060 if h_nc is not None:
1061 dn = h_nc.get(wkguid)
1062 if dn is None:
1063 dn = dsdb._dsdb_get_wellknown_dn(self, nc_root, wkguid)
1064 if dn is None:
1065 return dn
1066 if h_nc is None:
1067 self.hash_well_known[str(nc_root)] = {}
1068 h_nc = self.hash_well_known[str(nc_root)]
1069 h_nc[wkguid] = dn
1070 return dn
1072 def set_minPwdAge(self, value):
1073 if not isinstance(value, binary_type):
1074 value = str(value).encode('utf8')
1075 m = ldb.Message()
1076 m.dn = ldb.Dn(self, self.domain_dn())
1077 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
1078 self.modify(m)
1080 def get_minPwdAge(self):
1081 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
1082 if len(res) == 0:
1083 return None
1084 elif "minPwdAge" not in res[0]:
1085 return None
1086 else:
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')
1092 m = ldb.Message()
1093 m.dn = ldb.Dn(self, self.domain_dn())
1094 m["maxPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "maxPwdAge")
1095 self.modify(m)
1097 def get_maxPwdAge(self):
1098 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["maxPwdAge"])
1099 if len(res) == 0:
1100 return None
1101 elif "maxPwdAge" not in res[0]:
1102 return None
1103 else:
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')
1109 m = ldb.Message()
1110 m.dn = ldb.Dn(self, self.domain_dn())
1111 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
1112 self.modify(m)
1114 def get_minPwdLength(self):
1115 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
1116 if len(res) == 0:
1117 return None
1118 elif "minPwdLength" not in res[0]:
1119 return None
1120 else:
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')
1126 m = ldb.Message()
1127 m.dn = ldb.Dn(self, self.domain_dn())
1128 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
1129 self.modify(m)
1131 def get_pwdProperties(self):
1132 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
1133 if len(res) == 0:
1134 return None
1135 elif "pwdProperties" not in res[0]:
1136 return None
1137 else:
1138 return int(res[0]["pwdProperties"][0])
1140 def set_dsheuristics(self, dsheuristics):
1141 m = ldb.Message()
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,
1148 "dSHeuristics")
1149 else:
1150 m["dSHeuristics"] = \
1151 ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
1152 "dSHeuristics")
1153 self.modify(m)
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"])
1159 if len(res) == 0:
1160 dsheuristics = None
1161 elif "dSHeuristics" in res[0]:
1162 dsheuristics = res[0]["dSHeuristics"][0]
1163 else:
1164 dsheuristics = None
1166 return dsheuristics
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
1176 m = {"dn": ou_dn,
1177 "objectClass": "organizationalUnit"}
1179 if description:
1180 m["description"] = description
1181 if name:
1182 m["name"] = name
1184 if sd:
1185 m["nTSecurityDescriptor"] = ndr_pack(sd)
1186 self.add(m)
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()
1193 try:
1194 seq = super(SamDB, self).sequence_number(seq_type)
1195 except:
1196 self.transaction_cancel()
1197 raise
1198 else:
1199 self.transaction_commit()
1200 return seq
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)
1216 else:
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,
1246 current_time)
1247 else:
1248 return dsdb._dsdb_garbage_collect_tombstones(self, dn,
1249 current_time,
1250 tombstone_lifetime)
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
1264 return it as-is.
1266 :param dn: relative dn
1268 domain_dn = ldb.Dn(self, self.domain_dn())
1270 if isinstance(dn, ldb.Dn):
1271 dn = str(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)
1276 return full_dn