Move some samdb-specific code out of provision.
[kai/samba.git] / source4 / scripting / python / samba / samdb.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
5 #
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.
13 #   
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.
18 #   
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/>.
21 #
22
23 """Convenience functions for using the SAM."""
24
25 import samba
26 import glue
27 import ldb
28 from samba.idmap import IDmapDB
29 import pwd
30 import time
31
32 __docformat__ = "restructuredText"
33
34 class SamDB(samba.Ldb):
35     """The SAM database."""
36
37     def __init__(self, url=None, session_info=None, credentials=None, 
38                  modules_dir=None, lp=None):
39         """Open the Sam Database.
40
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"))
51
52     def connect(self, url):
53         super(SamDB, self).connect(self.lp.private_path(url))
54
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])
67
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")
75
76     def enable_account(self, user_dn):
77         """Enable an account.
78         
79         :param user_dn: Dn of the account to enable.
80         """
81         res = self.search(user_dn, ldb.SCOPE_BASE, None, ["userAccountControl"])
82         assert len(res) == 1
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
89
90         mod = """
91 dn: %s
92 changetype: modify
93 replace: userAccountControl
94 userAccountControl: %u
95 """ % (user_dn, userAccountControl)
96         self.modify_ldif(mod)
97
98     def domain_dn(self):
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]
105
106     def newuser(self, username, unixname, password):
107         """add a new user record.
108         
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
112         """
113         # connect to the sam 
114         self.transaction_start()
115         try:
116             domain_dn = self.domain_dn()
117             assert(domain_dn is not None)
118             user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
119
120             #
121             #  the new user record. note the reliance on the samdb module to 
122             #  fill in a sid, guid etc
123             #
124             #  now the real work
125             self.add({"dn": user_dn, 
126                 "sAMAccountName": username,
127                 "userPassword": password,
128                 "objectClass": "user"})
129
130             res = self.search(user_dn, scope=ldb.SCOPE_BASE,
131                               expression="objectclass=*",
132                               attrs=["objectSid"])
133             assert len(res) == 1
134             user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
135             
136             try:
137                 idmap = IDmapDB(lp=self.lp)
138
139                 user = pwd.getpwnam(unixname)
140                 # setup ID mapping for this UID
141                 
142                 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
143
144             except KeyError:
145                 pass
146
147             #  modify the userAccountControl to remove the disabled bit
148             self.enable_account(user_dn)
149         except:
150             self.transaction_cancel()
151             raise
152         self.transaction_commit()
153
154     def setpassword(self, filter, password):
155         """Set a password on a user record
156         
157         :param filter: LDAP filter to find the user (eg samccountname=name)
158         :param password: Password for the user
159         """
160         # connect to the sam 
161         self.transaction_start()
162         try:
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)
170
171             res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE, 
172                               expression=filter,
173                               attrs=[])
174             assert(len(res) == 1)
175             user_dn = res[0].dn
176
177             setpw = """
178     dn: %s
179     changetype: modify
180     replace: userPassword
181     userPassword: %s
182     """ % (user_dn, password)
183
184             self.modify_ldif(setpw)
185
186             #  modify the userAccountControl to remove the disabled bit
187             self.enable_account(user_dn)
188         except:
189             self.transaction_cancel()
190             raise
191         self.transaction_commit()
192
193     def set_domain_sid(self, sid):
194         """Change the domain SID used by this SamDB.
195
196         :param sid: The new domain sid to use.
197         """
198         glue.samdb_set_domain_sid(self, sid)
199
200     def attach_schema_from_ldif(self, pf, df):
201         glue.dsdb_attach_schema_from_ldif_file(self, pf, df)
202
203     def set_invocation_id(self, invocation_id):
204         """Set the invocation id for this SamDB handle.
205         
206         :param invocation_id: GUID of the invocation id.
207         """
208         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
209
210     def setexpiry(self, user, expiry_seconds, noexpiry):
211         """Set the password expiry for a user
212         
213         :param expiry_seconds: expiry time from now in seconds
214         :param noexpiry: if set, then don't expire password
215         """
216         self.transaction_start()
217         try:
218             res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
219                               expression=("(samAccountName=%s)" % user),
220                               attrs=["userAccountControl", "accountExpires"])
221             assert len(res) == 1
222             userAccountControl = int(res[0]["userAccountControl"][0])
223             accountExpires     = int(res[0]["accountExpires"][0])
224             if noexpiry:
225                 userAccountControl = userAccountControl | 0x10000
226                 accountExpires = 0
227             else:
228                 userAccountControl = userAccountControl & ~0x10000
229                 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))
230
231             mod = """
232     dn: %s
233     changetype: modify
234     replace: userAccountControl
235     userAccountControl: %u
236     replace: accountExpires
237     accountExpires: %u
238     """ % (res[0].dn, userAccountControl, accountExpires)
239             # now change the database
240             self.modify_ldif(mod)
241         except:
242             self.transaction_cancel()
243             raise
244         self.transaction_commit();