Debian Codegraph @

utils/oscap-im

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright 2024 Red Hat Inc., Durham, North Carolina.
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 import argparse
20 import os
21 import subprocess
22 import sys
23 import tempfile
24
25 from pathlib import Path
26
27
28 def parse_args():
29 parser = argparse.ArgumentParser(
30 description="Use in your Containerfile to build hardened bootable "
31 "container images. Performs OpenSCAP scan and remediation of the "
32 "image.")
33 parser.add_argument(
34 "--profile",
35 help="ID of the profile to be evaluated")
36 parser.add_argument(
37 "--tailoring-file",
38 help="Use given XCCDF Tailoring file")
39 parser.add_argument(
40 "--tailoring-id", metavar="COMPONENT_ID",
41 help="Use given DS component as XCCDF Tailoring file")
42 parser.add_argument(
43 "--results-arf",
44 help="Write ARF (result data stream) into file")
45 parser.add_argument(
46 "--report",
47 help="Write HTML report into file")
48 parser.add_argument(
49 "data_stream", metavar="DATA_STREAM",
50 help="Path to a SCAP source data stream, eg. "
51 "/usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml")
52 parser.add_argument(
53 "--fetch-remote-resources", action="store_true",
54 help="Fetch remote resources referenced in the XCCDF content")
55 # Unfortunately, we can't add "--rule", "--skip-rule", or "--reference"
56 # because the "oscap xccdf generate fix" submodule doesn't support these
57 # options.
58 return parser.parse_args()
59
60
61 def verify_bootc_build_env():
62 rv = subprocess.run(
63 ["rpm", "-q", "bootc"],
64 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
65 bootc_env = (rv.returncode == 0)
66 container_env = Path("/run/.containerenv").exists()
67 if not bootc_env or not container_env:
68 raise RuntimeError(
69 "This script is supposed to be used only in the bootable "
70 "container build environment.")
71
72
73 def install_sce_dependencies():
74 required_packages = [
75 "openscap-engine-sce",
76 "setools-console" # seinfo is used by the sebool template
77 ]
78 install_cmd = ["dnf", "-y", "install"] + required_packages
79 install_process = subprocess.run(
80 install_cmd, universal_newlines=True,
81 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
82 if install_process.returncode != 0:
83 raise RuntimeError(
84 f"{install_process.stdout}\nFailed to install SCE dependencies.")
85
86
87 def add_args(option_args_list, cmd):
88 for o, a in option_args_list:
89 if a:
90 cmd.append(o)
91 cmd.append(a)
92
93
94 def add_common_args(args, cmd):
95 oal = [
96 ("--profile", args.profile),
97 ("--tailoring-file", args.tailoring_file),
98 ("--tailoring-id", args.tailoring_id)
99 ]
100 add_args(oal, cmd)
101 if args.fetch_remote_resources:
102 cmd.append("--fetch-remote-resources")
103
104
105 def add_eval_args(args, cmd):
106 oal = [
107 ("--results-arf", args.results_arf),
108 ("--report", args.report),
109 ]
110 add_args(oal, cmd)
111
112
113 def pre_scan_fix(args):
114 with tempfile.NamedTemporaryFile() as remediation_script:
115 gen_fix_cmd = [
116 "oscap", "xccdf", "generate", "fix", "--fix-type", "bootc",
117 "--output", remediation_script.name]
118 add_common_args(args, gen_fix_cmd)
119 gen_fix_cmd.append(args.data_stream)
120 try:
121 subprocess.run(gen_fix_cmd, check=True, capture_output=True)
122 except subprocess.CalledProcessError as e:
123 raise RuntimeError(
124 f"OpenSCAP generate fix failed with return code "
125 f"{e.returncode}.\nOutput: {e.stderr.decode()}")
126 try:
127 subprocess.run(["bash", remediation_script.name], check=True)
128 except subprocess.CalledProcessError as e:
129 raise RuntimeError(
130 f"Remediation script failed with return code "
131 f"{e.returncode}.")
132
133
134 def scan_and_remediate(args):
135 oscap_cmd = ["oscap", "xccdf", "eval", "--progress", "--remediate"]
136 add_common_args(args, oscap_cmd)
137 add_eval_args(args, oscap_cmd)
138 oscap_cmd.append(args.data_stream)
139 env = {**os.environ, "OSCAP_PREFERRED_ENGINE": "SCE"}
140 try:
141 subprocess.run(oscap_cmd, env=env, check=True)
142 except subprocess.CalledProcessError as e:
143 if e.returncode not in [0, 2]:
144 raise RuntimeError(
145 f"OpenSCAP scan failed with return code {e.returncode}.\n")
146
147
148 def main():
149 args = parse_args()
150 verify_bootc_build_env()
151 install_sce_dependencies()
152 try:
153 pre_scan_fix(args)
154 scan_and_remediate(args)
155 except RuntimeError as e:
156 print(e, file=sys.stderr)
157 sys.exit(1)
158
159
160 if __name__ == "__main__":
161 main()