s4-provision Add an invalid names check for 'domain == netbiosname'
[nivanova/samba-autobuild/.git] / source4 / scripting / python / samba / schema.py
1 #
2 # Unix SMB/CIFS implementation.
3 # backend code for provisioning a Samba4 server
4 #
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008-2009
7 # Copyright (C) Oliver Liebel <oliver@itc.li> 2008-2009
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 """Functions for setting up a Samba Schema."""
24
25 from base64 import b64encode
26 from samba import read_and_sub_file, substitute_var, check_all_substituted
27 from samba.dcerpc import security
28 from samba.ms_schema import read_ms_schema
29 from samba.ndr import ndr_pack
30 from samba.samdb import SamDB
31 from samba import dsdb
32 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL
33 import os
34
35 def get_schema_descriptor(domain_sid):
36     sddl = "O:SAG:SAD:AI(OA;;CR;e12b56b6-0a95-11d1-adbb-00c04fd8d5cd;;SA)" \
37            "(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
38            "(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
39            "(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
40            "(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)" \
41            "(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)" \
42            "(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)" \
43            "(A;CI;RPLCLORC;;;AU)" \
44            "(A;CI;RPWPCRCCLCLORCWOWDSW;;;SA)" \
45            "(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
46            "(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
47            "(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)" \
48            "(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)" \
49            "(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)" \
50            "(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)" \
51            "(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;ER)" \
52            "(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ER)" \
53            "S:(AU;SA;WPCCDCWOWDSDDTSW;;;WD)" \
54            "(AU;CISA;WP;;;WD)" \
55            "(AU;SA;CR;;;BA)" \
56            "(AU;SA;CR;;;DU)" \
57            "(OU;SA;CR;e12b56b6-0a95-11d1-adbb-00c04fd8d5cd;;WD)" \
58            "(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)"
59     sec = security.descriptor.from_sddl(sddl, domain_sid)
60     return ndr_pack(sec)
61
62
63 class Schema(object):
64
65     def __init__(self, setup_path, domain_sid, invocationid=None, schemadn=None,
66                  files=None, override_prefixmap=None, additional_prefixmap=None):
67         """Load schema for the SamDB from the AD schema files and
68         samba4_schema.ldif
69
70         :param samdb: Load a schema into a SamDB.
71         :param setup_path: Setup path function.
72         :param schemadn: DN of the schema
73
74         Returns the schema data loaded, to avoid double-parsing when then
75         needing to add it to the db
76         """
77
78         self.schemadn = schemadn
79         # We need to have the am_rodc=False just to keep some warnings quiet -
80         # this isn't a real SAM, so it's meaningless.
81         self.ldb = SamDB(global_schema=False, am_rodc=False)
82         if invocationid is not None:
83             self.ldb.set_invocation_id(invocationid)
84
85         self.schema_data = read_ms_schema(
86             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Attributes.txt'),
87             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Classes.txt'))
88
89         if files is not None:
90             for file in files:
91                 self.schema_data += open(file, 'r').read()
92
93         self.schema_data = substitute_var(self.schema_data,
94             {"SCHEMADN": schemadn})
95         check_all_substituted(self.schema_data)
96
97         self.schema_dn_modify = read_and_sub_file(
98             setup_path("provision_schema_basedn_modify.ldif"),
99             {"SCHEMADN": schemadn})
100
101         descr = b64encode(get_schema_descriptor(domain_sid))
102         self.schema_dn_add = read_and_sub_file(
103             setup_path("provision_schema_basedn.ldif"),
104             {"SCHEMADN": schemadn, "DESCRIPTOR": descr})
105
106         if override_prefixmap is not None:
107             self.prefixmap_data = override_prefixmap
108         else:
109             self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()
110
111         if additional_prefixmap is not None:
112             for map in additional_prefixmap:
113                 self.prefixmap_data += "%s\n" % map
114
115         self.prefixmap_data = b64encode(self.prefixmap_data)
116
117         # We don't actually add this ldif, just parse it
118         prefixmap_ldif = "dn: cn=schema\nprefixMap:: %s\n\n" % self.prefixmap_data
119         self.set_from_ldif(prefixmap_ldif, self.schema_data)
120
121     def set_from_ldif(self, pf, df):
122         dsdb._dsdb_set_schema_from_ldif(self.ldb, pf, df)
123
124     def write_to_tmp_ldb(self, schemadb_path):
125         self.ldb.connect(url=schemadb_path)
126         self.ldb.transaction_start()
127         try:
128             self.ldb.add_ldif("""dn: @ATTRIBUTES
129 linkID: INTEGER
130
131 dn: @INDEXLIST
132 @IDXATTR: linkID
133 @IDXATTR: attributeSyntax
134 """)
135             # These bits of LDIF are supplied when the Schema object is created
136             self.ldb.add_ldif(self.schema_dn_add)
137             self.ldb.modify_ldif(self.schema_dn_modify)
138             self.ldb.add_ldif(self.schema_data)
139         except Exception:
140             self.ldb.transaction_cancel()
141             raise
142         else:
143             self.ldb.transaction_commit()
144
145     # Return a hash with the forward attribute as a key and the back as the
146     # value
147     def linked_attributes(self):
148         return get_linked_attributes(self.schemadn, self.ldb)
149
150     def dnsyntax_attributes(self):
151         return get_dnsyntax_attributes(self.schemadn, self.ldb)
152
153     def convert_to_openldap(self, target, mapping):
154         return dsdb._dsdb_convert_schema_to_openldap(self.ldb, target, mapping)
155
156
157 # Return a hash with the forward attribute as a key and the back as the value 
158 def get_linked_attributes(schemadn,schemaldb):
159     attrs = ["linkID", "lDAPDisplayName"]
160     res = schemaldb.search(expression="(&(linkID=*)(!(linkID:1.2.840.113556.1.4.803:=1))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))", base=schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
161     attributes = {}
162     for i in range (0, len(res)):
163         expression = "(&(objectclass=attributeSchema)(linkID=%d)(attributeSyntax=2.5.5.1))" % (int(res[i]["linkID"][0])+1)
164         target = schemaldb.searchone(basedn=schemadn, 
165                                      expression=expression, 
166                                      attribute="lDAPDisplayName", 
167                                      scope=SCOPE_SUBTREE)
168         if target is not None:
169             attributes[str(res[i]["lDAPDisplayName"])]=str(target)
170
171     return attributes
172
173
174 def get_dnsyntax_attributes(schemadn,schemaldb):
175     res = schemaldb.search(
176         expression="(&(!(linkID=*))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))",
177         base=schemadn, scope=SCOPE_ONELEVEL,
178         attrs=["linkID", "lDAPDisplayName"])
179     attributes = []
180     for i in range (0, len(res)):
181         attributes.append(str(res[i]["lDAPDisplayName"]))
182     return attributes
183
184
185 def ldb_with_schema(setup_dir=None,
186         schemadn="cn=schema,cn=configuration,dc=example,dc=com", 
187         domainsid=None,
188         override_prefixmap=None):
189     """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
190
191     :param setup_dir: Setup path
192     :param schemadn: DN of the schema
193     :param serverdn: DN of the server
194
195     Returns the schema data loaded as an object, with .ldb being a
196     new ldb with the schema loaded.  This allows certain tests to
197     operate without a remote or local schema.
198     """
199
200     def setup_path(file):
201         return os.path.join(setup_dir, file)
202
203     if domainsid is None:
204         domainsid = security.random_sid()
205     else:
206         domainsid = security.dom_sid(domainsid)
207     return Schema(setup_path, domainsid, schemadn=schemadn,
208         override_prefixmap=override_prefixmap)