947c46079f55d71922c031e6fab5ae41a8549b94
[ira/wip.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 enable_account(self, user_dn):
69         """Enable an account.
70         
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
81
82         mod = """
83 dn: %s
84 changetype: modify
85 replace: userAccountControl
86 userAccountControl: %u
87 """ % (user_dn, userAccountControl)
88         self.modify_ldif(mod)
89
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]
97
98     def newuser(self, username, unixname, password):
99         """add a new user record.
100         
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
104         """
105         # connect to the sam 
106         self.transaction_start()
107         try:
108             domain_dn = self.domain_dn()
109             assert(domain_dn is not None)
110             user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
111
112             #
113             #  the new user record. note the reliance on the samdb module to 
114             #  fill in a sid, guid etc
115             #
116             #  now the real work
117             self.add({"dn": user_dn, 
118                 "sAMAccountName": username,
119                 "userPassword": password,
120                 "objectClass": "user"})
121
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])
127             
128             try:
129                 idmap = IDmapDB(lp=self.lp)
130
131                 user = pwd.getpwnam(unixname)
132                 # setup ID mapping for this UID
133                 
134                 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
135
136             except KeyError:
137                 pass
138
139             #  modify the userAccountControl to remove the disabled bit
140             self.enable_account(user_dn)
141         except:
142             self.transaction_cancel()
143             raise
144         self.transaction_commit()
145
146     def setpassword(self, filter, password):
147         """Set a password on a user record
148         
149         :param filter: LDAP filter to find the user (eg samccountname=name)
150         :param password: Password for the user
151         """
152         # connect to the sam 
153         self.transaction_start()
154         try:
155             # find the DNs for the domain
156             res = self.search("", scope=ldb.SCOPE_BASE, 
157                               expression="(defaultNamingContext=*)", 
158                               attrs=["defaultNamingContext"])
159             assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
160             domain_dn = res[0]["defaultNamingContext"][0]
161             assert(domain_dn is not None)
162
163             res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE, 
164                               expression=filter,
165                               attrs=[])
166             assert(len(res) == 1)
167             user_dn = res[0].dn
168
169             setpw = """
170     dn: %s
171     changetype: modify
172     replace: userPassword
173     userPassword: %s
174     """ % (user_dn, password)
175
176             self.modify_ldif(setpw)
177
178             #  modify the userAccountControl to remove the disabled bit
179             self.enable_account(user_dn)
180         except:
181             self.transaction_cancel()
182             raise
183         self.transaction_commit()
184
185     def set_domain_sid(self, sid):
186         """Change the domain SID used by this SamDB.
187
188         :param sid: The new domain sid to use.
189         """
190         glue.samdb_set_domain_sid(self, sid)
191
192     def attach_schema_from_ldif(self, pf, df):
193         glue.dsdb_attach_schema_from_ldif_file(self, pf, df)
194
195     def set_invocation_id(self, invocation_id):
196         """Set the invocation id for this SamDB handle.
197         
198         :param invocation_id: GUID of the invocation id.
199         """
200         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
201
202     def setexpiry(self, user, expiry_seconds, noexpiry):
203         """Set the password expiry for a user
204         
205         :param expiry_seconds: expiry time from now in seconds
206         :param noexpiry: if set, then don't expire password
207         """
208         self.transaction_start()
209         try:
210             res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
211                               expression=("(samAccountName=%s)" % user),
212                               attrs=["userAccountControl", "accountExpires"])
213             assert len(res) == 1
214             userAccountControl = int(res[0]["userAccountControl"][0])
215             accountExpires     = int(res[0]["accountExpires"][0])
216             if noexpiry:
217                 userAccountControl = userAccountControl | 0x10000
218                 accountExpires = 0
219             else:
220                 userAccountControl = userAccountControl & ~0x10000
221                 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))
222
223             mod = """
224     dn: %s
225     changetype: modify
226     replace: userAccountControl
227     userAccountControl: %u
228     replace: accountExpires
229     accountExpires: %u
230     """ % (res[0].dn, userAccountControl, accountExpires)
231             # now change the database
232             self.modify_ldif(mod)
233         except:
234             self.transaction_cancel()
235             raise
236         self.transaction_commit();