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