ms_forest_updates_markdown: Write a parser for the forest updates .md
[nivanova/samba-autobuild/.git] / python / samba / ms_forest_updates_markdown.py
1 # Create forest updates ldif from Github markdown
2 #
3 # Each update is converted to an ldif then gets written to a corresponding
4 # .LDF output file or stored in a dictionary.
5 #
6 # Only add updates can generally be applied.
7 #
8 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2017
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
23 """Generate LDIF from Github documentation."""
24
25 import re
26 import os
27 import markdown
28 import xml.etree.ElementTree as ET
29
30
31 # Display specifier updates or otherwise (ignored in forest_update.py)
32 def noop(description, attributes, sd):
33     return (None, None, [], None)
34
35
36 # ACE addition updates (ignored in forest_update.py)
37 def parse_grant(description, attributes, sd):
38     return ('modify', None, [], sd if sd.lower() != 'n/a' else None)
39
40
41 # Addition of new objects to the directory (most are applied in forest_update.py)
42 def parse_add(description, attributes, sd):
43     dn = extract_dn(description)
44     return ('add', dn, extract_attrib(dn, attributes), sd if sd.lower() != 'n/a' else None)
45
46
47 # Set of a particular attribute (ignored in forest_update.py)
48 def parse_set(description, attributes, sd):
49     return ('modify', extract_dn_or_none(description),
50             extract_replace_attrib(attributes),
51             sd if sd.lower() != 'n/a' else None)
52
53
54 # Set of a particular ACE (ignored in forest_update.py)
55 # The general issue is that the list of DNs must be generated dynamically
56 def parse_ace(description, attributes, sd):
57
58     def extract_dn_ace(text):
59         if 'Sam-Domain' in text:
60             return ('${DOMAIN_DN}', 'CN=Sam-Domain,${SCHEMA_DN}')
61         elif 'Domain-DNS' in text:
62             return ('${...}', 'CN=Domain-DNS,${SCHEMA_DN}')
63
64         return None
65
66     return [('modify', extract_dn_ace(description)[0],
67              ['replace: nTSecurityDescriptor',
68               'nTSecurityDescriptor: ${DOMAIN_SCHEMA_SD}%s' % sd], None),
69             ('modify', extract_dn_ace(description)[1],
70              ['replace: defaultSecurityDescriptor',
71               'defaultSecurityDescriptor: ${OLD_SAMBA_SD}%s' % sd], None)]
72
73
74 # We are really only interested in 'Created' items
75 operation_map = {
76     # modify
77     'Granting': parse_grant,
78     # add
79     'Created': parse_add,
80     # modify
81     'Set': parse_set,
82     # modify
83     'Added ACE': parse_ace,
84     # modify
85     'Updated': parse_set,
86     # unknown
87     'Call': noop
88 }
89
90
91 def extract_dn(text):
92     """
93     Extract a DN from the textual description
94     :param text:
95     :return: DN in string form
96     """
97     text = text.replace(' in the Schema partition.', ',${SCHEMA_DN}')
98     text = text.replace(' in the Configuration partition.', ',${CONFIG_DN}')
99     dn = re.search('([CDO][NCU]=.*?,)*([CDO][NCU]=.*)', text).group(0)
100
101     # This should probably be also fixed upstream
102     if dn == 'CN=ad://ext/AuthenticationSilo,CN=Claim Types,CN=Claims Configuration,CN=Services':
103         return 'CN=ad://ext/AuthenticationSilo,CN=Claim Types,CN=Claims Configuration,CN=Services,${CONFIG_DN}'
104
105     return dn
106
107
108 def extract_dn_or_none(text):
109     """
110     Same as above, but returns None if it doesn't work
111     :param text:
112     :return: DN or None
113     """
114     try:
115         return extract_dn(text)
116     except:
117         return None
118
119
120 def save_ldif(filename, answers, out_folder):
121     """
122     Save ldif to disk for each updates
123     :param filename: filename use ([OPERATION NUM]-{GUID}.ldif)
124     :param answers: array of tuples generated with earlier functions
125     :param out_folder: folder to prepend
126     """
127     path = os.path.join(out_folder, filename)
128     with open(path, 'w') as ldif:
129         for answer in answers:
130             change, dn, attrib, sd = answer
131             ldif.write('dn: %s\n' % dn)
132             ldif.write('changetype: %s\n' % change)
133             if len(attrib) > 0:
134                 ldif.write('\n'.join(attrib) + '\n')
135             if sd is not None:
136                 ldif.write('nTSecurityDescriptor: D:%s\n' % sd)
137             ldif.write('-\n\n')
138
139
140 def save_array(guid, answers, out_dict):
141     """
142     Save ldif to an output dictionary
143     :param guid: GUID to store
144     :param answers: array of tuples generated with earlier functions
145     :param out_dict: output dictionary
146     """
147     ldif = ''
148     for answer in answers:
149         change, dn, attrib, sd = answer
150         ldif += 'dn: %s\n' % dn
151         ldif += 'changetype: %s\n' % change
152         if len(attrib) > 0:
153             ldif += '\n'.join(attrib) + '\n'
154         if sd is not None:
155             ldif += 'nTSecurityDescriptor: D:%s\n' % sd
156         ldif += '-\n\n'
157
158     out_dict[guid] = ldif
159
160
161 def extract_attrib(dn, attributes):
162     """
163     Extract the attributes as an array from the attributes column
164     :param dn: parsed from markdown
165     :param attributes: from markdown
166     :return: attribute array (ldif-type format)
167     """
168     attrib = [x.lstrip('- ') for x in attributes.split('-   ') if x.lower() != 'n/a' and x != '']
169     attrib = [x.replace(': True', ': TRUE') if x.endswith(': True') else x for x in attrib]
170     attrib = [x.replace(': False', ': FALSE') if x.endswith(': False') else x for x in attrib]
171     # We only have one such value, we may as well skip them all consistently
172     attrib = [x for x in attrib if not x.lower().startswith('msds-claimpossiblevalues')]
173
174     return attrib
175
176
177 def extract_replace_attrib(attributes):
178     """
179     Extract the attributes as an array from the attributes column
180     (for replace)
181     :param attributes: from markdown
182     :return: attribute array (ldif-type format)
183     """
184     lines = [x.lstrip('- ') for x in attributes.split('-   ') if x.lower() != 'n/a' and x != '']
185     lines = [('replace: %s' % line.split(':')[0], line) for line in lines]
186     lines = [line for pair in lines for line in pair]
187     return lines
188
189
190 def innertext(tag):
191     return (tag.text or '') + \
192         ''.join(innertext(e) for e in tag) + \
193         (tag.tail or '')
194
195
196 def read_ms_markdown(in_file, out_folder=None, out_dict={}):
197     """
198     Read Github documentation to produce forest wide udpates
199     :param in_file: Forest-Wide-Updates.md
200     :param out_folder: output folder
201     :param out_dict: output dictionary
202     """
203
204     with open(in_file) as update_file:
205         # There is a hidden ClaimPossibleValues in this md file
206         html = markdown.markdown(re.sub(r'CN=<forest root domain.*?>',
207                                         '${FOREST_ROOT_DOMAIN}',
208                                         update_file.read()),
209                                  output_format='xhtml')
210
211     html = html.replace('CN=Schema,%ws', '${SCHEMA_DN}')
212
213     tree = ET.fromstring('<root>' + html + '</root>')
214
215     for node in tree:
216         if node.text and node.text.startswith('|Operation'):
217             # Strip first and last |
218             updates = [x[1:len(x)-1].split('|') for x in
219                        ET.tostring(node,method='text').splitlines()]
220             for update in updates[2:]:
221                 output = re.match('Operation (\d+): {(.*)}', update[0])
222                 if output:
223                     # print output.group(1), output.group(2)
224                     guid = output.group(2)
225                     filename = "%s-{%s}.ldif" % (output.group(1).zfill(4), guid)
226
227                 found = False
228
229                 if update[3].startswith('Created') or update[1].startswith('Added ACE'):
230                     # Trigger the security descriptor code
231                     # Reduce info to just the security descriptor
232                     update[3] = update[3].split(':')[-1]
233
234                     result = parse_ace(update[1], update[2], update[3])
235
236                     if filename and out_folder is not None:
237                         save_ldif(filename, result, out_folder)
238                     else:
239                         save_array(guid, result, out_dict)
240
241                     continue
242
243                 for operation in operation_map:
244                     if update[1].startswith(operation):
245                         found = True
246
247                         result = operation_map[operation](update[1], update[2], update[3])
248
249                         if filename and out_folder is not None:
250                             save_ldif(filename, [result], out_folder)
251                         else:
252                             save_array(guid, [result], out_dict)
253
254                         break
255
256                 if not found:
257                     raise Exception(update)
258
259             # print ET.tostring(node, method='text')
260
261 if __name__ == '__main__':
262     import sys
263
264     out_folder = ''
265
266     if len(sys.argv) == 0:
267         print >>sys.stderr, "Usage: %s <Forest-Wide-Updates.md> [<output folder>]" % (sys.argv[0])
268         sys.exit(1)
269
270     in_file = sys.argv[1]
271     if len(sys.argv) > 2:
272         out_folder = sys.argv[2]
273
274     read_ms_markdown(in_file, out_folder)