Ivan Suzdal | 184c4e3 | 2018-06-06 13:55:30 +0400 | [diff] [blame] | 1 | from lxml.etree import Element, SubElement, tostring |
| 2 | from subprocess import Popen, PIPE |
| 3 | import shlex |
| 4 | import re |
| 5 | import datetime |
| 6 | |
| 7 | import salt.ext.six as six |
| 8 | |
| 9 | def normalize_id(id, |
| 10 | xccdf_version='1.2', |
| 11 | typeof='profile', |
| 12 | vendor='mirantis'): |
| 13 | |
| 14 | if xccdf_version == '1.2': |
| 15 | if not re.match('^xccdf_[^_]+_{}_.+'.format(typeof), id): |
| 16 | return 'xccdf_org.{0}.content_{1}_{2}'.format(vendor, typeof, id) |
| 17 | return id |
| 18 | |
| 19 | def build_tailoring(data, id): |
| 20 | xccdf_version = data.get('xccdf_version', '1.2') |
| 21 | ns = {None: 'http://checklists.nist.gov/xccdf/{}'.format(xccdf_version)} |
| 22 | tid = normalize_id(id, xccdf_version, typeof='tailoring') |
| 23 | pid = normalize_id(data['profile'], xccdf_version, vendor='customer') |
| 24 | ext = normalize_id(data['extends'], xccdf_version) |
| 25 | tailoring = Element('Tailoring', nsmap=ns, id=tid) |
| 26 | tailoring.append(Element('benchmark', {'href': ext})) |
| 27 | |
| 28 | now = datetime.datetime.now().isoformat() |
| 29 | version = SubElement(tailoring, 'version', time=now).text = '1' |
| 30 | |
| 31 | profile = SubElement(tailoring, 'Profile', id=pid, extends=ext) |
| 32 | |
| 33 | title = SubElement(profile, 'title').text = \ |
| 34 | 'Extends {}'.format(ext) |
| 35 | |
| 36 | for key, value in six.iteritems(data.get('values', {})): |
| 37 | idref = normalize_id(key, xccdf_version, typeof='value') |
| 38 | elem = SubElement(profile, 'set-value', idref=idref) |
| 39 | elem.text = str(value) |
| 40 | return tostring(tailoring, pretty_print=True) |
| 41 | |
| 42 | def run(cmd, cwd=None): |
| 43 | # The Popen used here because the __salt__['cmd.run'] returns only stdout |
| 44 | proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE, cwd=cwd) |
| 45 | (stdout, stderr) = proc.communicate() |
| 46 | return stdout, stderr, proc.returncode |