Completed
Push — rhel8-branch ( 714abe...652bc6 )
by Jan
21s queued 14s
created

org_fedora_oscap.common   F

Complexity

Total Complexity 78

Size/Duplication

Total Lines 597
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 78
eloc 302
dl 0
loc 597
rs 2.16
c 0
b 0
f 0

16 Functions

Rating   Name   Duplication   Size   Complexity  
A get_fix_rules_pre() 0 15 1
B _run_oscap_gen_fix() 0 41 7
C run_oscap_remediate() 0 63 9
A assert_scanner_works() 0 19 4
A do_chroot() 0 5 3
A _() 0 5 2
A N_() 0 1 1
A dry_run_skip() 0 18 2
A get_ssg_path() 0 2 1
B _extract_tarball() 0 40 7
A _schedule_firstboot_remediation() 0 22 5
A strip_content_dir() 0 22 4
A schedule_firstboot_remediation() 0 14 2
D extract_data() 0 72 12
A ssg_available() 0 9 1
D _extract_rpm() 0 69 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A SubprocessLauncher.log_messages() 0 3 2
A SubprocessLauncher.execute() 0 20 2
A SubprocessLauncher.__init__() 0 6 1

How to fix   Complexity   

Complexity

Complex classes like org_fedora_oscap.common often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
def _schedule_firstboot_remediation(
314
        chroot, profile, ds_path, results_path, report_path, ds_id, xccdf_id, tailoring_path):
