Debian Codegraph @

utils/oscap_docker_python/oscap_docker_util.py

raw symbols SCIP
1 # Copyright (C) 2015 Brent Baude <[email protected]>
2 # Copyright (C) 2019 Dominique Blaze <[email protected]>
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the
16 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 # Boston, MA 02110-1301 USA
18
19 from __future__ import print_function
20
21 import os
22 import io
23 from pathlib import Path
24 from itertools import chain
25 import tarfile
26 import tempfile
27 import shutil
28 from oscap_docker_python.get_cve_input import getInputCVE
29 import sys
30 import docker
31 import uuid
32 import collections
33 from oscap_docker_python.oscap_docker_common import oscap_chroot, get_dist, \
34 OscapResult, OscapError
35
36
37 class OscapError(Exception):
38 ''' oscap Error'''
39 pass
40
41
42 OscapResult = collections.namedtuple("OscapResult", ("returncode", "stdout", "stderr"))
43
44
45 class OscapDockerScan(object):
46
47 def __init__(self, target, is_image=False, oscap_binary='oscap'):
48
49 # init docker high level API (to deal with start/stop/run containers/image)
50 self.client_api = docker.from_env()
51 self.is_image = is_image
52 self.oscap_binary = oscap_binary or 'oscap'
53 self.container_name = None
54 self.image_name = None
55 self.extracted_container = False
56
57 # init docker low level api (useful for deep details like container pid)
58 self.client = self.client_api.api
59
60 if self.is_image:
61 self.image_name, self.config = self._get_image_name_and_config(target)
62 if "," in self.image_name:
63 # Fix when a single image has multiple tags
64 self.image_name = self.image_name.split(",")[0]
65 if self.image_name:
66 print("Creating a temporary container for the image...")
67
68 try:
69 tmp_cont = self.client.create_container(
70 self.image_name, name=self.container_name, command="\x00")
71
72 self.container_name = tmp_cont["Id"]
73 self.config = self.client.inspect_container(self.container_name)
74 except Exception as e:
75 sys.stderr.write("Cannot create container for image {0}.\n".format(self.image_name))
76 raise e
77
78 self._extract_container()
79 else:
80 raise ValueError("Image {0} not found.\n".format(target))
81
82 else:
83 self.container_name, self.config = \
84 self._get_container_name_and_config(target)
85 if not self.container_name:
86 raise ValueError("Container {0} not found.\n".format(target))
87
88 # is the container running ?
89 if int(self.config["State"]["Pid"]) == 0:
90 print("Container {0} is stopped"
91 .format(self.container_name))
92
93 self._extract_container()
94 else:
95 print("Container {0} is running, using its existing mount..."
96 .format(self.container_name))
97 self.mountpoint = "/proc/{0}/root".format(self.config["State"]["Pid"])
98
99 if self._check_container_mountpoint():
100 print("Docker container {0} ready to be scanned."
101 .format(self.container_name))
102 else:
103 self._end()
104 raise RuntimeError(
105 "Cannot access mountpoint of container {0}, "
106 "please RUN WITH ROOT privileges.\n"
107 .format(self.container_name))
108
109 def _end(self):
110 if self.is_image:
111 # remove the temporary container
112 self.client.remove_container(self.container_name)
113 print("Temporary container {0} cleaned".format(self.container_name))
114 if self.extracted_container:
115 print("Cleaning temporary extracted container...")
116 shutil.rmtree(self.mountpoint)
117
118 def _extract_container(self):
119 '''
120 Extracts the container and sets mountpoint to the extracted directory
121 '''
122 with tempfile.TemporaryFile() as tar:
123 for chunk in self.client.export(self.container_name):
124 tar.write(chunk)
125 tar.seek(0)
126 self.mountpoint = tempfile.mkdtemp()
127 self.extracted_container = True
128 with tarfile.open(fileobj=tar) as tf:
129 tf.extractall(path=self.mountpoint)
130 Path(os.path.join(self.mountpoint, '.dockerenv')).touch()
131
132
133 def _get_image_name_and_config(self, target):
134 '''
135 Ensure that target is an image.
136 Returns full image name if exists or image ID otherwise.
137 For containers returns
138 container name if exists or container ID otherwise.
139 '''
140
141 try:
142 image = self.client.inspect_image(target)
143 if image["RepoTags"]:
144 name = ", ".join(image["RepoTags"])
145 else:
146 name = image["Id"][len("sha256:"):][:10]
147 return name, image
148 except docker.errors.NotFound:
149 return None, {}
150
151 def _get_container_name_and_config(self, target):
152 '''
153 Ensure that target is a container.
154 Returns container name if exists or container ID otherwise.
155 '''
156 try:
157 container = self.client.inspect_container(target)
158 if container["Name"]:
159 name = container["Name"].lstrip("/")
160 else:
161 name = container["Id"][:10]
162 return name, container
163 except docker.errors.NotFound:
164 return None, {}
165
166 def _check_container_mountpoint(self):
167 '''
168 Ensure that the container fs is well mounted and return its path
169 '''
170 return os.access(self.mountpoint, os.R_OK)
171
172 def scan_cve(self, scan_args):
173 '''
174 Wrapper function for scanning cve of a mounted container
175 '''
176
177 tmp_dir = tempfile.mkdtemp()
178
179 # Figure out which RHEL dist is in the chroot
180 dist = get_dist(self.mountpoint, self.oscap_binary,
181 self.config["Config"].get("Env", []) or [])
182
183 if dist is None:
184 sys.stderr.write("{0} is not based on RHEL\n"
185 .format(self.image_name or self.container_name))
186 return None
187
188 # Fetch the CVE input data for the dist
189 fetch = getInputCVE(tmp_dir)
190 cve_file = fetch._fetch_single(dist)
191
192 print("CVEs downloaded in " + cve_file)
193
194 args = ("oval", "eval")
195 for a in scan_args:
196 args += (a,)
197 args += (cve_file,)
198
199 scan_result = oscap_chroot(
200 self.mountpoint, self.oscap_binary, args,
201 self.image_name or self.container_name,
202 self.config["Config"].get("Env", []) or [] # because Env can exists but be None
203 )
204
205 print(scan_result.stdout)
206 print(scan_result.stderr, file=sys.stderr)
207
208 # cleanup
209
210 print("Cleaning temporary files ...")
211 shutil.rmtree(tmp_dir)
212 self._end()
213
214 return scan_result.returncode
215
216 def scan(self, scan_args):
217 '''
218 Wrapper function forwarding oscap args for an offline scan
219 '''
220 scan_result = oscap_chroot(
221 self.mountpoint,
222 self.oscap_binary, scan_args,
223 self.image_name or self.container_name,
224 self.config["Config"].get("Env", []) or [] # because Env can exists but be None
225 )
226
227 print(scan_result.stdout)
228 print(scan_result.stderr, file=sys.stderr)
229
230 self._end()
231
232 return scan_result.returncode