s4:provision Pass in the invoication ID and NTDS Settings DN to Schema()
[metze/samba/wip.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 ms_schema import read_ms_schema
27 from samba.dcerpc import security
28 from samba import read_and_sub_file, substitute_var, check_all_substituted
29 from samba.samdb import SamDB
30 from samba import Ldb
31 from samba.ndr import ndr_pack
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;89e95b76-444d-4c62-991a-0facbeda640c" \
37            ";;ER)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)(OA;;CR;1131f6ad-9c07-1" \
38            "1d1-f79f-00c04fc2dcd2;;ER)(OA;;CR;e12b56b6-0a95-11d1-adbb-00c04fd8d5cd;;SA)(O" \
39            "A;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)(OA;;CR;1131f6aa-9c07-11d1-f79" \
40            "f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1" \
41            "131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04" \
42            "fc2dcd2;;BA)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)(OA;;CR;1131f6aa" \
43            "-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2" \
44            ";;ED)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ad-9c07-1" \
45            "1d1-f79f-00c04fc2dcd2;;ED)(A;;RPWPCCDCLCLORCWOWDSDDTSW;;;LA)(A;CI;RPWPCRCCLCL" \
46            "ORCWOWDSW;;;SA)(A;CI;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)S:(O" \
47            "U;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)(OU;SA;CR;e12b56b6-0a95-11d1" \
48            "-adbb-00c04fd8d5cd;;WD)(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPCCDCWOWDSDDTSW;" \
49            ";;WD)(AU;CISA;WP;;;WD)"
50     sec = security.descriptor.from_sddl(sddl, domain_sid)
51     return ndr_pack(sec)
52
53    
54 class Schema(object):
55
56     def __init__(self, setup_path, domain_sid, invocationid=None, schemadn=None,
57                  serverdn=None, files=None, prefixmap=None):
58         """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
59         
60         :param samdb: Load a schema into a SamDB.
61         :param setup_path: Setup path function.
62         :param schemadn: DN of the schema
63         :param serverdn: DN of the server
64         
65         Returns the schema data loaded, to avoid double-parsing when then needing to add it to the db
66         """
67
68         self.schemadn = schemadn
69         self.ldb = SamDB(global_schema=False)
70         if serverdn is not None:
71             self.ldb.set_ntds_settings_dn("CN=NTDS Settings,%s" % serverdn)
72         if invocationid is not None:
73             self.ldb.set_invocation_id(invocationid)
74
75         self.schema_data = read_ms_schema(
76             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Attributes.txt'),
77             setup_path('ad-schema/MS-AD_Schema_2K8_R2_Classes.txt'))
78
79         if files is not None:
80             for file in files:
81                 self.schema_data += open(file, 'r').read()
82
83         self.schema_data = substitute_var(self.schema_data,
84             {"SCHEMADN": schemadn})
85         check_all_substituted(self.schema_data)
86
87         self.schema_dn_modify = read_and_sub_file(
88             setup_path("provision_schema_basedn_modify.ldif"),
89             {"SCHEMADN": schemadn, "SERVERDN": serverdn})
90
91         descr = b64encode(get_schema_descriptor(domain_sid))
92         self.schema_dn_add = read_and_sub_file(
93             setup_path("provision_schema_basedn.ldif"),
94             {"SCHEMADN": schemadn, "DESCRIPTOR": descr})
95
96         self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()
97
98         if prefixmap is not None:
99             for map in prefixmap:
100                 self.prefixmap_data += "%s\n" % map
101
102         self.prefixmap_data = b64encode(self.prefixmap_data)
103
104         # We don't actually add this ldif, just parse it
105         prefixmap_ldif = "dn: cn=schema\nprefixMap:: %s\n\n" % self.prefixmap_data
106         self.ldb.set_schema_from_ldif(prefixmap_ldif, self.schema_data)
107
108     def write_to_tmp_ldb(self, schemadb_path):
109         self.ldb.connect(url=schemadb_path)
110         self.ldb.transaction_start()
111         try:
112             self.ldb.add_ldif("""dn: @ATTRIBUTES
113 linkID: INTEGER
114
115 dn: @INDEXLIST
116 @IDXATTR: linkID
117 @IDXATTR: attributeSyntax
118 """)
119             # These bits of LDIF are supplied when the Schema object is created
120             self.ldb.add_ldif(self.schema_dn_add)
121             self.ldb.modify_ldif(self.schema_dn_modify)
122             self.ldb.add_ldif(self.schema_data)
123         except:
124             self.ldb.transaction_cancel()
125             raise
126         else:
127             self.ldb.transaction_commit()
128
129     # Return a hash with the forward attribute as a key and the back as the value 
130     def linked_attributes(self):
131         return get_linked_attributes(self.schemadn, self.ldb)
132
133     def dnsyntax_attributes(self):
134         return get_dnsyntax_attributes(self.schemadn, self.ldb)
135
136 # Return a hash with the forward attribute as a key and the back as the value 
137 def get_linked_attributes(schemadn,schemaldb):
138     attrs = ["linkID", "lDAPDisplayName"]
139     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)
140     attributes = {}
141     for i in range (0, len(res)):
142         expression = "(&(objectclass=attributeSchema)(linkID=%d)(attributeSyntax=2.5.5.1))" % (int(res[i]["linkID"][0])+1)
143         target = schemaldb.searchone(basedn=schemadn, 
144                                      expression=expression, 
145                                      attribute="lDAPDisplayName", 
146                                      scope=SCOPE_SUBTREE)
147         if target is not None:
148             attributes[str(res[i]["lDAPDisplayName"])]=str(target)
149             
150     return attributes
151
152
153 def get_dnsyntax_attributes(schemadn,schemaldb):
154     res = schemaldb.search(
155         expression="(&(!(linkID=*))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))",
156         base=schemadn, scope=SCOPE_ONELEVEL,
157         attrs=["linkID", "lDAPDisplayName"])
158     attributes = []
159     for i in range (0, len(res)):
160         attributes.append(str(res[i]["lDAPDisplayName"]))
161     return attributes
162
163
164 def ldb_with_schema(setup_dir=None,
165         schemadn="cn=schema,cn=configuration,dc=example,dc=com", 
166         serverdn="cn=server,cn=servers,cn=default-first-site-name,cn=sites,cn=cn=configuration,dc=example,dc=com",
167         domainsid=None):
168     """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
169     
170     :param setup_dir: Setup path
171     :param schemadn: DN of the schema
172     :param serverdn: DN of the server
173     
174     Returns the schema data loaded as an object, with .ldb being a
175     new ldb with the schema loaded.  This allows certain tests to
176     operate without a remote or local schema.
177     """
178     
179     def setup_path(file):
180         return os.path.join(setup_dir, file)
181
182     if domainsid is None:
183         domainsid = security.random_sid()
184     else:
185         domainsid = security.dom_sid(domainsid)
186     return Schema(setup_path, domainsid, schemadn=schemadn, serverdn=serverdn)