Merge branch 'v4-0-test' of ssh://git.samba.org/data/git/samba into v4-0-wsgi
[sfrench/samba-autobuild/.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 misc
27 import ldb
28 from samba.idmap import IDmapDB
29 import pwd
30
31 __docformat__ = "restructuredText"
32
33 class SamDB(samba.Ldb):
34     """The SAM database."""
35
36     def __init__(self, url=None, session_info=None, credentials=None, 
37                  modules_dir=None, lp=None):
38         """Open the Sam Database.
39
40         :param url: URL of the database.
41         """
42         self.lp = lp
43         super(SamDB, self).__init__(session_info=session_info, credentials=credentials,
44                                     modules_dir=modules_dir, lp=lp)
45         assert misc.dsdb_set_global_schema(self) == 0
46         if url:
47             self.connect(url)
48         else:
49             self.connect(lp.get("sam database"))
50
51     def connect(self, url):
52         super(SamDB, self).connect(misc.private_path(self.lp, url))
53
54     def add_foreign(self, domaindn, sid, desc):
55         """Add a foreign security principle."""
56         add = """
57 dn: CN=%s,CN=ForeignSecurityPrincipals,%s
58 objectClass: top
59 objectClass: foreignSecurityPrincipal
60 description: %s
61         """ % (sid, domaindn, desc)
62         # deliberately ignore errors from this, as the records may
63         # already exist
64         for msg in self.parse_ldif(add):
65             self.add(msg[1])
66
67     def enable_account(self, user_dn):
68         """Enable an account.
69         
70         :param user_dn: Dn of the account to enable.
71         """
72         res = self.search(user_dn, ldb.SCOPE_BASE, None, ["userAccountControl"])
73         assert len(res) == 1
74         userAccountControl = res[0]["userAccountControl"][0]
75         userAccountControl = int(userAccountControl)
76         if (userAccountControl & 0x2):
77             userAccountControl = userAccountControl & ~0x2 # remove disabled bit
78         if (userAccountControl & 0x20):
79             userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit
80
81         mod = """
82 dn: %s
83 changetype: modify
84 replace: userAccountControl
85 userAccountControl: %u
86 """ % (user_dn, userAccountControl)
87         self.modify_ldif(mod)
88
89     def newuser(self, username, unixname, password):
90         """add a new user record.
91         
92         :param username: Name of the new user.
93         :param unixname: Name of the unix user to map to.
94         :param password: Password for the new user
95         """
96         # connect to the sam 
97         self.transaction_start()
98
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         domain_dn = res[0]["defaultNamingContext"][0]
105         assert(domain_dn is not None)
106         user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
107
108         #
109         #  the new user record. note the reliance on the samdb module to fill
110         #  in a sid, guid etc
111         #
112         #  now the real work
113         self.add({"dn": user_dn, 
114             "sAMAccountName": username,
115             "sambaPassword": password,
116             "objectClass": "user"})
117
118         res = self.search(user_dn, scope=ldb.SCOPE_BASE,
119                           expression="objectclass=*",
120                           attrs=["objectSid"])
121         assert(len(res) == 1)
122         user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
123         
124         
125         try:
126             idmap = IDmapDB(lp=self.lp)
127
128             user = pwd.getpwnam(unixname)
129             # setup ID mapping for this UID
130             
131             idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2])
132
133         except KeyError:
134             pass
135
136         #  modify the userAccountControl to remove the disabled bit
137         self.enable_account(user_dn)
138         self.transaction_commit()
139
140     def setpassword(self, filter, password):
141         """Set a password on a user record
142         
143         :param filter: LDAP filter to find the user (eg samccountname=name)
144         :param password: Password for the user
145         """
146         # connect to the sam 
147         self.transaction_start()
148
149         # find the DNs for the domain
150         res = self.search("", scope=ldb.SCOPE_BASE, 
151                           expression="(defaultNamingContext=*)", 
152                           attrs=["defaultNamingContext"])
153         assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
154         domain_dn = res[0]["defaultNamingContext"][0]
155         assert(domain_dn is not None)
156
157         res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE, 
158                           expression=filter,
159                           attrs=[])
160         assert(len(res) == 1)
161         user_dn = res[0].dn
162
163         setpw = """
164 dn: %s
165 changetype: modify
166 replace: sambaPassword
167 sambaPassword: %s
168 """ % (user_dn, password)
169
170         self.modify_ldif(setpw)
171
172         #  modify the userAccountControl to remove the disabled bit
173         self.enable_account(user_dn)
174         self.transaction_commit()
175
176     def set_domain_sid(self, sid):
177         """Change the domain SID used by this SamDB.
178
179         :param sid: The new domain sid to use.
180         """
181         misc.samdb_set_domain_sid(self, sid)
182
183     def attach_schema_from_ldif(self, pf, df):
184         misc.dsdb_attach_schema_from_ldif_file(self, pf, df)
185
186     def set_invocation_id(self, invocation_id):
187         """Set the invocation id for this SamDB handle.
188         
189         :param invocation_id: GUID of the invocation id.
190         """
191         misc.dsdb_set_ntds_invocation_id(self, invocation_id)