315
    config = textwrap.dedent(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
    relative_filename = "var/tmp/oscap-remediate-offline.conf.sh"
329
    local_config_filename = f"/{relative_filename}"
330
    chroot_config_filename = os.path.join(chroot, relative_filename)
331
    with open(chroot_config_filename, "w") as f:
332
        f.write(config)
333
    os.symlink(local_config_filename,
334
               os.path.join(chroot, "system-update"))
335
336
337
def schedule_firstboot_remediation(chroot, profile, fpath, ds_id="", xccdf_id="", tailoring=""):
338
    if not profile:
339
        return ""
340
341
    # make sure the directory for the results exists
342
    results_dir = os.path.dirname(RESULTS_PATH)
343
    results_dir = os.path.normpath(chroot + "/" + results_dir)
344
    utils.ensure_dir_exists(results_dir)
345
346
    log.info("OSCAP addon: Scheduling firstboot remediation")
347
    _schedule_firstboot_remediation(
348
        chroot, profile, fpath, RESULTS_PATH, REPORT_PATH, ds_id, xccdf_id, tailoring)
349
350
    return ""
351
352
353
def extract_data(archive, out_dir, ensure_has_files=None):
354
    """
355
    Fuction that extracts the given archive to the given output directory. It
356
    tries to find out the archive type by the file name.
357
358
    :param archive: path to the archive file that should be extracted
359
    :type archive: str
360
    :param out_dir: output directory the archive should be extracted to
361
    :type out_dir: str
362
    :param ensure_has_files: relative paths to the files that must exist in the
363
                             archive
364
    :type ensure_has_files: iterable of strings or None
365
    :return: a list of files and directories extracted from the archive
366
    :rtype: [str]
367
368
    """
369
370
    if not ensure_has_files:
371
        ensure_has_files = []
372
373
    # get rid of empty file paths
374
    if not ensure_has_files:
375
        ensure_has_files = []
376
    else:
377
        ensure_has_files = [fpath for fpath in ensure_has_files if fpath]
378
379
    msg = "OSCAP addon: Extracting {archive}".format(archive=archive)
380
    if ensure_has_files:
381
        msg += ", expecting to find {files} there.".format(files=tuple(ensure_has_files))
382
    log.info(msg)
383
384
    result = []
385
    if archive.endswith(".zip"):
386
        # ZIP file
387
        try:
388
            zfile = zipfile.ZipFile(archive, "r")
389
        except Exception as exc:
390
            msg = _(f"Error extracting archive as a zipfile: {exc}")
391
            raise ExtractionError(msg)
392
393
        # generator for the paths of the files found in the archive (dirs end
394
        # with "/")
395
        files = set(info.filename for info in zfile.filelist
396
                    if not info.filename.endswith("/"))
397
        for fpath in ensure_has_files or ():
398
            if fpath not in files:
399
                msg = "File '%s' not found in the archive '%s'" % (fpath,
400
                                                                   archive)
401
                raise ExtractionError(msg)
402
403
        utils.ensure_dir_exists(out_dir)
404
        zfile.extractall(path=out_dir)
405
        result = [utils.join_paths(out_dir, info.filename) for info in zfile.filelist]
406
        zfile.close()
407
    elif archive.endswith(".tar"):
408
        # plain tarball
409
        result = _extract_tarball(archive, out_dir, ensure_has_files, None)
410
    elif archive.endswith(".tar.gz"):
411
        # gzipped tarball
412
        result = _extract_tarball(archive, out_dir, ensure_has_files, "gz")
413
    elif archive.endswith(".tar.bz2"):
414
        # bzipped tarball
415
        result = _extract_tarball(archive, out_dir, ensure_has_files, "bz2")
416
    elif archive.endswith(".rpm"):
417
        # RPM
418
        result = _extract_rpm(archive, out_dir, ensure_has_files)
419
    # elif other types of archives
420
    else:
421
        raise ExtractionError("Unsuported archive type")
422
    log.info("OSCAP addon: Extracted {files} from the supplied content"
423
             .format(files=result))
424
    return result
425
426
427
def _extract_tarball(archive, out_dir, ensure_has_files, alg):
428
    """
429
    Extract the given TAR archive to the given output directory and make sure
430
    the given file exists in the archive.
431
432
    :see: extract_data
433
    :param alg: compression algorithm used for the tarball
434
    :type alg: str (one of "gz", "bz2") or None
435
    :return: a list of files and directories extracted from the archive
436
    :rtype: [str]
437
438
    """
439
440
    if alg and alg not in ("gz", "bz2",):
441
        raise ExtractionError("Unsupported compression algorithm")
442
443
    mode = "r"
444
    if alg:
445
        mode += ":%s" % alg
446
447
    try:
448
        tfile = tarfile.TarFile.open(archive, mode)
449
    except tarfile.TarError as err:
450
        raise ExtractionError(str(err))
451
452
    # generator for the paths of the files found in the archive
453
    files = set(member.path for member in tfile.getmembers()
454
                if member.isfile())
455
456
    for fpath in ensure_has_files or ():
457
        if fpath not in files:
458
            msg = "File '%s' not found in the archive '%s'" % (fpath, archive)
459
            raise ExtractionError(msg)
460
461
    utils.ensure_dir_exists(out_dir)
462
    tfile.extractall(path=out_dir)
463
    result = [utils.join_paths(out_dir, member.path) for member in tfile.getmembers()]
464
    tfile.close()
465
466
    return result
467
468
469
def _extract_rpm(rpm_path, root="/", ensure_has_files=None):
470
    """
471
    Extract the given RPM into the directory tree given by the root argument
472
    and make sure the given file exists in the archive.
473
474
    :param rpm_path: path to the RPM file that should be extracted
475
    :type rpm_path: str
476
    :param root: root of the directory tree the RPM should be extracted into
477
    :type root: str
478
    :param ensure_has_files: relative paths to the files that must exist in the
479
                             RPM
480
    :type ensure_has_files: iterable of strings or None
481
    :return: a list of files and directories extracted from the archive
482
    :rtype: [str]
483
484
    """
485
486
    # run rpm2cpio and process the output with the cpioarchive module
487
    temp_fd, temp_path = tempfile.mkstemp(prefix="oscap_rpm")
488
    proc = subprocess.Popen(["rpm2cpio", rpm_path], stdout=temp_fd)
489
    proc.wait()
490
    if proc.returncode != 0:
491
        msg = "Failed to convert RPM '%s' to cpio archive" % rpm_path
492
        raise ExtractionError(msg)
493
494
    os.close(temp_fd)
495
496
    try:
497
        archive = cpioarchive.CpioArchive(temp_path)
498
    except cpioarchive.CpioError as err:
499
        raise ExtractionError(str(err))
500
501
    # get entries from the archive (supports only iteration over entries)
502
    entries = set(entry for entry in archive)
503
504
    # cpio entry names (paths) start with the dot
505
    entry_names = [entry.name.lstrip(".") for entry in entries]
506
507
    for fpath in ensure_has_files or ():
508
        # RPM->cpio entries have absolute paths
509
        if fpath not in entry_names and \
510
           os.path.join("/", fpath) not in entry_names:
511
            msg = "File '%s' not found in the archive '%s'" % (fpath, rpm_path)
512
            raise ExtractionError(msg)
513
514
    try:
515
        for entry in entries:
516
            if entry.size == 0:
517
                continue
518
            dirname = os.path.dirname(entry.name.lstrip("."))
519
            out_dir = os.path.normpath(root + dirname)
520
            utils.ensure_dir_exists(out_dir)
521
522
            out_fpath = os.path.normpath(root + entry.name.lstrip("."))
523
            if os.path.exists(out_fpath):
524
                continue
525
            with open(out_fpath, "wb") as out_file:
526
                buf = entry.read(IO_BUF_SIZE)
527
                while buf:
528
                    out_file.write(buf)
529
                    buf = entry.read(IO_BUF_SIZE)
530
    except (IOError, cpioarchive.CpioError) as e:
531
        raise ExtractionError(e)
532
533
    # cleanup
534
    archive.close()
535
    os.unlink(temp_path)
536
537
    return [os.path.normpath(root + name) for name in entry_names]
538
539
540
def strip_content_dir(fpaths, phase="preinst"):
541
    """
542
    Strip content directory prefix from the file paths for either
543
    pre-installation or post-installation phase.
544
545
    :param fpaths: iterable of file paths to strip content directory prefix
546
                   from
547
    :type fpaths: iterable of strings
548
    :param phase: specifies pre-installation or post-installation phase
549
    :type phase: "preinst" or "postinst"
550
    :return: the same iterable of file paths as given with the content
551
             directory prefix stripped
552
    :rtype: same type as fpaths
553
554
    """
555
556
    if phase == "preinst":
557
        remove_prefix = lambda x: x[len(INSTALLATION_CONTENT_DIR):]
558
    else:
559
        remove_prefix = lambda x: x[len(TARGET_CONTENT_DIR):]
560
561
    return utils.keep_type_map(remove_prefix, fpaths)
562
563
564
def get_ssg_path(root="/"):
565
    return utils.join_paths(root, SSG_DIR + SSG_CONTENT)
566
567
568
def ssg_available(root="/"):
569
    """
570
    Tries to find the SCAP Security Guide under the given root.
571
572
    :return: True if SSG was found under the given root, False otherwise
573
574
    """
575
576
    return os.path.exists(get_ssg_path(root))
577
578
579
def dry_run_skip(func):
580
    """
581
    Decorator that makes sure the decorated function is noop in the dry-run
582
    mode.
583
584
    :param func: a decorated function that needs to have the first parameter an
585
                 object with the _addon_data attribute referencing the OSCAP
586
                 addon's ksdata
587
    """
588
589
    @wraps(func)
590
    def decorated(self, *args, **kwargs):
591
        if self._addon_data.dry_run:
592
            return
593
        else:
594
            return func(self, *args, **kwargs)
595
596
    return decorated
597