Passed
Pull Request — rhel8-branch (#190)
by Matěj
01:28
created

schedule_firstboot_remediation()   A

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nop 6
dl 0
loc 14
rs 9.9
c 0
b 0
f 0
1
#
2
# Copyright (C) 2013  Red Hat, Inc.
3
#
4
# This copyrighted material is made available to anyone wishing to use,
5
# modify, copy, or redistribute it subject to the terms and conditions of
6
# the GNU General Public License v.2, or (at your option) any later version.
7
# This program is distributed in the hope that it will be useful, but WITHOUT
8
# ANY WARRANTY expressed or implied, including the implied warranties of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
10
# Public License for more details.  You should have received a copy of the
11
# GNU General Public License along with this program; if not, write to the
12
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
13
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
14
# source code or documentation are not subject to the GNU General Public
15
# License and may only be used or replicated with the express permission of
16
# Red Hat, Inc.
17
#
18
# Red Hat Author(s): Vratislav Podzimek <[email protected]>
19
#
20
21
"""
22
Module with various classes and functions needed by the OSCAP addon that are
23
not specific to any installation mode (tui, gui, ks).
24
25
"""
26
27
import os
28
import tempfile
29
import subprocess
30
import zipfile
31
import tarfile
32
import textwrap
33
34
import cpioarchive
35
import re
36
import logging
37
38
from collections import namedtuple
39
import gettext
40
from functools import wraps
41
from pyanaconda.core import constants
42
from org_fedora_oscap import utils
43
44
log = logging.getLogger("anaconda")
45
46
47
# mimick pyanaconda/core/i18n.py
48
def _(string):
49
    if string:
50
        return gettext.translation("oscap-anaconda-addon", fallback=True).gettext(string)
51
    else:
52
        return ""
53
54
55
def N_(string): return string
56
57
58
# everything else should be private
59
__all__ = ["run_oscap_remediate", "get_fix_rules_pre",
60
           "extract_data", "strip_content_dir",
61
           "OSCAPaddonError"]
62
63
INSTALLATION_CONTENT_DIR = "/tmp/openscap_data/"
64
TARGET_CONTENT_DIR = "/root/openscap_data/"
65
66
SSG_DIR = "/usr/share/xml/scap/ssg/content/"
67
68
# Enable patches that set the content name at package-time
69
DEFAULT_SSG_CONTENT_NAME = ""
70
SSG_CONTENT = DEFAULT_SSG_CONTENT_NAME
71
if not SSG_CONTENT:
72
    if constants.shortProductName != 'anaconda':
73
        if constants.shortProductName == 'fedora':
74
            SSG_CONTENT = "ssg-fedora-ds.xml"
75
        else:
76
            SSG_CONTENT = (
77
                "ssg-{name}{version}-ds.xml"
78
                .format(
79
                    name=constants.shortProductName,
80
                    version=constants.productVersion.strip(".")[0]))
81
82
RESULTS_PATH = utils.join_paths(TARGET_CONTENT_DIR,
83
                                "eval_remediate_results.xml")
84
REPORT_PATH = utils.join_paths(TARGET_CONTENT_DIR,
85
                               "eval_remediate_report.html")
86
87
PRE_INSTALL_FIX_SYSTEM_ATTR = "urn:redhat:anaconda:pre"
88
89
THREAD_FETCH_DATA = "AnaOSCAPdataFetchThread"
90
91
SUPPORTED_ARCHIVES = (".zip", ".tar", ".tar.gz", ".tar.bz2", )
92
93
# buffer size for reading and writing out data (in bytes)
94
IO_BUF_SIZE = 2 * 1024 * 1024
95
96
97
class OSCAPaddonError(Exception):
98
    """Exception class for OSCAP addon related errors."""
99
100
    pass
101
102
103
class OSCAPaddonNetworkError(OSCAPaddonError):
104
    """Exception class for OSCAP addon related network errors."""
105
106
    pass
107
108
109
class ExtractionError(OSCAPaddonError):
110
    """Exception class for the extraction errors."""
111
112
    pass
113
114
115
MESSAGE_TYPE_FATAL = 0
116
MESSAGE_TYPE_WARNING = 1
117
MESSAGE_TYPE_INFO = 2
118
119
# namedtuple for messages returned from the rules evaluation
120
#   origin -- class (inherited from RuleHandler) that generated the message
121
#   type -- one of the MESSAGE_TYPE_* constants defined above
122
#   text -- the actual message that should be displayed, logged, ...
123
RuleMessage = namedtuple("RuleMessage", ["origin", "type", "text"])
124
125
126
class SubprocessLauncher(object):
127
    def __init__(self, args):
128
        self.args = args
129
        self.stdout = ""
130
        self.stderr = ""
131
        self.messages = []
132
        self.returncode = None
133
134
    def execute(self, ** kwargs):
135
        command_string = " ".join(self.args)
136
        log.info(
137
            "OSCAP addon: Executing subprocess: '{command_string}'"
138
            .format(command_string=command_string))
139
        try:
140
            proc = subprocess.Popen(self.args, stdout=subprocess.PIPE,
141
                                    stderr=subprocess.PIPE, ** kwargs)
142
        except OSError as oserr:
143
            msg = ("Failed to execute command '{command_string}': {oserr}"
144
                   .format(command_string=command_string, oserr=oserr))
145
            raise OSCAPaddonError(msg)
146
147
        (stdout, stderr) = proc.communicate()
148
        self.stdout = stdout.decode()
149
        self.stderr = stderr.decode(errors="replace")
150
        self.messages = re.findall(r'OpenSCAP Error:.*', self.stderr)
151
        self.messages = self.messages + re.findall(r'E: oscap:.*', self.stderr)
152
153
        self.returncode = proc.returncode
154
155
    def log_messages(self):
156
        for message in self.messages:
157
            log.warning("OSCAP addon: " + message)
158
159
160
def get_fix_rules_pre(profile, fpath, ds_id="", xccdf_id="", tailoring=""):
161
    """
162
    Get fix rules for the pre-installation environment for a given profile in a
163
    given datastream and checklist in a given file.
164
165
    :see: run_oscap_remediate
166
    :see: _run_oscap_gen_fix
167
    :return: fix rules for a given profile
168
    :rtype: str
169
170
    """
171
172
    return _run_oscap_gen_fix(profile, fpath, PRE_INSTALL_FIX_SYSTEM_ATTR,
173
                              ds_id=ds_id, xccdf_id=xccdf_id,
174
                              tailoring=tailoring)
175
176
177
def _run_oscap_gen_fix(profile, fpath, template, ds_id="", xccdf_id="",
178
                       tailoring=""):
179
    """
180
    Run oscap tool on a given file to get the contents of fix elements with the
181
    'system' attribute equal to a given template for a given datastream,
182
    checklist and profile.
183
184
    :see: run_oscap_remediate
185
    :param template: the value of the 'system' attribute of the fix elements
186
    :type template: str
187
    :return: oscap tool's stdout
188
    :rtype: str
189
190
    """
191
192
    if not profile:
193
        return ""
194
195
    args = ["oscap", "xccdf", "generate", "fix"]
196
    args.append("--template=%s" % template)
197
198
    # oscap uses the default profile by default
199
    if profile.lower() != "default":
200
        args.append("--profile=%s" % profile)
201
    if ds_id:
202
        args.append("--datastream-id=%s" % ds_id)
203
    if xccdf_id:
204
        args.append("--xccdf-id=%s" % xccdf_id)
205
    if tailoring:
206
        args.append("--tailoring-file=%s" % tailoring)
207
208
    args.append(fpath)
209
210
    proc = SubprocessLauncher(args)
211
    proc.execute()
212
    proc.log_messages()
213
    if proc.returncode != 0:
214
        msg = "Failed to generate fix rules with the oscap tool: %s" % proc.stderr
215
        raise OSCAPaddonError(msg)
216
217
    return proc.stdout
218
219
220
def do_chroot(chroot):
221
    """Helper function doing the chroot if requested."""
222
    if chroot and chroot != "/":
223
        os.chroot(chroot)
224
        os.chdir("/")
225
226
227
def assert_scanner_works(chroot, executable="oscap"):
228
    args = [executable, "--version"]
229
    command = " ".join(args)
230
231
    try:
232
        proc = subprocess.Popen(
233
            args, preexec_fn=lambda: do_chroot(chroot),
234
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
235
        (stdout, stderr) = proc.communicate()
236
        stderr = stderr.decode(errors="replace")
237
    except OSError as exc:
238
        msg = _(f"Basic invocation '{command}' fails: {str(exc)}")
239
        raise OSCAPaddonError(msg)
240
    if proc.returncode != 0:
241
        msg = _(
242
            f"Basic scanner invocation '{command}' exited "
243
            "with non-zero error code {proc.returncode}: {stderr}")
244
        raise OSCAPaddonError(msg)
245
    return True
246
247
248
def run_oscap_remediate(profile, fpath, ds_id="", xccdf_id="", tailoring="",
249
                        chroot=""):
250
    """
251
    Run the evaluation and remediation with the oscap tool on a given file,
252
    doing the remediation as defined in a given profile defined in a given
253
    checklist that is a part of a given datastream. If requested, run in
254
    chroot.
255
256
    :param profile: id of the profile that will drive the remediation
257
    :type profile: str
258
    :param fpath: path to a file with SCAP content
259
    :type fpath: str
260
    :param ds_id: ID of the datastream that contains the checklist defining
261
                  the profile
262
    :type ds_id: str
263
    :param xccdf_id: ID of the checklist that defines the profile
264
    :type xccdf_id: str
265
    :param tailoring: path to a tailoring file
266
    :type tailoring: str
267
    :param chroot: path to the root the oscap tool should be run in
268
    :type chroot: str
269
    :return: oscap tool's stdout (summary of the rules, checks and fixes)
270
    :rtype: str
271
272
    """
273
274
    if not profile:
275
        return ""
276
277
    # make sure the directory for the results exists
278
    results_dir = os.path.dirname(RESULTS_PATH)
279
    if chroot:
280
        results_dir = os.path.normpath(chroot + "/" + results_dir)
281
    utils.ensure_dir_exists(results_dir)
282
283
    args = ["oscap", "xccdf", "eval"]
284
    args.append("--remediate")
285
    args.append("--results=%s" % RESULTS_PATH)
286
    args.append("--report=%s" % REPORT_PATH)
287
288
    # oscap uses the default profile by default
289
    if profile.lower() != "default":
290
        args.append("--profile=%s" % profile)
291
    if ds_id:
292
        args.append("--datastream-id=%s" % ds_id)
293
    if xccdf_id:
294
        args.append("--xccdf-id=%s" % xccdf_id)
295
    if tailoring:
296
        args.append("--tailoring-file=%s" % tailoring)
297
298
    args.append(fpath)
299
300
    proc = SubprocessLauncher(args)
301
    proc.execute(preexec_fn=lambda: do_chroot(chroot))
302
    proc.log_messages()
303
304
    if proc.returncode not in (0, 2):
305
        # 0 -- success; 2 -- no error, but checks/remediation failed
306
        msg = "Content evaluation and remediation with the oscap tool "\
307
            "failed: %s" % proc.stderr
308
        raise OSCAPaddonError(msg)
309
310
    return proc.stdout
311
312
313
314
def _schedule_firstboot_remediation(
315
        chroot, profile, ds_path, results_path, report_path, ds_id, xccdf_id, tailoring_path):
316
    config = textwrap.dedent(f"""\
317
    OSCAP_REMEDIATE_DS='{ds_path}'
318
    OSCAP_REMEDIATE_PROFILE_ID='{profile}'
319
    OSCAP_REMEDIATE_ARF_RESULT='{results_path}'
320
    OSCAP_REMEDIATE_HTML_REPORT='{report_path}'
321
    OSCAP_REMEDIATE_VERBOSE_LOGS='/var/tmp/oscap_verbose.log'
322
    """)
323
    if ds_id:
324
        config += "OSCAP_REMEDIATE_DATASTREAM_ID='{ds_id}'\n"
325
    if xccdf_id:
326
        config += "OSCAP_REMEDIATE_XCCDF_ID='{xccdf_id}'\n"
327
    if tailoring_path:
328
        config += "OSCAP_REMEDIATE_TAILORING='{tailoring_path}'\n"
329
330
    relative_filename = "var/tmp/oscap-remediate-offline.conf.sh"
331
    local_config_filename = f"/{relative_filename}"
332
    chroot_config_filename = os.path.join(chroot, relative_filename)
333
    with open(chroot_config_filename, "w") as f:
334
        f.write(config)
335
    os.symlink(local_config_filename,
336
               os.path.join(chroot, "system-update"))
337
338
339
def schedule_firstboot_remediation(chroot, profile, fpath, ds_id="", xccdf_id="", tailoring=""):
340
    if not profile:
341
        return ""
342
343
    # make sure the directory for the results exists
344
    results_dir = os.path.dirname(RESULTS_PATH)
345
    results_dir = os.path.normpath(chroot + "/" + results_dir)
346
    utils.ensure_dir_exists(results_dir)
347
348
    log.info("OSCAP addon: Scheduling firstboot remediation")
349
    _schedule_firstboot_remediation(
350
        chroot, profile, fpath, RESULTS_PATH, REPORT_PATH, ds_id, xccdf_id, tailoring)
351
352
    return ""
353
354
355
def extract_data(archive, out_dir, ensure_has_files=None):
356
    """
357
    Fuction that extracts the given archive to the given output directory. It
358
    tries to find out the archive type by the file name.
359
360
    :param archive: path to the archive file that should be extracted
361
    :type archive: str
362
    :param out_dir: output directory the archive should be extracted to
363
    :type out_dir: str
364
    :param ensure_has_files: relative paths to the files that must exist in the
365
                             archive
366
    :type ensure_has_files: iterable of strings or None
367
    :return: a list of files and directories extracted from the archive
368
    :rtype: [str]
369
370
    """
371
372
    if not ensure_has_files:
373
        ensure_has_files = []
374
375
    # get rid of empty file paths
376
    if not ensure_has_files:
377
        ensure_has_files = []
378
    else:
379
        ensure_has_files = [fpath for fpath in ensure_has_files if fpath]
380
381
    msg = "OSCAP addon: Extracting {archive}".format(archive=archive)
382
    if ensure_has_files:
383
        msg += ", expecting to find {files} there.".format(files=tuple(ensure_has_files))
384
    log.info(msg)
385
386
    result = []
387
    if archive.endswith(".zip"):
388
        # ZIP file
389
        try:
390
            zfile = zipfile.ZipFile(archive, "r")
391
        except Exception as exc:
392
            msg = _(f"Error extracting archive as a zipfile: {exc}")
393
            raise ExtractionError(msg)
394
395
        # generator for the paths of the files found in the archive (dirs end
396
        # with "/")
397
        files = set(info.filename for info in zfile.filelist
398
                    if not info.filename.endswith("/"))
399
        for fpath in ensure_has_files or ():
400
            if fpath not in files:
401
                msg = "File '%s' not found in the archive '%s'" % (fpath,
402
                                                                   archive)
403
                raise ExtractionError(msg)
404
405
        utils.ensure_dir_exists(out_dir)
406
        zfile.extractall(path=out_dir)
407
        result = [utils.join_paths(out_dir, info.filename) for info in zfile.filelist]
408
        zfile.close()
409
    elif archive.endswith(".tar"):
410
        # plain tarball
411
        result = _extract_tarball(archive, out_dir, ensure_has_files, None)
412
    elif archive.endswith(".tar.gz"):
413
        # gzipped tarball
414
        result = _extract_tarball(archive, out_dir, ensure_has_files, "gz")
415
    elif archive.endswith(".tar.bz2"):
416
        # bzipped tarball
417
        result = _extract_tarball(archive, out_dir, ensure_has_files, "bz2")
418
    elif archive.endswith(".rpm"):
419
        # RPM
420
        result = _extract_rpm(archive, out_dir, ensure_has_files)
421
    # elif other types of archives
422
    else:
423
        raise ExtractionError("Unsuported archive type")
424
    log.info("OSCAP addon: Extracted {files} from the supplied content"
425
             .format(files=result))
426
    return result
427
428
429
def _extract_tarball(archive, out_dir, ensure_has_files, alg):
430
    """
431
    Extract the given TAR archive to the given output directory and make sure
432
    the given file exists in the archive.
433
434
    :see: extract_data
435
    :param alg: compression algorithm used for the tarball
436
    :type alg: str (one of "gz", "bz2") or None
437
    :return: a list of files and directories extracted from the archive
438
    :rtype: [str]
439
440
    """
441
442
    if alg and alg not in ("gz", "bz2",):
443
        raise ExtractionError("Unsupported compression algorithm")
444
445
    mode = "r"
446
    if alg:
447
        mode += ":%s" % alg
448
449
    try:
450
        tfile = tarfile.TarFile.open(archive, mode)
451
    except tarfile.TarError as err:
452
        raise ExtractionError(str(err))
453
454
    # generator for the paths of the files found in the archive
455
    files = set(member.path for member in tfile.getmembers()
456
                if member.isfile())
457
458
    for fpath in ensure_has_files or ():
459
        if fpath not in files:
460
            msg = "File '%s' not found in the archive '%s'" % (fpath, archive)
461
            raise ExtractionError(msg)
462
463
    utils.ensure_dir_exists(out_dir)
464
    tfile.extractall(path=out_dir)
465
    result = [utils.join_paths(out_dir, member.path) for member in tfile.getmembers()]
466
    tfile.close()
467
468
    return result
469
470
471
def _extract_rpm(rpm_path, root="/", ensure_has_files=None):
472
    """
473
    Extract the given RPM into the directory tree given by the root argument
474
    and make sure the given file exists in the archive.
475
476
    :param rpm_path: path to the RPM file that should be extracted
477
    :type rpm_path: str
478
    :param root: root of the directory tree the RPM should be extracted into
479
    :type root: str
480
    :param ensure_has_files: relative paths to the files that must exist in the
481
                             RPM
482
    :type ensure_has_files: iterable of strings or None
483
    :return: a list of files and directories extracted from the archive
484
    :rtype: [str]
485
486
    """
487
488
    # run rpm2cpio and process the output with the cpioarchive module
489
    temp_fd, temp_path = tempfile.mkstemp(prefix="oscap_rpm")
490
    proc = subprocess.Popen(["rpm2cpio", rpm_path], stdout=temp_fd)
491
    proc.wait()
492
    if proc.returncode != 0:
493
        msg = "Failed to convert RPM '%s' to cpio archive" % rpm_path
494
        raise ExtractionError(msg)
495
496
    os.close(temp_fd)
497
498
    try:
499
        archive = cpioarchive.CpioArchive(temp_path)
500
    except cpioarchive.CpioError as err:
501
        raise ExtractionError(str(err))
502
503
    # get entries from the archive (supports only iteration over entries)
504
    entries = set(entry for entry in archive)
505
506
    # cpio entry names (paths) start with the dot
507
    entry_names = [entry.name.lstrip(".") for entry in entries]
508
509
    for fpath in ensure_has_files or ():
510
        # RPM->cpio entries have absolute paths
511
        if fpath not in entry_names and \
512
           os.path.join("/", fpath) not in entry_names:
513
            msg = "File '%s' not found in the archive '%s'" % (fpath, rpm_path)
514
            raise ExtractionError(msg)
515
516
    try:
517
        for entry in entries:
518
            if entry.size == 0:
519
                continue
520
            dirname = os.path.dirname(entry.name.lstrip("."))
521
            out_dir = os.path.normpath(root + dirname)
522
            utils.ensure_dir_exists(out_dir)
523
524
            out_fpath = os.path.normpath(root + entry.name.lstrip("."))
525
            if os.path.exists(out_fpath):
526
                continue
527
            with open(out_fpath, "wb") as out_file:
528
                buf = entry.read(IO_BUF_SIZE)
529
                while buf:
530
                    out_file.write(buf)
531
                    buf = entry.read(IO_BUF_SIZE)
532
    except (IOError, cpioarchive.CpioError) as e:
533
        raise ExtractionError(e)
534
535
    # cleanup
536
    archive.close()
537
    os.unlink(temp_path)
538
539
    return [os.path.normpath(root + name) for name in entry_names]
540
541
542
def strip_content_dir(fpaths, phase="preinst"):
543
    """
544
    Strip content directory prefix from the file paths for either
545
    pre-installation or post-installation phase.
546
547
    :param fpaths: iterable of file paths to strip content directory prefix
548
                   from
549
    :type fpaths: iterable of strings
550
    :param phase: specifies pre-installation or post-installation phase
551
    :type phase: "preinst" or "postinst"
552
    :return: the same iterable of file paths as given with the content
553
             directory prefix stripped
554
    :rtype: same type as fpaths
555
556
    """
557
558
    if phase == "preinst":
559
        remove_prefix = lambda x: x[len(INSTALLATION_CONTENT_DIR):]
560
    else:
561
        remove_prefix = lambda x: x[len(TARGET_CONTENT_DIR):]
562
563
    return utils.keep_type_map(remove_prefix, fpaths)
564
565
566
def get_ssg_path(root="/"):
567
    return utils.join_paths(root, SSG_DIR + SSG_CONTENT)
568
569
570
def ssg_available(root="/"):
571
    """
572
    Tries to find the SCAP Security Guide under the given root.
573
574
    :return: True if SSG was found under the given root, False otherwise
575
576
    """
577
578
    return os.path.exists(get_ssg_path(root))
579
580
581
def dry_run_skip(func):
582
    """
583
    Decorator that makes sure the decorated function is noop in the dry-run
584
    mode.
585
586
    :param func: a decorated function that needs to have the first parameter an
587
                 object with the _addon_data attribute referencing the OSCAP
588
                 addon's ksdata
589
    """
590
591
    @wraps(func)
592
    def decorated(self, *args, **kwargs):
593
        if self._addon_data.dry_run:
594
            return
595
        else:
596
            return func(self, *args, **kwargs)
597
598
    return decorated
599