Debian Codegraph @

utils/oscap_docker_python/get_cve_input.py

raw symbols SCIP
1 # Copyright (C) 2015 Brent Baude <[email protected]>
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the
15 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16 # Boston, MA 02110-1301 USA
17
18 import urllib.parse
19 import urllib.request
20 from os.path import join, exists
21 from os import stat, utime
22 from sys import stderr
23 import datetime
24
25
26 class getInputCVE(object):
27 '''
28 Class to obtain the CVE data provided by RH used to scan
29 for CVEs using openscap
30 '''
31
32 hdr = {'User-agent': 'Mozilla/5.0'}
33 hdr2 = [('User-agent', 'Mozilla/5.0')]
34 url = "https://www.redhat.com/security/data/oval/"
35 dist_cve_name = "com.redhat.rhsa-RHEL{0}.xml.bz2"
36 dists = [5, 6, 7]
37 remote_pattern = '%a, %d %b %Y %H:%M:%S %Z'
38
39 def __init__(self, fs_dest, DEBUG=False):
40 ''' Simple init declaration '''
41 self.dest = fs_dest
42 self.DEBUG = DEBUG
43
44 def _fetch_single(self, dist):
45 '''
46 Given a distribution number (i.e. 7), it will fetch the
47 distribution specific data file if upstream has a newer
48 input file. Returns the path of file.
49 '''
50 cve_file = self.dist_cve_name.format(dist)
51 dest_file = join(self.dest, cve_file)
52 dist_url = urllib.parse.urljoin(self.url, cve_file)
53 if self._is_cache_same(dest_file, dist_url):
54 return dest_file
55
56 _url = urllib.request.Request(dist_url, headers=self.hdr)
57 # TODO
58 # When dist specific files are available in bz form, some
59 # of this logic may need to change
60 try:
61 resp = urllib.request.urlopen(_url)
62
63 except Exception as url_error:
64 raise Exception("Unable to fetch CVE inputs due to {0}"
65 .format(url_error))
66
67 fh = open(dest_file, "wb")
68 fh.write(resp.read())
69 fh.close()
70
71 # Correct Last-Modified timestamp
72 headers = self._parse_http_headers(resp.info())
73 resp.close()
74 try:
75 remote_ts = headers['last-modified']
76 epoch = datetime.datetime.utcfromtimestamp(0)
77 remote_dt = datetime.datetime.strptime(remote_ts, self.remote_pattern)
78 seconds_epoch = (remote_dt - epoch).total_seconds()
79 utime(dest_file, (seconds_epoch, seconds_epoch))
80 except KeyError:
81 self._print_no_last_modified_warning(dist_url)
82
83 return dest_file
84
85 def _print_no_last_modified_warning(self, url):
86 if self.DEBUG:
87 stderr.write("Warning: Response header of HTTP doesn't contain " \
88 "\"last-modified\" field. Cannot determine version" \
89 " of remote file \"{0}\"\n".format(url))
90
91 def _parse_http_headers(self, http_headers):
92 '''
93 Returns dictionary containing HTTP headers with lowercase keys
94 '''
95
96 headers_dict = dict(http_headers)
97 return dict( (key.lower(), value) for key, value in headers_dict.items() )
98
99 def _is_cache_same(self, dest_file, dist_url):
100 '''
101 Checks if the local cache version and the upstream
102 version is the same or not. If they are the same,
103 returns True; else False.
104 '''
105
106 if not exists(dest_file):
107 if self.DEBUG:
108 stderr.write("No file in cache, fetching {0}\n".format(dest_file))
109 return False
110
111 opener = urllib.request.build_opener()
112 # Add the header
113 opener.addheaders = self.hdr2
114 # Grab the header
115 try:
116 res = opener.open(HeadRequest(dist_url))
117 headers = self._parse_http_headers(res.info())
118 res.close()
119 remote_ts = headers['last-modified']
120
121 except urllib.request.HTTPError as http_error:
122 if self.DEBUG:
123 stderr.write("Cannot send HTTP HEAD request to get \"last-modified\"" \
124 " attribute of remote content file.\n{0} - {1}\n"
125 .format(http_error.code, http_error.reason))
126 return False
127
128 except KeyError:
129 self._print_no_last_modified_warning(dist_url)
130 return False
131
132 # The remote's datetime
133 remote_dt = datetime.datetime.strptime(remote_ts, self.remote_pattern)
134 # Get the locals datetime from the file's mtime, converted to UTC
135 local_dt = datetime.datetime.utcfromtimestamp((stat(dest_file))
136 .st_mtime)
137
138 # Giving a two second comfort zone
139 # Else we declare they are different
140 if (remote_dt - local_dt).seconds > 2:
141 if self.DEBUG:
142 stderr.write("Had a local file {0} " \
143 "but it wasn't new enough\n".format(dest_file))
144 return False
145 if self.DEBUG:
146 stderr.write("File {0} is same as upstream\n".format(dest_file))
147
148 return True
149
150 def fetch_dist_data(self):
151 '''
152 Fetches all the the distribution specific data used for
153 input with openscap cve scanning and returns a list
154 of those files.
155 '''
156 cve_files = []
157 for dist in self.dists:
158 cve_files.append(self._fetch_single(dist))
159 return cve_files
160
161
162 class HeadRequest(urllib.request.Request):
163 def get_method(self):
164 return 'HEAD'