python/samdb: add option to specify types of group members
[Samba.git] / python / samba / samdb.py
blob1090383f5266a52d24f01c493a9edf3d122d3551
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))
264 filter = "(|%s)" % filter
266 return 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
276 operation
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()
283 try:
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)
290 modified = False
292 addtargettogroup = """
293 dn: %s
294 changetype: modify
295 """ % (str(targetgroup[0].dn))
297 for member in members:
298 filter = self.group_member_filter(member, member_types)
299 foreign_msg = None
300 try:
301 membersid = security.dom_sid(member)
302 except TypeError as e:
303 membersid = None
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,
314 attrs=[])
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']]):
322 modified = True
323 addtargettogroup += """add: member
324 member: %s
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']):
328 modified = True
329 addtargettogroup += """delete: member
330 member: %s
331 """ % (str(targetmember_dn))
333 if modified is True:
334 self.modify_ldif(addtargettogroup)
336 except:
337 self.transaction_cancel()
338 raise
339 else:
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 +
358 initials + lastname
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
387 displayname = ""
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
397 cn = username
398 if useusernameascn is None and displayname != "":
399 cn = 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)
415 setpassword = False
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
466 if sd is not None:
467 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
469 ldbmessage2 = None
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)
474 if uid is not None:
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,
494 'unixUserPassword')
496 self.transaction_start()
497 try:
498 self.add(ldbmessage)
499 if ldbmessage2:
500 self.modify(ldbmessage2)
502 # Sets the password for it
503 if setpassword:
504 self.setpassword(("(distinguishedName=%s)" %
505 ldb.binary_encode(user_dn)),
506 password,
507 force_password_change_at_next_login_req)
508 except:
509 self.transaction_cancel()
510 raise
511 else:
512 self.transaction_commit()
514 def newcontact(self,
515 fullcontactname=None,
516 ou=None,
517 surname=None,
518 givenname=None,
519 initials=None,
520 displayname=None,
521 jobtitle=None,
522 department=None,
523 company=None,
524 description=None,
525 mailaddress=None,
526 internetaddress=None,
527 telephonenumber=None,
528 mobilenumber=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.
550 cn = ""
551 if givenname is not None:
552 cn += givenname
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:
564 cn = fullcontactname
566 if fullcontactname is None and cn == "":
567 raise Exception('No name for contact specified')
569 contactcontainer_dn = self.domain_dn()
570 if ou:
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
618 self.add(ldbmessage)
620 return cn
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)
636 if cn.count('$'):
637 raise Exception('Illegal computername "%s"' % computername)
638 samaccountname = "%s$" % cn
640 computercontainer_dn = "CN=Computers,%s" % self.domain_dn()
641 if computerou:
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)
659 if prepare_oldjoin:
660 accountcontrol = str(dsdb.UF_WORKSTATION_TRUST_ACCOUNT)
661 ldbmessage["userAccountControl"] = accountcontrol
663 if ip_address_list:
664 ldbmessage['dNSHostName'] = '{}.{}'.format(
665 cn, self.domain_dns_name())
667 self.transaction_start()
668 try:
669 self.add(ldbmessage)
671 if prepare_oldjoin:
672 password = cn.lower()
673 self.setpassword(("(distinguishedName=%s)" %
674 ldb.binary_encode(computer_dn)),
675 password, False)
676 except:
677 self.transaction_cancel()
678 raise
679 else:
680 self.transaction_commit()
682 def deleteuser(self, username):
683 """Deletes a user
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()
690 try:
691 target = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
692 expression=filter, attrs=[])
693 if len(target) == 0:
694 raise Exception('Unable to find user "%s"' % username)
695 assert(len(target) == 1)
696 self.delete(target[0].dn)
697 except:
698 self.transaction_cancel()
699 raise
700 else:
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
708 samccountname=name)
709 :param password: Password for the user
710 :param force_change_at_next_login: Force password change
712 self.transaction_start()
713 try:
714 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
715 expression=search_filter, attrs=[])
716 if len(res) == 0:
717 raise Exception('Unable to find user "%s"' % (username or search_filter))
718 if len(res) > 1:
719 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
720 user_dn = res[0].dn
721 if not isinstance(password, text_type):
722 pw = password.decode('utf-8')
723 else:
724 pw = password
725 pw = ('"' + pw + '"').encode('utf-16-le')
726 setpw = """
727 dn: %s
728 changetype: modify
729 replace: unicodePwd
730 unicodePwd:: %s
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)
741 except:
742 self.transaction_cancel()
743 raise
744 else:
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
751 samaccountname=name)
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()
756 try:
757 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
758 expression=search_filter,
759 attrs=["userAccountControl", "accountExpires"])
760 if len(res) == 0:
761 raise Exception('Unable to find user "%s"' % search_filter)
762 assert(len(res) == 1)
763 user_dn = res[0].dn
765 userAccountControl = int(res[0]["userAccountControl"][0])
766 accountExpires = int(res[0]["accountExpires"][0])
767 if no_expiry_req:
768 userAccountControl = userAccountControl | 0x10000
769 accountExpires = 0
770 else:
771 userAccountControl = userAccountControl & ~0x10000
772 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
774 setexp = """
775 dn: %s
776 changetype: modify
777 replace: userAccountControl
778 userAccountControl: %u
779 replace: accountExpires
780 accountExpires: %u
781 """ % (user_dn, userAccountControl, accountExpires)
783 self.modify_ldif(setexp)
784 except:
785 self.transaction_cancel()
786 raise
787 else:
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,
822 is_schema_nc=False):
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
850 rootDSE attribute.
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):
891 ldif = """
893 changetype: modify
894 add: schemaUpdateNow
895 schemaUpdateNow: 1
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)]
917 else:
918 return None
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",
930 "lDAPDisplayName"])
931 if len(res) > 0:
932 for e in res:
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
938 the given field
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"])
950 if len(res) == 0:
951 return None
953 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
954 res[0]["replPropertyMetaData"][0])
955 ctr = repl.ctr
956 if len(self.hash_oid_name.keys()) == 0:
957 self._populate_oid_attid()
958 for o in ctr.array:
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():
963 return o.version
964 return None
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"])
972 if len(res) == 0:
973 return None
975 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
976 res[0]["replPropertyMetaData"][0])
977 ctr = repl.ctr
978 now = samba.unix2nttime(int(time.time()))
979 found = False
980 if len(self.hash_oid_name.keys()) == 0:
981 self._populate_oid_attid()
982 for o in ctr.array:
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():
987 found = True
988 seq = self.sequence_number(ldb.SEQ_NEXT)
989 o.version = value
990 o.originating_change_time = now
991 o.originating_invocation_id = misc.GUID(self.get_invocation_id())
992 o.originating_usn = seq
993 o.local_usn = seq
995 if not found and addifnotexist and len(ctr.array) > 0:
996 o2 = drsblobs.replPropertyMetaData1()
997 o2.attid = 589914
998 att_oid = self.get_oid_from_attid(o2.attid)
999 seq = self.sequence_number(ldb.SEQ_NEXT)
1000 o2.version = value
1001 o2.originating_change_time = now
1002 o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
1003 o2.originating_usn = seq
1004 o2.local_usn = seq
1005 found = True
1006 tab = ctr.array
1007 tab.append(o2)
1008 ctr.count = ctr.count + 1
1009 ctr.array = tab
1011 if found:
1012 replBlob = ndr_pack(repl)
1013 msg = ldb.Message()
1014 msg.dn = res[0].dn
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))
1032 dn = None
1033 if h_nc is not None:
1034 dn = h_nc.get(wkguid)
1035 if dn is None:
1036 dn = dsdb._dsdb_get_wellknown_dn(self, nc_root, wkguid)
1037 if dn is None:
1038 return dn
1039 if h_nc is None:
1040 self.hash_well_known[str(nc_root)] = {}
1041 h_nc = self.hash_well_known[str(nc_root)]
1042 h_nc[wkguid] = dn
1043 return dn
1045 def set_minPwdAge(self, value):
1046 if not isinstance(value, binary_type):
1047 value = str(value).encode('utf8')
1048 m = ldb.Message()
1049 m.dn = ldb.Dn(self, self.domain_dn())
1050 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
1051 self.modify(m)
1053 def get_minPwdAge(self):
1054 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
1055 if len(res) == 0:
1056 return None
1057 elif "minPwdAge" not in res[0]:
1058 return None
1059 else:
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')
1065 m = ldb.Message()
1066 m.dn = ldb.Dn(self, self.domain_dn())
1067 m["maxPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "maxPwdAge")
1068 self.modify(m)
1070 def get_maxPwdAge(self):
1071 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["maxPwdAge"])
1072 if len(res) == 0:
1073 return None
1074 elif "maxPwdAge" not in res[0]:
1075 return None
1076 else:
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')
1082 m = ldb.Message()
1083 m.dn = ldb.Dn(self, self.domain_dn())
1084 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
1085 self.modify(m)
1087 def get_minPwdLength(self):
1088 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
1089 if len(res) == 0:
1090 return None
1091 elif "minPwdLength" not in res[0]:
1092 return None
1093 else:
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')
1099 m = ldb.Message()
1100 m.dn = ldb.Dn(self, self.domain_dn())
1101 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
1102 self.modify(m)
1104 def get_pwdProperties(self):
1105 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
1106 if len(res) == 0:
1107 return None
1108 elif "pwdProperties" not in res[0]:
1109 return None
1110 else:
1111 return int(res[0]["pwdProperties"][0])
1113 def set_dsheuristics(self, dsheuristics):
1114 m = ldb.Message()
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,
1121 "dSHeuristics")
1122 else:
1123 m["dSHeuristics"] = \
1124 ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
1125 "dSHeuristics")
1126 self.modify(m)
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"])
1132 if len(res) == 0:
1133 dsheuristics = None
1134 elif "dSHeuristics" in res[0]:
1135 dsheuristics = res[0]["dSHeuristics"][0]
1136 else:
1137 dsheuristics = None
1139 return dsheuristics
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
1149 m = {"dn": ou_dn,
1150 "objectClass": "organizationalUnit"}
1152 if description:
1153 m["description"] = description
1154 if name:
1155 m["name"] = name
1157 if sd:
1158 m["nTSecurityDescriptor"] = ndr_pack(sd)
1159 self.add(m)
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()
1166 try:
1167 seq = super(SamDB, self).sequence_number(seq_type)
1168 except:
1169 self.transaction_cancel()
1170 raise
1171 else:
1172 self.transaction_commit()
1173 return seq
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)
1189 else:
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,
1219 current_time)
1220 else:
1221 return dsdb._dsdb_garbage_collect_tombstones(self, dn,
1222 current_time,
1223 tombstone_lifetime)
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
1237 return it as-is.
1239 :param dn: relative dn
1241 domain_dn = ldb.Dn(self, self.domain_dn())
1243 if isinstance(dn, ldb.Dn):
1244 dn = str(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)
1249 return full_dn