py: Fix initialisation of subtypes, fix segfaults.
[Samba/ekacnet.git] / source4 / scripting / python / samba / samdb.py
blob92b0bd7b89f679685f08d0c9c5d11bbfc14cc503
1 #!/usr/bin/python
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
8 #
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 glue
27 import ldb
28 from samba.idmap import IDmapDB
29 import pwd
30 import time
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.
42 """
43 self.lp = lp
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)
47 if url:
48 self.connect(url)
49 else:
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."""
57 add = """
58 dn: CN=%s,CN=ForeignSecurityPrincipals,%s
59 objectClass: top
60 objectClass: foreignSecurityPrincipal
61 description: %s
62 """ % (sid, domaindn, desc)
63 # deliberately ignore errors from this, as the records may
64 # already exist
65 for msg in self.parse_ldif(add):
66 self.add(msg[1])
68 def enable_account(self, user_dn):
69 """Enable an account.
71 :param user_dn: Dn of the account to enable.
72 """
73 res = self.search(user_dn, ldb.SCOPE_BASE, None, ["userAccountControl"])
74 assert len(res) == 1
75 userAccountControl = res[0]["userAccountControl"][0]
76 userAccountControl = int(userAccountControl)
77 if (userAccountControl & 0x2):
78 userAccountControl = userAccountControl & ~0x2 # remove disabled bit
79 if (userAccountControl & 0x20):
80 userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit
82 mod = """
83 dn: %s
84 changetype: modify
85 replace: userAccountControl
86 userAccountControl: %u
87 """ % (user_dn, userAccountControl)
88 self.modify_ldif(mod)
90 def domain_dn(self):
91 # find the DNs for the domain and the domain users group
92 res = self.search("", scope=ldb.SCOPE_BASE,
93 expression="(defaultNamingContext=*)",
94 attrs=["defaultNamingContext"])
95 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
96 return res[0]["defaultNamingContext"][0]
98 def newuser(self, username, unixname, password):
99 """add a new user record.
101 :param username: Name of the new user.
102 :param unixname: Name of the unix user to map to.
103 :param password: Password for the new user
105 # connect to the sam
106 self.transaction_start()
108 domain_dn = self.domain_dn()
109 assert(domain_dn is not None)
110 user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
113 # the new user record. note the reliance on the samdb module to fill
114 # in a sid, guid etc
116 # now the real work
117 self.add({"dn": user_dn,
118 "sAMAccountName": username,
119 "userPassword": password,
120 "objectClass": "user"})
122 res = self.search(user_dn, scope=ldb.SCOPE_BASE,
123 expression="objectclass=*",
124 attrs=["objectSid"])
125 assert(len(res) == 1)
126 user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
129 try:
130 idmap = IDmapDB(lp=self.lp)
132 user = pwd.getpwnam(unixname)
133 # setup ID mapping for this UID
135 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
137 except KeyError:
138 pass
140 # modify the userAccountControl to remove the disabled bit
141 self.enable_account(user_dn)
142 self.transaction_commit()
144 def setpassword(self, filter, password):
145 """Set a password on a user record
147 :param filter: LDAP filter to find the user (eg samccountname=name)
148 :param password: Password for the user
150 # connect to the sam
151 self.transaction_start()
153 # find the DNs for the domain
154 res = self.search("", scope=ldb.SCOPE_BASE,
155 expression="(defaultNamingContext=*)",
156 attrs=["defaultNamingContext"])
157 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
158 domain_dn = res[0]["defaultNamingContext"][0]
159 assert(domain_dn is not None)
161 res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
162 expression=filter,
163 attrs=[])
164 assert(len(res) == 1)
165 user_dn = res[0].dn
167 setpw = """
168 dn: %s
169 changetype: modify
170 replace: userPassword
171 userPassword: %s
172 """ % (user_dn, password)
174 self.modify_ldif(setpw)
176 # modify the userAccountControl to remove the disabled bit
177 self.enable_account(user_dn)
178 self.transaction_commit()
180 def set_domain_sid(self, sid):
181 """Change the domain SID used by this SamDB.
183 :param sid: The new domain sid to use.
185 glue.samdb_set_domain_sid(self, sid)
187 def attach_schema_from_ldif(self, pf, df):
188 glue.dsdb_attach_schema_from_ldif_file(self, pf, df)
190 def set_invocation_id(self, invocation_id):
191 """Set the invocation id for this SamDB handle.
193 :param invocation_id: GUID of the invocation id.
195 glue.dsdb_set_ntds_invocation_id(self, invocation_id)
197 def setexpiry(self, user, expiry_seconds, noexpiry):
198 """Set the password expiry for a user
200 :param expiry_seconds: expiry time from now in seconds
201 :param noexpiry: if set, then don't expire password
203 self.transaction_start();
204 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
205 expression=("(samAccountName=%s)" % user),
206 attrs=["userAccountControl", "accountExpires"])
207 assert len(res) == 1
208 userAccountControl = int(res[0]["userAccountControl"][0])
209 accountExpires = int(res[0]["accountExpires"][0])
210 if noexpiry:
211 userAccountControl = userAccountControl | 0x10000
212 accountExpires = 0
213 else:
214 userAccountControl = userAccountControl & ~0x10000
215 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))
217 mod = """
218 dn: %s
219 changetype: modify
220 replace: userAccountControl
221 userAccountControl: %u
222 replace: accountExpires
223 accountExpires: %u
224 """ % (res[0].dn, userAccountControl, accountExpires)
225 # now change the database
226 self.modify_ldif(mod)
227 self.transaction_commit();