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."""
32 __docformat__ = "restructuredText"
34 class SamDB(samba.Ldb):
35 """The SAM database."""
37 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
38 credentials=None, flags=0, options=None, global_schema=True, auto_connect=True,
43 elif url is None and lp is not None:
44 url = lp.get("sam database")
46 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
47 session_info=session_info, credentials=credentials, flags=flags,
51 dsdb.dsdb_set_global_schema(self)
53 dsdb.dsdb_set_am_rodc(self, am_rodc)
55 def connect(self, url=None, flags=0, options=None):
56 if self.lp is not None:
57 url = self.lp.private_path(url)
59 super(SamDB, self).connect(url=url, flags=flags,
63 # find the DNs for the domain
64 res = self.search(base="",
66 expression="(defaultNamingContext=*)",
67 attrs=["defaultNamingContext"])
68 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
69 return res[0]["defaultNamingContext"][0]
71 def enable_account(self, filter):
74 :param filter: LDAP filter to find the user (eg samccountname=name)
76 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
77 expression=filter, attrs=["userAccountControl"])
81 userAccountControl = int(res[0]["userAccountControl"][0])
82 if (userAccountControl & 0x2):
83 userAccountControl = userAccountControl & ~0x2 # remove disabled bit
84 if (userAccountControl & 0x20):
85 userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit
90 replace: userAccountControl
91 userAccountControl: %u
92 """ % (user_dn, userAccountControl)
95 def force_password_change_at_next_login(self, filter):
96 """Forces a password change at next login
98 :param filter: LDAP filter to find the user (eg samccountname=name)
100 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
101 expression=filter, attrs=[])
102 assert(len(res) == 1)
111 self.modify_ldif(mod)
113 def newgroup(self, groupname, groupou=None, grouptype=None,
114 description=None, mailaddress=None, notes=None):
115 """Adds a new group with additional parameters
117 :param groupname: Name of the new group
118 :param grouptype: Type of the new group
119 :param description: Description of the new group
120 :param mailaddress: Email address of the new group
121 :param notes: Notes of the new group
124 group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
126 # The new user record. Note the reliance on the SAMLDB module which
127 # fills in the default informations
128 ldbmessage = {"dn": group_dn,
129 "sAMAccountName": groupname,
130 "objectClass": "group"}
132 if grouptype is not None:
133 ldbmessage["groupType"] = "%d" % ((grouptype)-2**32)
135 if description is not None:
136 ldbmessage["description"] = description
138 if mailaddress is not None:
139 ldbmessage["mail"] = mailaddress
141 if notes is not None:
142 ldbmessage["info"] = notes
144 self.transaction_start()
148 self.transaction_cancel()
151 self.transaction_commit()
153 def deletegroup (self, groupname):
156 :param groupname: Name of the target group
159 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
160 self.transaction_start()
162 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
163 expression=groupfilter, attrs=[])
164 if len(targetgroup) == 0:
165 print('Unable to find group "%s"' % (groupname or expression))
167 assert(len(targetgroup) == 1)
169 self.delete (targetgroup[0].dn);
172 self.transaction_cancel()
175 self.transaction_commit()
177 def add_remove_group_members (self, groupname, listofmembers,
178 add_members_operation=True):
179 """Adds or removes group members
181 :param groupname: Name of the target group
182 :param listofmembers: Comma-separated list of group members
183 :param add_members_operation: Defines if its an add or remove operation
186 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
187 groupmembers = listofmembers.split(',')
189 self.transaction_start()
191 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
192 expression=groupfilter, attrs=['member'])
193 if len(targetgroup) == 0:
194 print('Unable to find group "%s"' % (groupname or expression))
196 assert(len(targetgroup) == 1)
200 addtargettogroup = """
203 """ % (str(targetgroup[0].dn))
205 for member in groupmembers:
206 targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
207 expression="(|(sAMAccountName=%s)(CN=%s))" % (member, member), attrs=[])
209 if len(targetmember) != 1:
212 if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']):
214 addtargettogroup += """add: member
216 """ % (str(targetmember[0].dn))
218 elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']):
220 addtargettogroup += """delete: member
222 """ % (str(targetmember[0].dn))
225 self.modify_ldif(addtargettogroup)
228 self.transaction_cancel()
231 self.transaction_commit()
233 def newuser(self, username, password,
234 force_password_change_at_next_login_req=False,
235 useusernameascn=False, userou=None, surname=None, givenname=None, initials=None,
236 profilepath=None, scriptpath=None, homedrive=None, homedirectory=None,
237 jobtitle=None, department=None, company=None, description=None,
238 mailaddress=None, internetaddress=None, telephonenumber=None,
239 physicaldeliveryoffice=None):
240 """Adds a new user with additional parameters
242 :param username: Name of the new user
243 :param password: Password for the new user
244 :param force_password_change_at_next_login_req: Force password change
245 :param useusernameascn: Use username as cn rather that firstname + initials + lastname
246 :param userou: Object container (without domainDN postfix) for new user
247 :param surname: Surname of the new user
248 :param givenname: First name of the new user
249 :param initials: Initials of the new user
250 :param profilepath: Profile path of the new user
251 :param scriptpath: Logon script path of the new user
252 :param homedrive: Home drive of the new user
253 :param homedirectory: Home directory of the new user
254 :param jobtitle: Job title of the new user
255 :param department: Department of the new user
256 :param company: Company of the new user
257 :param description: of the new user
258 :param mailaddress: Email address of the new user
259 :param internetaddress: Home page of the new user
260 :param telephonenumber: Phone number of the new user
261 :param physicaldeliveryoffice: Office location of the new user
265 if givenname is not None:
266 displayname += givenname
268 if initials is not None:
269 displayname += ' %s.' % initials
271 if surname is not None:
272 displayname += ' %s' % surname
275 if useusernameascn is None and displayname is not "":
278 user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
280 # The new user record. Note the reliance on the SAMLDB module which
281 # fills in the default informations
282 ldbmessage = {"dn": user_dn,
283 "sAMAccountName": username,
284 "objectClass": "user"}
286 if surname is not None:
287 ldbmessage["sn"] = surname
289 if givenname is not None:
290 ldbmessage["givenName"] = givenname
292 if displayname is not "":
293 ldbmessage["displayName"] = displayname
294 ldbmessage["name"] = displayname
296 if initials is not None:
297 ldbmessage["initials"] = '%s.' % initials
299 if profilepath is not None:
300 ldbmessage["profilePath"] = profilepath
302 if scriptpath is not None:
303 ldbmessage["scriptPath"] = scriptpath
305 if homedrive is not None:
306 ldbmessage["homeDrive"] = homedrive
308 if homedirectory is not None:
309 ldbmessage["homeDirectory"] = homedirectory
311 if jobtitle is not None:
312 ldbmessage["title"] = jobtitle
314 if department is not None:
315 ldbmessage["department"] = department
317 if company is not None:
318 ldbmessage["company"] = company
320 if description is not None:
321 ldbmessage["description"] = description
323 if mailaddress is not None:
324 ldbmessage["mail"] = mailaddress
326 if internetaddress is not None:
327 ldbmessage["wWWHomePage"] = internetaddress
329 if telephonenumber is not None:
330 ldbmessage["telephoneNumber"] = telephonenumber
332 if physicaldeliveryoffice is not None:
333 ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
335 self.transaction_start()
339 # Sets the password for it
340 self.setpassword("(dn=" + user_dn + ")", password,
341 force_password_change_at_next_login_req)
344 self.transaction_cancel()
347 self.transaction_commit()
349 def setpassword(self, filter, password,
350 force_change_at_next_login=False,
352 """Sets the password for a user
354 Note: This call uses the "userPassword" attribute to set the password.
355 This works correctly on SAMBA 4 and on Windows DCs with
356 "2003 Native" or higer domain function level.
358 :param filter: LDAP filter to find the user (eg samccountname=name)
359 :param password: Password for the user
360 :param force_change_at_next_login: Force password change
362 self.transaction_start()
364 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
365 expression=filter, attrs=[])
367 print('Unable to find user "%s"' % (username or filter))
369 assert(len(res) == 1)
375 replace: userPassword
377 """ % (user_dn, base64.b64encode(password))
379 self.modify_ldif(setpw)
381 if force_change_at_next_login:
382 self.force_password_change_at_next_login(
383 "(dn=" + str(user_dn) + ")")
385 # modify the userAccountControl to remove the disabled bit
386 self.enable_account(filter)
388 self.transaction_cancel()
391 self.transaction_commit()
393 def setexpiry(self, filter, expiry_seconds, no_expiry_req=False):
394 """Sets the account expiry for a user
396 :param filter: LDAP filter to find the user (eg samccountname=name)
397 :param expiry_seconds: expiry time from now in seconds
398 :param no_expiry_req: if set, then don't expire password
400 self.transaction_start()
402 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
404 attrs=["userAccountControl", "accountExpires"])
405 assert(len(res) == 1)
408 userAccountControl = int(res[0]["userAccountControl"][0])
409 accountExpires = int(res[0]["accountExpires"][0])
411 userAccountControl = userAccountControl | 0x10000
414 userAccountControl = userAccountControl & ~0x10000
415 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
420 replace: userAccountControl
421 userAccountControl: %u
422 replace: accountExpires
424 """ % (user_dn, userAccountControl, accountExpires)
426 self.modify_ldif(setexp)
428 self.transaction_cancel()
431 self.transaction_commit()
433 def set_domain_sid(self, sid):
434 """Change the domain SID used by this LDB.
436 :param sid: The new domain sid to use.
438 dsdb.samdb_set_domain_sid(self, sid)
440 def get_domain_sid(self):
441 """Read the domain SID used by this LDB.
444 dsdb.samdb_get_domain_sid(self)
446 def set_invocation_id(self, invocation_id):
447 """Set the invocation id for this SamDB handle.
449 :param invocation_id: GUID of the invocation id.
451 dsdb.dsdb_set_ntds_invocation_id(self, invocation_id)
453 def get_oid_from_attid(self, attid):
454 return dsdb.dsdb_get_oid_from_attid(self, attid)
456 def get_invocation_id(self):
457 "Get the invocation_id id"
458 return dsdb.samdb_ntds_invocation_id(self)
460 def set_ntds_settings_dn(self, ntds_settings_dn):
461 """Set the NTDS Settings DN, as would be returned on the dsServiceName rootDSE attribute
463 This allows the DN to be set before the database fully exists
465 :param ntds_settings_dn: The new DN to use
467 dsdb.samdb_set_ntds_settings_dn(self, ntds_settings_dn)
469 invocation_id = property(get_invocation_id, set_invocation_id)
471 domain_sid = property(get_domain_sid, set_domain_sid)
473 def get_ntds_GUID(self):
474 "Get the NTDS objectGUID"
475 return dsdb.samdb_ntds_objectGUID(self)
477 def server_site_name(self):
478 "Get the server site name"
479 return dsdb.samdb_server_site_name(self)
481 def load_partition_usn(self, base_dn):
482 return dsdb.dsdb_load_partition_usn(self, base_dn)