s3:nmbd: add _NMBD_NMBD_H_ guard to nmbd.h
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / samdb.py
blob99f141e664233d24f231f5e70f9a5c354290e64a
1 #!/usr/bin/env python
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
5 # Copyright (C) Matthias Dieter Wallnoefer 2009
7 # Based on the original in EJS:
8 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 """Convenience functions for using the SAM."""
26 import samba
27 import ldb
28 import time
29 import base64
30 from samba import dsdb
31 from samba.ndr import ndr_unpack, ndr_pack
32 from samba.dcerpc import drsblobs, misc
34 __docformat__ = "restructuredText"
37 class SamDB(samba.Ldb):
38 """The SAM database."""
40 hash_oid_name = {}
42 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
43 credentials=None, flags=0, options=None, global_schema=True,
44 auto_connect=True, am_rodc=None):
45 self.lp = lp
46 if not auto_connect:
47 url = None
48 elif url is None and lp is not None:
49 url = lp.get("sam database")
51 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
52 session_info=session_info, credentials=credentials, flags=flags,
53 options=options)
55 if global_schema:
56 dsdb._dsdb_set_global_schema(self)
58 if am_rodc is not None:
59 dsdb._dsdb_set_am_rodc(self, am_rodc)
61 def connect(self, url=None, flags=0, options=None):
62 if self.lp is not None:
63 url = self.lp.private_path(url)
65 super(SamDB, self).connect(url=url, flags=flags,
66 options=options)
68 def am_rodc(self):
69 return dsdb._am_rodc(self)
71 def domain_dn(self):
72 return str(self.get_default_basedn())
74 def enable_account(self, search_filter):
75 """Enables an account
77 :param search_filter: LDAP filter to find the user (eg
78 samccountname=name)
79 """
80 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
81 expression=search_filter, attrs=["userAccountControl"])
82 assert(len(res) == 1)
83 user_dn = res[0].dn
85 userAccountControl = int(res[0]["userAccountControl"][0])
86 if userAccountControl & 0x2:
87 # remove disabled bit
88 userAccountControl = userAccountControl & ~0x2
89 if userAccountControl & 0x20:
90 # remove 'no password required' bit
91 userAccountControl = userAccountControl & ~0x20
93 mod = """
94 dn: %s
95 changetype: modify
96 replace: userAccountControl
97 userAccountControl: %u
98 """ % (user_dn, userAccountControl)
99 self.modify_ldif(mod)
101 def force_password_change_at_next_login(self, search_filter):
102 """Forces a password change at next login
104 :param search_filter: LDAP filter to find the user (eg
105 samccountname=name)
107 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
108 expression=search_filter, attrs=[])
109 assert(len(res) == 1)
110 user_dn = res[0].dn
112 mod = """
113 dn: %s
114 changetype: modify
115 replace: pwdLastSet
116 pwdLastSet: 0
117 """ % (user_dn)
118 self.modify_ldif(mod)
120 def newgroup(self, groupname, groupou=None, grouptype=None,
121 description=None, mailaddress=None, notes=None, sd=None):
122 """Adds a new group with additional parameters
124 :param groupname: Name of the new group
125 :param grouptype: Type of the new group
126 :param description: Description of the new group
127 :param mailaddress: Email address of the new group
128 :param notes: Notes of the new group
129 :param sd: security descriptor of the object
132 group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
134 # The new user record. Note the reliance on the SAMLDB module which
135 # fills in the default informations
136 ldbmessage = {"dn": group_dn,
137 "sAMAccountName": groupname,
138 "objectClass": "group"}
140 if grouptype is not None:
141 ldbmessage["groupType"] = "%d" % grouptype
143 if description is not None:
144 ldbmessage["description"] = description
146 if mailaddress is not None:
147 ldbmessage["mail"] = mailaddress
149 if notes is not None:
150 ldbmessage["info"] = notes
152 if sd is not None:
153 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
155 self.add(ldbmessage)
157 def deletegroup(self, groupname):
158 """Deletes a group
160 :param groupname: Name of the target group
163 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
164 self.transaction_start()
165 try:
166 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
167 expression=groupfilter, attrs=[])
168 if len(targetgroup) == 0:
169 raise Exception('Unable to find group "%s"' % groupname)
170 assert(len(targetgroup) == 1)
171 self.delete(targetgroup[0].dn)
172 except Exception:
173 self.transaction_cancel()
174 raise
175 else:
176 self.transaction_commit()
178 def add_remove_group_members(self, groupname, listofmembers,
179 add_members_operation=True):
180 """Adds or removes group members
182 :param groupname: Name of the target group
183 :param listofmembers: Comma-separated list of group members
184 :param add_members_operation: Defines if its an add or remove
185 operation
188 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
189 groupmembers = listofmembers.split(',')
191 self.transaction_start()
192 try:
193 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
194 expression=groupfilter, attrs=['member'])
195 if len(targetgroup) == 0:
196 raise Exception('Unable to find group "%s"' % groupname)
197 assert(len(targetgroup) == 1)
199 modified = False
201 addtargettogroup = """
202 dn: %s
203 changetype: modify
204 """ % (str(targetgroup[0].dn))
206 for member in groupmembers:
207 targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
208 expression="(|(sAMAccountName=%s)(CN=%s))" % (member, member), attrs=[])
210 if len(targetmember) != 1:
211 continue
213 if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']):
214 modified = True
215 addtargettogroup += """add: member
216 member: %s
217 """ % (str(targetmember[0].dn))
219 elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']):
220 modified = True
221 addtargettogroup += """delete: member
222 member: %s
223 """ % (str(targetmember[0].dn))
225 if modified is True:
226 self.modify_ldif(addtargettogroup)
228 except Exception:
229 self.transaction_cancel()
230 raise
231 else:
232 self.transaction_commit()
234 def newuser(self, username, password,
235 force_password_change_at_next_login_req=False,
236 useusernameascn=False, userou=None, surname=None, givenname=None,
237 initials=None, profilepath=None, scriptpath=None, homedrive=None,
238 homedirectory=None, jobtitle=None, department=None, company=None,
239 description=None, mailaddress=None, internetaddress=None,
240 telephonenumber=None, physicaldeliveryoffice=None, sd=None,
241 setpassword=True):
242 """Adds a new user with additional parameters
244 :param username: Name of the new user
245 :param password: Password for the new user
246 :param force_password_change_at_next_login_req: Force password change
247 :param useusernameascn: Use username as cn rather that firstname +
248 initials + lastname
249 :param userou: Object container (without domainDN postfix) for new user
250 :param surname: Surname of the new user
251 :param givenname: First name of the new user
252 :param initials: Initials of the new user
253 :param profilepath: Profile path of the new user
254 :param scriptpath: Logon script path of the new user
255 :param homedrive: Home drive of the new user
256 :param homedirectory: Home directory of the new user
257 :param jobtitle: Job title of the new user
258 :param department: Department of the new user
259 :param company: Company of the new user
260 :param description: of the new user
261 :param mailaddress: Email address of the new user
262 :param internetaddress: Home page of the new user
263 :param telephonenumber: Phone number of the new user
264 :param physicaldeliveryoffice: Office location of the new user
265 :param sd: security descriptor of the object
266 :param setpassword: optionally disable password reset
269 displayname = ""
270 if givenname is not None:
271 displayname += givenname
273 if initials is not None:
274 displayname += ' %s.' % initials
276 if surname is not None:
277 displayname += ' %s' % surname
279 cn = username
280 if useusernameascn is None and displayname is not "":
281 cn = displayname
283 user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
285 dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "")
286 user_principal_name = "%s@%s" % (username, dnsdomain)
287 # The new user record. Note the reliance on the SAMLDB module which
288 # fills in the default informations
289 ldbmessage = {"dn": user_dn,
290 "sAMAccountName": username,
291 "userPrincipalName": user_principal_name,
292 "objectClass": "user"}
294 if surname is not None:
295 ldbmessage["sn"] = surname
297 if givenname is not None:
298 ldbmessage["givenName"] = givenname
300 if displayname is not "":
301 ldbmessage["displayName"] = displayname
302 ldbmessage["name"] = displayname
304 if initials is not None:
305 ldbmessage["initials"] = '%s.' % initials
307 if profilepath is not None:
308 ldbmessage["profilePath"] = profilepath
310 if scriptpath is not None:
311 ldbmessage["scriptPath"] = scriptpath
313 if homedrive is not None:
314 ldbmessage["homeDrive"] = homedrive
316 if homedirectory is not None:
317 ldbmessage["homeDirectory"] = homedirectory
319 if jobtitle is not None:
320 ldbmessage["title"] = jobtitle
322 if department is not None:
323 ldbmessage["department"] = department
325 if company is not None:
326 ldbmessage["company"] = company
328 if description is not None:
329 ldbmessage["description"] = description
331 if mailaddress is not None:
332 ldbmessage["mail"] = mailaddress
334 if internetaddress is not None:
335 ldbmessage["wWWHomePage"] = internetaddress
337 if telephonenumber is not None:
338 ldbmessage["telephoneNumber"] = telephonenumber
340 if physicaldeliveryoffice is not None:
341 ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
343 if sd is not None:
344 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
346 self.transaction_start()
347 try:
348 self.add(ldbmessage)
350 # Sets the password for it
351 if setpassword:
352 self.setpassword("(samAccountName=%s)" % username, password,
353 force_password_change_at_next_login_req)
354 except Exception:
355 self.transaction_cancel()
356 raise
357 else:
358 self.transaction_commit()
360 def setpassword(self, search_filter, password,
361 force_change_at_next_login=False, username=None):
362 """Sets the password for a user
364 :param search_filter: LDAP filter to find the user (eg
365 samccountname=name)
366 :param password: Password for the user
367 :param force_change_at_next_login: Force password change
369 self.transaction_start()
370 try:
371 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
372 expression=search_filter, attrs=[])
373 if len(res) == 0:
374 raise Exception('Unable to find user "%s"' % (username or search_filter))
375 if len(res) > 1:
376 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
377 user_dn = res[0].dn
378 setpw = """
379 dn: %s
380 changetype: modify
381 replace: unicodePwd
382 unicodePwd:: %s
383 """ % (user_dn, base64.b64encode(("\"" + password + "\"").encode('utf-16-le')))
385 self.modify_ldif(setpw)
387 if force_change_at_next_login:
388 self.force_password_change_at_next_login(
389 "(dn=" + str(user_dn) + ")")
391 # modify the userAccountControl to remove the disabled bit
392 self.enable_account(search_filter)
393 except Exception:
394 self.transaction_cancel()
395 raise
396 else:
397 self.transaction_commit()
399 def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False):
400 """Sets the account expiry for a user
402 :param search_filter: LDAP filter to find the user (eg
403 samaccountname=name)
404 :param expiry_seconds: expiry time from now in seconds
405 :param no_expiry_req: if set, then don't expire password
407 self.transaction_start()
408 try:
409 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
410 expression=search_filter,
411 attrs=["userAccountControl", "accountExpires"])
412 assert(len(res) == 1)
413 user_dn = res[0].dn
415 userAccountControl = int(res[0]["userAccountControl"][0])
416 accountExpires = int(res[0]["accountExpires"][0])
417 if no_expiry_req:
418 userAccountControl = userAccountControl | 0x10000
419 accountExpires = 0
420 else:
421 userAccountControl = userAccountControl & ~0x10000
422 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
424 setexp = """
425 dn: %s
426 changetype: modify
427 replace: userAccountControl
428 userAccountControl: %u
429 replace: accountExpires
430 accountExpires: %u
431 """ % (user_dn, userAccountControl, accountExpires)
433 self.modify_ldif(setexp)
434 except Exception:
435 self.transaction_cancel()
436 raise
437 else:
438 self.transaction_commit()
440 def set_domain_sid(self, sid):
441 """Change the domain SID used by this LDB.
443 :param sid: The new domain sid to use.
445 dsdb._samdb_set_domain_sid(self, sid)
447 def get_domain_sid(self):
448 """Read the domain SID used by this LDB. """
449 return dsdb._samdb_get_domain_sid(self)
451 domain_sid = property(get_domain_sid, set_domain_sid,
452 "SID for the domain")
454 def set_invocation_id(self, invocation_id):
455 """Set the invocation id for this SamDB handle.
457 :param invocation_id: GUID of the invocation id.
459 dsdb._dsdb_set_ntds_invocation_id(self, invocation_id)
461 def get_invocation_id(self):
462 """Get the invocation_id id"""
463 return dsdb._samdb_ntds_invocation_id(self)
465 invocation_id = property(get_invocation_id, set_invocation_id,
466 "Invocation ID GUID")
468 def get_oid_from_attid(self, attid):
469 return dsdb._dsdb_get_oid_from_attid(self, attid)
471 def get_attid_from_lDAPDisplayName(self, ldap_display_name,
472 is_schema_nc=False):
473 return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
474 ldap_display_name, is_schema_nc)
476 def set_ntds_settings_dn(self, ntds_settings_dn):
477 """Set the NTDS Settings DN, as would be returned on the dsServiceName
478 rootDSE attribute.
480 This allows the DN to be set before the database fully exists
482 :param ntds_settings_dn: The new DN to use
484 dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn)
486 def get_ntds_GUID(self):
487 """Get the NTDS objectGUID"""
488 return dsdb._samdb_ntds_objectGUID(self)
490 def server_site_name(self):
491 """Get the server site name"""
492 return dsdb._samdb_server_site_name(self)
494 def load_partition_usn(self, base_dn):
495 return dsdb._dsdb_load_partition_usn(self, base_dn)
497 def set_schema(self, schema):
498 self.set_schema_from_ldb(schema.ldb)
500 def set_schema_from_ldb(self, ldb_conn):
501 dsdb._dsdb_set_schema_from_ldb(self, ldb_conn)
503 def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements):
504 return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements)
506 def get_attribute_from_attid(self, attid):
507 """ Get from an attid the associated attribute
509 :param attid: The attribute id for searched attribute
510 :return: The name of the attribute associated with this id
512 if len(self.hash_oid_name.keys()) == 0:
513 self._populate_oid_attid()
514 if self.hash_oid_name.has_key(self.get_oid_from_attid(attid)):
515 return self.hash_oid_name[self.get_oid_from_attid(attid)]
516 else:
517 return None
519 def _populate_oid_attid(self):
520 """Populate the hash hash_oid_name.
522 This hash contains the oid of the attribute as a key and
523 its display name as a value
525 self.hash_oid_name = {}
526 res = self.search(expression="objectClass=attributeSchema",
527 controls=["search_options:1:2"],
528 attrs=["attributeID",
529 "lDAPDisplayName"])
530 if len(res) > 0:
531 for e in res:
532 strDisplay = str(e.get("lDAPDisplayName"))
533 self.hash_oid_name[str(e.get("attributeID"))] = strDisplay
535 def get_attribute_replmetadata_version(self, dn, att):
536 """Get the version field trom the replPropertyMetaData for
537 the given field
539 :param dn: The on which we want to get the version
540 :param att: The name of the attribute
541 :return: The value of the version field in the replPropertyMetaData
542 for the given attribute. None if the attribute is not replicated
545 res = self.search(expression="dn=%s" % dn,
546 scope=ldb.SCOPE_SUBTREE,
547 controls=["search_options:1:2"],
548 attrs=["replPropertyMetaData"])
549 if len(res) == 0:
550 return None
552 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
553 str(res[0]["replPropertyMetaData"]))
554 ctr = repl.ctr
555 if len(self.hash_oid_name.keys()) == 0:
556 self._populate_oid_attid()
557 for o in ctr.array:
558 # Search for Description
559 att_oid = self.get_oid_from_attid(o.attid)
560 if self.hash_oid_name.has_key(att_oid) and\
561 att.lower() == self.hash_oid_name[att_oid].lower():
562 return o.version
563 return None
565 def set_attribute_replmetadata_version(self, dn, att, value,
566 addifnotexist=False):
567 res = self.search(expression="dn=%s" % dn,
568 scope=ldb.SCOPE_SUBTREE,
569 controls=["search_options:1:2"],
570 attrs=["replPropertyMetaData"])
571 if len(res) == 0:
572 return None
574 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
575 str(res[0]["replPropertyMetaData"]))
576 ctr = repl.ctr
577 now = samba.unix2nttime(int(time.time()))
578 found = False
579 if len(self.hash_oid_name.keys()) == 0:
580 self._populate_oid_attid()
581 for o in ctr.array:
582 # Search for Description
583 att_oid = self.get_oid_from_attid(o.attid)
584 if self.hash_oid_name.has_key(att_oid) and\
585 att.lower() == self.hash_oid_name[att_oid].lower():
586 found = True
587 seq = self.sequence_number(ldb.SEQ_NEXT)
588 o.version = value
589 o.originating_change_time = now
590 o.originating_invocation_id = misc.GUID(self.get_invocation_id())
591 o.originating_usn = seq
592 o.local_usn = seq
594 if not found and addifnotexist and len(ctr.array) >0:
595 o2 = drsblobs.replPropertyMetaData1()
596 o2.attid = 589914
597 att_oid = self.get_oid_from_attid(o2.attid)
598 seq = self.sequence_number(ldb.SEQ_NEXT)
599 o2.version = value
600 o2.originating_change_time = now
601 o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
602 o2.originating_usn = seq
603 o2.local_usn = seq
604 found = True
605 tab = ctr.array
606 tab.append(o2)
607 ctr.count = ctr.count + 1
608 ctr.array = tab
610 if found :
611 replBlob = ndr_pack(repl)
612 msg = ldb.Message()
613 msg.dn = res[0].dn
614 msg["replPropertyMetaData"] = ldb.MessageElement(replBlob,
615 ldb.FLAG_MOD_REPLACE,
616 "replPropertyMetaData")
617 self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
619 def write_prefixes_from_schema(self):
620 dsdb._dsdb_write_prefixes_from_schema_to_ldb(self)
622 def get_partitions_dn(self):
623 return dsdb._dsdb_get_partitions_dn(self)
625 def set_minPwdAge(self, value):
626 m = ldb.Message()
627 m.dn = ldb.Dn(self, self.domain_dn())
628 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
629 self.modify(m)
631 def get_minPwdAge(self):
632 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
633 if len(res) == 0:
634 return None
635 elif not "minPwdAge" in res[0]:
636 return None
637 else:
638 return res[0]["minPwdAge"][0]
640 def set_minPwdLength(self, value):
641 m = ldb.Message()
642 m.dn = ldb.Dn(self, self.domain_dn())
643 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
644 self.modify(m)
646 def get_minPwdLength(self):
647 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
648 if len(res) == 0:
649 return None
650 elif not "minPwdLength" in res[0]:
651 return None
652 else:
653 return res[0]["minPwdLength"][0]
655 def set_pwdProperties(self, value):
656 m = ldb.Message()
657 m.dn = ldb.Dn(self, self.domain_dn())
658 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
659 self.modify(m)
661 def get_pwdProperties(self):
662 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
663 if len(res) == 0:
664 return None
665 elif not "pwdProperties" in res[0]:
666 return None
667 else:
668 return res[0]["pwdProperties"][0]
670 def set_dsheuristics(self, dsheuristics):
671 m = ldb.Message()
672 m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
673 % self.get_config_basedn().get_linearized())
674 if dsheuristics is not None:
675 m["dSHeuristics"] = ldb.MessageElement(dsheuristics,
676 ldb.FLAG_MOD_REPLACE, "dSHeuristics")
677 else:
678 m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
679 "dSHeuristics")
680 self.modify(m)
682 def get_dsheuristics(self):
683 res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
684 % self.get_config_basedn().get_linearized(),
685 scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"])
686 if len(res) == 0:
687 dsheuristics = None
688 elif "dSHeuristics" in res[0]:
689 dsheuristics = res[0]["dSHeuristics"][0]
690 else:
691 dsheuristics = None
693 return dsheuristics
695 def create_ou(self, ou_dn, description=None, name=None, sd=None):
696 """Creates an organizationalUnit object
697 :param ou_dn: dn of the new object
698 :param description: description attribute
699 :param name: name atttribute
700 :param sd: security descriptor of the object, can be
701 an SDDL string or security.descriptor type
703 m = {"dn": ou_dn,
704 "objectClass": "organizationalUnit"}
706 if description:
707 m["description"] = description
708 if name:
709 m["name"] = name
711 if sd:
712 m["nTSecurityDescriptor"] = ndr_pack(sd)
713 self.add(m)