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

org_fedora_oscap.common.do_chroot()   A

Complexity

Conditions 3

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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