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

org_fedora_oscap.common._()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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