Move domain DN determination out of newuser function.
[vlendec/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 domain_dn(self):
90         # find the DNs for the domain and the domain users group
91         res = self.search("", scope=ldb.SCOPE_BASE, 
92                           expression="(defaultNamingContext=*)", 
93                           attrs=["defaultNamingContext"])
94         assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
95         return res[0]["defaultNamingContext"][0]
96
97     def newuser(self, username, unixname, password):
98         """add a new user record.
99         
100         :param username: Name of the new user.
101         :param unixname: Name of the unix user to map to.
102         :param password: Password for the new user
103         """
104         # connect to the sam 
105         self.transaction_start()
106
107         domain_dn = self.domain_dn()
108         assert(domain_dn is not None)
109         user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
110
111         #
112         #  the new user record. note the reliance on the samdb module to fill
113         #  in a sid, guid etc
114         #
115         #  now the real work
116         self.add({"dn": user_dn, 
117             "sAMAccountName": username,
118             "userPassword": password,
119             "objectClass": "user"})
120
121         res = self.search(user_dn, scope=ldb.SCOPE_BASE,
122                           expression="objectclass=*",
123                           attrs=["objectSid"])
124         assert(len(res) == 1)
125         user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0])
126         
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         self.transaction_commit()
142
143     def setpassword(self, filter, password):
144         """Set a password on a user record
145         
146         :param filter: LDAP filter to find the user (eg samccountname=name)
147         :param password: Password for the user
148         """
149         # connect to the sam 
150         self.transaction_start()
151
152         # find the DNs for the domain
153         res = self.search("", scope=ldb.SCOPE_BASE, 
154                           expression="(defaultNamingContext=*)", 
155                           attrs=["defaultNamingContext"])
156         assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None)
157         domain_dn = res[0]["defaultNamingContext"][0]
158         assert(domain_dn is not None)
159
160         res = self.search(domain_dn, scope=ldb.SCOPE_SUBTREE, 
161                           expression=filter,
162                           attrs=[])
163         assert(len(res) == 1)
164         user_dn = res[0].dn
165
166         setpw = """
167 dn: %s
168 changetype: modify
169 replace: userPassword
170 userPassword: %s
171 """ % (user_dn, password)
172
173         self.modify_ldif(setpw)
174
175         #  modify the userAccountControl to remove the disabled bit
176         self.enable_account(user_dn)
177         self.transaction_commit()
178
179     def set_domain_sid(self, sid):
180         """Change the domain SID used by this SamDB.
181
182         :param sid: The new domain sid to use.
183         """
184         misc.samdb_set_domain_sid(self, sid)
185
186     def attach_schema_from_ldif(self, pf, df):
187         misc.dsdb_attach_schema_from_ldif_file(self, pf, df)
188
189     def set_invocation_id(self, invocation_id):
190         """Set the invocation id for this SamDB handle.
191         
192         :param invocation_id: GUID of the invocation id.
193         """
194         misc.dsdb_set_ntds_invocation_id(self, invocation_id)