Merge branch 'v4-0-test' of git://git.samba.org/samba into 4-0-local
[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
29 class SamDB(samba.Ldb):
30     """The SAM database."""
31     def __init__(self, url=None, session_info=None, credentials=None, 
32                  modules_dir=None, lp=None):
33         """Open the Sam Database.
34
35         :param url: URL of the database.
36         """
37         super(SamDB, self).__init__(session_info=session_info, credentials=credentials,
38                                     modules_dir=modules_dir, lp=lp)
39         assert misc.dsdb_set_global_schema(self) == 0
40         if url:
41             self.connect(url)
42
43     def add_foreign(self, domaindn, sid, desc):
44         """Add a foreign security principle."""
45         add = """
46 dn: CN=%s,CN=ForeignSecurityPrincipals,%s
47 objectClass: top
48 objectClass: foreignSecurityPrincipal
49 description: %s
50         """ % (sid, domaindn, desc)
51         # deliberately ignore errors from this, as the records may
52         # already exist
53         for msg in self.parse_ldif(add):
54             self.add(msg[1])
55
56     def setup_name_mapping(self, domaindn, sid, unixname):
57         """Setup a mapping between a sam name and a unix name.
58         
59         :param domaindn: DN of the domain.
60         :param sid: SID of the NT-side of the mapping.
61         :param unixname: Unix name to map to.
62         """
63         res = self.search(domaindn, ldb.SCOPE_SUBTREE, 
64                          "objectSid=%s" % sid, ["dn"])
65         assert len(res) == 1, "Failed to find record for objectSid %s" % sid
66
67         mod = """
68 dn: %s
69 changetype: modify
70 replace: unixName
71 unixName: %s
72 """ % (res[0].dn, unixname)
73         self.modify(self.parse_ldif(mod).next()[1])
74
75     def enable_account(self, user_dn):
76         """Enable an account.
77         
78         :param user_dn: Dn of the account to enable.
79         """
80         res = self.search(user_dn, SCOPE_ONELEVEL, None, ["userAccountControl"])
81         assert len(res) == 1
82         userAccountControl = res[0].userAccountControl
83         userAccountControl = userAccountControl - 2 # remove disabled bit
84         mod = """
85 dn: %s
86 changetype: modify
87 replace: userAccountControl
88 userAccountControl: %u
89 """ % (user_dn, userAccountControl)
90         self.modify_ldif(mod)
91
92     def newuser(self, username, unixname, password):
93         """add a new user record.
94         
95         :param username: Name of the new user.
96         :param unixname: Name of the unix user to map to.
97         :param password: Password for the new user
98         """
99         # connect to the sam 
100         self.transaction_start()
101
102         # find the DNs for the domain and the domain users group
103         res = self.search("", scope=ldb.SCOPE_BASE, 
104                           expression="(defaultNamingContext=*)", 
105                           attrs=["defaultNamingContext"])
106         assert(len(res) == 1 and res[0].defaultNamingContext is not None)
107         domain_dn = res[0]["defaultNamingContext"][0]
108         assert(domain_dn is not None)
109         dom_users = self.searchone(basedn=domain_dn, attribute="dn", 
110                                    expression="name=Domain Users")
111         assert(dom_users is not None)
112
113         user_dn = "CN=%s,CN=Users,%s" % (username, domain_dn)
114
115         #
116         #  the new user record. note the reliance on the samdb module to fill
117         #  in a sid, guid etc
118         #
119         #  now the real work
120         self.add({"dn": user_dn, 
121             "sAMAccountName": username,
122             "unixName": unixname,
123             "sambaPassword": password,
124             "objectClass": "user"})
125
126         #  add the user to the users group as well
127         modgroup = """
128 dn: %s
129 changetype: modify
130 add: member
131 member: %s
132 """ % (dom_users, user_dn)
133
134
135         self.modify(modgroup)
136
137         #  modify the userAccountControl to remove the disabled bit
138         enable_account(self, user_dn)
139         self.transaction_commit()
140
141     def set_domain_sid(self, sid):
142         """Change the domain SID used by this SamDB.
143
144         :param sid: The new domain sid to use.
145         """
146         misc.samdb_set_domain_sid(self, sid)
147
148     def attach_schema_from_ldif(self, pf, df):
149         misc.dsdb_attach_schema_from_ldif_file(self, pf, df)
150
151     def set_invocation_id(self, invocation_id):
152         """Set the invocation id for this SamDB handle.
153         
154         :param invocation_id: GUID of the invocation id.
155         """
156         misc.dsdb_set_ntds_invocation_id(self, invocation_id)