eaa01640c64ababc13e7bb7b6af923d3579d3e22
[gd/samba-autobuild/.git] / 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, name_map={}):
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     # the schema files (and corresponding object version) that we know about
66     base_schemas = {
67        "2008_R2" : ("MS-AD_Schema_2K8_R2_Attributes.txt",
68                     "MS-AD_Schema_2K8_R2_Classes.txt",
69                     47),
70        "2012"    : ("AD_DS_Attributes__Windows_Server_2012.ldf",
71                     "AD_DS_Classes__Windows_Server_2012.ldf",
72                     56),
73        "2012_R2" : ("AD_DS_Attributes__Windows_Server_2012_R2.ldf",
74                     "AD_DS_Classes__Windows_Server_2012_R2.ldf",
75                     69),
76     }
77
78     def __init__(self, domain_sid, invocationid=None, schemadn=None,
79                  files=None, override_prefixmap=None, additional_prefixmap=None):
80         from samba.provision import setup_path
81
82         """Load schema for the SamDB from the AD schema files and
83         samba4_schema.ldif
84
85         :param samdb: Load a schema into a SamDB.
86         :param schemadn: DN of the schema
87
88         Returns the schema data loaded, to avoid double-parsing when then
89         needing to add it to the db
90         """
91
92         self.schemadn = schemadn
93         # We need to have the am_rodc=False just to keep some warnings quiet -
94         # this isn't a real SAM, so it's meaningless.
95         self.ldb = SamDB(global_schema=False, am_rodc=False)
96         if invocationid is not None:
97             self.ldb.set_invocation_id(invocationid)
98
99         self.schema_data = read_ms_schema(
100             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Attributes.txt'),
101             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Classes.txt'))
102
103         if files is not None:
104             for file in files:
105                 self.schema_data += open(file, 'r').read()
106
107         self.schema_data = substitute_var(self.schema_data,
108             {"SCHEMADN": schemadn})
109         check_all_substituted(self.schema_data)
110
111         self.schema_dn_modify = read_and_sub_file(
112             setup_path("provision_schema_basedn_modify.ldif"),
113             {"SCHEMADN": schemadn})
114
115         descr = b64encode(get_schema_descriptor(domain_sid))
116         self.schema_dn_add = read_and_sub_file(
117             setup_path("provision_schema_basedn.ldif"),
118             {"SCHEMADN": schemadn, "DESCRIPTOR": descr})
119
120         if override_prefixmap is not None:
121             self.prefixmap_data = override_prefixmap
122         else:
123             self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()
124
125         if additional_prefixmap is not None:
126             for map in additional_prefixmap:
127                 self.prefixmap_data += "%s\n" % map
128
129         self.prefixmap_data = b64encode(self.prefixmap_data)
130
131         # We don't actually add this ldif, just parse it
132         prefixmap_ldif = "dn: %s\nprefixMap:: %s\n\n" % (self.schemadn, self.prefixmap_data)
133         self.set_from_ldif(prefixmap_ldif, self.schema_data, self.schemadn)
134
135     @staticmethod
136     def default_base_schema():
137         """Returns the default base schema to use"""
138         return "2008_R2"
139
140     @staticmethod
141     def get_version(base_schema):
142         """Returns the base schema's object version, e.g. 47 for 2008_R2"""
143         return Schema.base_schemas[base_schema][2]
144
145     def set_from_ldif(self, pf, df, dn):
146         dsdb._dsdb_set_schema_from_ldif(self.ldb, pf, df, dn)
147
148     def write_to_tmp_ldb(self, schemadb_path):
149         self.ldb.connect(url=schemadb_path)
150         self.ldb.transaction_start()
151         try:
152             # These are actually ignored, as the schema has been forced
153             # when the ldb object was created, and that overrides this
154             self.ldb.add_ldif("""dn: @ATTRIBUTES
155 linkID: INTEGER
156
157 dn: @INDEXLIST
158 @IDXATTR: linkID
159 @IDXATTR: attributeSyntax
160 @IDXGUID: objectGUID
161 """)
162
163             schema_dn_add = self.schema_dn_add \
164                             + "objectGUID: 24e2ca70-b093-4ae8-84c0-2d7ac652a1b8\n"
165
166             # These bits of LDIF are supplied when the Schema object is created
167             self.ldb.add_ldif(schema_dn_add)
168             self.ldb.modify_ldif(self.schema_dn_modify)
169             self.ldb.add_ldif(self.schema_data)
170         except:
171             self.ldb.transaction_cancel()
172             raise
173         else:
174             self.ldb.transaction_commit()
175
176     # Return a hash with the forward attribute as a key and the back as the
177     # value
178     def linked_attributes(self):
179         return get_linked_attributes(self.schemadn, self.ldb)
180
181     def dnsyntax_attributes(self):
182         return get_dnsyntax_attributes(self.schemadn, self.ldb)
183
184     def convert_to_openldap(self, target, mapping):
185         return dsdb._dsdb_convert_schema_to_openldap(self.ldb, target, mapping)
186
187
188 # Return a hash with the forward attribute as a key and the back as the value
189 def get_linked_attributes(schemadn, schemaldb):
190     attrs = ["linkID", "lDAPDisplayName"]
191     res = schemaldb.search(
192         expression="(&(linkID=*)"
193                    "(!(linkID:1.2.840.113556.1.4.803:=1))"
194                    "(objectclass=attributeSchema)"
195                    "(attributeSyntax=2.5.5.1))",
196         base=schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
197     attributes = {}
198     for i in range(0, len(res)):
199         expression = ("(&(objectclass=attributeSchema)(linkID=%d)"
200                       "(attributeSyntax=2.5.5.1))" %
201                       (int(res[i]["linkID"][0])+1))
202         target = schemaldb.searchone(basedn=schemadn,
203                                      expression=expression,
204                                      attribute="lDAPDisplayName",
205                                      scope=SCOPE_SUBTREE)
206         if target is not None:
207             attributes[str(res[i]["lDAPDisplayName"])]=str(target)
208
209     return attributes
210
211
212 def get_dnsyntax_attributes(schemadn,schemaldb):
213     res = schemaldb.search(
214         expression="(&(!(linkID=*))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))",
215         base=schemadn, scope=SCOPE_ONELEVEL,
216         attrs=["linkID", "lDAPDisplayName"])
217     attributes = []
218     for i in range(0, len(res)):
219         attributes.append(str(res[i]["lDAPDisplayName"]))
220     return attributes
221
222
223 def ldb_with_schema(schemadn="cn=schema,cn=configuration,dc=example,dc=com",
224                     domainsid=None,
225                     override_prefixmap=None):
226     """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
227
228     :param schemadn: DN of the schema
229     :param serverdn: DN of the server
230
231     Returns the schema data loaded as an object, with .ldb being a
232     new ldb with the schema loaded.  This allows certain tests to
233     operate without a remote or local schema.
234     """
235
236     if domainsid is None:
237         domainsid = security.random_sid()
238     else:
239         domainsid = security.dom_sid(domainsid)
240     return Schema(domainsid, schemadn=schemadn,
241         override_prefixmap=override_prefixmap)