3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
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."""
28 from samba.idmap import IDmapDB
32 __docformat__ = "restructuredText"
34 class SamDB(samba.Ldb):
35 """The SAM database."""
37 def __init__(self, url=None, session_info=None, credentials=None,
38 modules_dir=None, lp=None):
39 """Open the Sam Database.
41 :param url: URL of the database.
44 super(SamDB, self).__init__(session_info=session_info, credentials=credentials,
45 modules_dir=modules_dir, lp=lp)
46 glue.dsdb_set_global_schema(self)
50 self.connect(lp.get("sam database"))
52 def connect(self, url):
53 super(SamDB, self).connect(self.lp.private_path(url))
55 def add_foreign(self, domaindn, sid, desc):
56 """Add a foreign security principle."""
58 dn: CN=%s,CN=ForeignSecurityPrincipals,%s
60 objectClass: foreignSecurityPrincipal
62 """ % (sid, domaindn, desc)
63 # deliberately ignore errors from this, as the records may
65 for msg in self.parse_ldif(add):
68 def add_stock_foreign_sids(self):
69 domaindn = self.domain_dn()
70 self.add_foreign(domaindn, "S-1-5-7", "Anonymous")
71 self.add_foreign(domaindn, "S-1-1-0", "World")
72 self.add_foreign(domaindn, "S-1-5-2", "Network")
73 self.add_foreign(domaindn, "S-1-5-18", "System")
74 self.add_foreign(domaindn, "S-1-5-11", "Authenticated Users")
76 def enable_account(self, user_dn):
79 :param user_dn: Dn of the account to enable.
81 res = self.search(user_dn, ldb.SCOPE_BASE, None, ["userAccountControl"])
83 userAccountControl = res[0]["userAccountControl"][0]
84 userAccountControl = int(userAccountControl)
85 if (userAccountControl & 0x2):
86 userAccountControl = userAccountControl & ~0x2 # remove disabled bit
87 if (userAccountControl & 0x20):
88 userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit
93 replace: userAccountControl
94 userAccountControl: %u
95 """ % (user_dn, userAccountControl)
99 # find the DNs for the domain and the domain users group
100 res = self.search("", scope=ldb.SCOPE_BASE,
101 expression="(defaultNamingContext=*)",
102 attrs=["defaultNamingContext"])
103 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
104 return res[0]["defaultNamingContext"][0]
106 def newuser(self, username, unixname, password):
107 """add a new user record.
109 :param username: Name of the new user.
110 :param unixname: Name of the unix user to map to.
111 :param password: Password for the new user
114 self.transaction_start()
116 domain_dn = self.domain_dn()
117 assert(domain_dn is not None)
118 user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
121 # the new user record. note the reliance on the samdb module to
122 # fill in a sid, guid etc
125 self.add({"dn": user_dn,
126 "sAMAccountName": username,
127 "userPassword": password,
128 "objectClass": "user"})
130 res = self.search(user_dn, scope=ldb.SCOPE_BASE,
131 expression="objectclass=*",
134 user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
137 idmap = IDmapDB(lp=self.lp)
139 user = pwd.getpwnam(unixname)
140 # setup ID mapping for this UID
142 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
147 # modify the userAccountControl to remove the disabled bit
148 self.enable_account(user_dn)
150 self.transaction_cancel()
152 self.transaction_commit()
154 def setpassword(self, filter, password):
155 """Set a password on a user record
157 :param filter: LDAP filter to find the user (eg samccountname=name)
158 :param password: Password for the user
161 self.transaction_start()
163 # find the DNs for the domain
164 res = self.search("", scope=ldb.SCOPE_BASE,
165 expression="(defaultNamingContext=*)",
166 attrs=["defaultNamingContext"])
167 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
168 domain_dn = res[0]["defaultNamingContext"][0]
169 assert(domain_dn is not None)
171 res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
174 assert(len(res) == 1)
180 replace: userPassword
182 """ % (user_dn, password)
184 self.modify_ldif(setpw)
186 # modify the userAccountControl to remove the disabled bit
187 self.enable_account(user_dn)
189 self.transaction_cancel()
191 self.transaction_commit()
193 def set_domain_sid(self, sid):
194 """Change the domain SID used by this SamDB.
196 :param sid: The new domain sid to use.
198 glue.samdb_set_domain_sid(self, sid)
200 def attach_schema_from_ldif(self, pf, df):
201 glue.dsdb_attach_schema_from_ldif_file(self, pf, df)
203 def set_invocation_id(self, invocation_id):
204 """Set the invocation id for this SamDB handle.
206 :param invocation_id: GUID of the invocation id.
208 glue.dsdb_set_ntds_invocation_id(self, invocation_id)
210 def setexpiry(self, user, expiry_seconds, noexpiry):
211 """Set the password expiry for a user
213 :param expiry_seconds: expiry time from now in seconds
214 :param noexpiry: if set, then don't expire password
216 self.transaction_start()
218 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
219 expression=("(samAccountName=%s)" % user),
220 attrs=["userAccountControl", "accountExpires"])
222 userAccountControl = int(res[0]["userAccountControl"][0])
223 accountExpires = int(res[0]["accountExpires"][0])
225 userAccountControl = userAccountControl | 0x10000
228 userAccountControl = userAccountControl & ~0x10000
229 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))
234 replace: userAccountControl
235 userAccountControl: %u
236 replace: accountExpires
238 """ % (res[0].dn, userAccountControl, accountExpires)
239 # now change the database
240 self.modify_ldif(mod)
242 self.transaction_cancel()
244 self.transaction_commit();