Merge ~alexmurray/ubuntu-cve-tracker:python3-12-deprecation-fixups into ubuntu-cve-tracker:master

Proposed by Alex Murray
Status: Merged
Merge reported by: Steve Beattie
Merged at revision: b50dcd7ffc132ad87b39990ead6d05694faead0d
Proposed branch: ~alexmurray/ubuntu-cve-tracker:python3-12-deprecation-fixups
Merge into: ubuntu-cve-tracker:master
Diff against target: 249 lines (+29/-30)
3 files modified
scripts/active_edit (+2/-2)
scripts/check-cves (+9/-9)
scripts/oval_lib.py (+18/-19)
Reviewer Review Type Date Requested Status
Steve Beattie Approve
Review via email: mp+461222@code.launchpad.net

Description of the change

I suspect we have other scripts that will need similar fixes so will try and capture as many as I can here.

To post a comment you must log in.
8683bc4... by Alex Murray

scripts/oval_lib.py: update for Python 3.12 deprecations

Signed-off-by: Alex Murray <email address hidden>

b50dcd7... by Alex Murray

scripts/active_edit: update for Python 3.12 deprecations

Signed-off-by: Alex Murray <email address hidden>

Revision history for this message
Steve Beattie (sbeattie) wrote :

For the datetime changes,

- public_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
+ public_date = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d")

datetime.UTC was introduced in python 3.11 (so ubuntu 23.10, mantic), so jammy and older won't have this. We'll want to use datetime.timezone.utc instead; while most people should be running mantic or newer, we do have team members and systems running older releases than that. Given that datetime.datetime.now(datetime.timezone.utc) is a bit unwieldy, we could do something like:

  from datetime import datetime, timezone
  public_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")

Thanks.

Revision history for this message
Steve Beattie (sbeattie) wrote :
Revision history for this message
Steve Beattie (sbeattie) wrote :

I went ahead and fixed a bunch more and did the conversion to use datetime.timezone.utc instead of datetime.UTC, and then merged everything in https://git.launchpad.net/ubuntu-cve-tracker/commit/?id=92593eaa749bd40f80856e717c2186064f2993f5

Unfortunately, I ended up needing to rebase on top of master due to a merge conflict, so launchpad is not autoclosing this merge request.

review: Approve
Revision history for this message
Steve Beattie (sbeattie) wrote :

(I didn't squash the commits, all the individual ones are still there, that's just how cgit shows the merge request.)

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/scripts/active_edit b/scripts/active_edit
2index dadaf35..b02c28e 100755
3--- a/scripts/active_edit
4+++ b/scripts/active_edit
5@@ -99,7 +99,7 @@ def fetch_kernel_fixes(url):
6 if re.match("commit [0-9a-f]{40} upstream.", line):
7 # This is an LTS backport, skip it
8 return []
9- if re.match("\[ Upstream commit [0-9a-f]{40} \]", line):
10+ if re.match(r"\[ Upstream commit [0-9a-f]{40} \]", line):
11 # This is an LTS backport, skip it
12 return []
13 if not commit_hash and line.startswith("From "):
14@@ -316,7 +316,7 @@ def create_or_update_cve(cve, packages, priority=None, bug_urls=None,
15 # Set a default public date only when the CVE isn't being added to the
16 # embargoed tree
17 if not embargoed and not public_date:
18- public_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
19+ public_date = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d")
20
21 if update:
22 mode = "a"
23diff --git a/scripts/check-cves b/scripts/check-cves
24index 322f38b..0865e4a 100755
25--- a/scripts/check-cves
26+++ b/scripts/check-cves
27@@ -183,7 +183,7 @@ def convert_to_nvd(cves=[], desc=""):
28 nvd = {"CVE_data_type": "CVE",
29 "CVE_data_format": "MITRE",
30 "CVE_data_version": "4.0",
31- "CVE_data_timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%MZ"),
32+ "CVE_data_timestamp": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%MZ"),
33 "CVE_Items": []}
34
35 keys = list(cves.keys())
36@@ -474,8 +474,8 @@ def read_locate_cves_output(f):
37 subject += " " + s.strip()
38
39 # Try to fake up some urls
40- rhsa_regex = '\[RHSA-\d\d\d\d:\d+-\d+\]'
41- osssec_regex = '\[oss-security\]'
42+ rhsa_regex = r'\[RHSA-\d\d\d\d:\d+-\d+\]'
43+ osssec_regex = r'\[oss-security\]'
44 if re.search(r'' + rhsa_regex, subject):
45 rhsa = re.sub(r'.*(%s).*' % rhsa_regex, r'\1', subject).strip('[|]')
46 url = "https://rhn.redhat.com/errata/%s-%s.html" % (rhsa.split(':')[0], rhsa.split(':')[1].split('-')[0])
47@@ -651,7 +651,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
48 raise KeyError("NVD JSON in '%s' seems invalid" % fp.name)
49
50 metadata = cve["CVE_data_meta"]
51- if not re.match('^CVE-\d{4}-\d{4,}$', metadata["ID"]):
52+ if not re.match(r'^CVE-\d{4}-\d{4,}$', metadata["ID"]):
53 print("Ignoring invalid CVE with ID '%s'" % metadata["ID"])
54 return
55 self.curr_cve = metadata["ID"]
56@@ -850,8 +850,8 @@ class CVEHandler(xml.sax.handler.ContentHandler):
57 if suggestion.startswith('a ') and len(phrases) > 1:
58 suggestion = phrases[-2]
59
60- version_preps = '(\s+(before|through|prior to|versions?|[<>]=?))+\s*'
61- version_regex = '\s+([a-zA-Z\._\-]*[0-9]+[a-zA-Z\._\-]*)+'
62+ version_preps = r'(\s+(before|through|prior to|versions?|[<>]=?))+\s*'
63+ version_regex = r'\s+([a-zA-Z\._\-]*[0-9]+[a-zA-Z\._\-]*)+'
64 # prefer 'Apple iOS before <version>' or 'Apple Mac OS X through
65 # <version' in the last phrase over other suggestions
66 if not re.search(r'' + version_preps + version_regex, suggestion):
67@@ -1405,7 +1405,7 @@ class CVEHandler(xml.sax.handler.ContentHandler):
68 cmd = ['./scripts/active_edit', '-c', cve, '--yes',
69 '--public',
70 # set date as now
71- datetime.datetime.utcnow().strftime("%Y-%m-%d")]
72+ datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d")]
73 if breakfix:
74 cmd.extend(['-k'])
75 for url in ref_urls:
76@@ -1750,7 +1750,7 @@ def refresh_cves(cve_refresh_list, full_refresh=True):
77 debug("updated pubdate for %s" % (cvefile))
78
79 # Add CVE Reference, if it's missing
80- if 'References' in data and re.match('^CVE-\d+-\d+$', cve):
81+ if 'References' in data and re.match(r'^CVE-\d+-\d+$', cve):
82 mitre_ref = "https://cve.mitre.org/cgi-bin/cvename.cgi?name=" + cve
83 if mitre_ref not in data['References']:
84 cve_lib.add_reference(cvefile, mitre_ref)
85@@ -1808,7 +1808,7 @@ for cve in new_cves:
86 # pick half as often, if year is 2 years ago we want to pick
87 # 1/4 as often etc - so do 1/2^(diff)
88 year = int(re.split('-', cve)[1])
89- now = datetime.datetime.utcnow().year
90+ now = datetime.datetime.now(datetime.UTC).year
91 prob = 1.0 / math.pow(2, now - year)
92 rand = random.random()
93 if rand > prob:
94diff --git a/scripts/oval_lib.py b/scripts/oval_lib.py
95old mode 100644
96new mode 100755
97index d60c6dc..ace0cb3
98--- a/scripts/oval_lib.py
99+++ b/scripts/oval_lib.py
100@@ -29,7 +29,6 @@ import tempfile
101 import collections
102 import glob
103 import xml.etree.cElementTree as etree
104-import json
105 from xml.dom import minidom
106 from typing import Tuple # Needed because of Python < 3.9 and to also support < 3.7
107
108@@ -105,15 +104,15 @@ def is_kernel_binaries(binaries):
109 """
110 def process_kernel_binaries(binaries, oval_format):
111 packages = ' '.join(binaries)
112- parts = re.findall('linux-image-[a-z]*-?([\d|\.]+-)\d+(-[\w|-]+)', packages)
113+ parts = re.findall(r'linux-image-[a-z]*-?([\d|\.]+-)\d+(-[\w|-]+)', packages)
114 if parts:
115 values = set(map(lambda x: x[0], parts))
116 version = ''.join(values)
117 values = sorted(set(map(lambda x: x[1], parts)))
118 flavours = '|'.join(values)
119- regex = version + '\d+(' + flavours + ')'
120+ regex = version + r'\d+(' + flavours + ')'
121 if oval_format == 'oci':
122- regex = 'linux-image-(?:unsigned-)?' + version + '\d+(?:' + flavours + ')'
123+ regex = 'linux-image-(?:unsigned-)?' + version + r'\d+(?:' + flavours + ')'
124 return regex
125
126 return None
127@@ -312,7 +311,7 @@ class CVE:
128 for url in info['References'].split('\n'):
129 if 'https://ubuntu.com/security/notices/USN-' in url:
130 self.usns.append(url[40:])
131- elif re.match("https?:\/\/(bugs\.)?launchpad\.net\/(.*\/\+bug|bugs)\/\d+", url):
132+ elif re.match(r"https?:\/\/(bugs\.)?launchpad\.net\/(.*\/\+bug|bugs)\/\d+", url):
133 self.bugs.append(url)
134 elif url:
135 self.references.append(url)
136@@ -711,7 +710,7 @@ class OvalGenerator:
137 instance = etree.SubElement(object, "ind-def:instance",attrib={"datatype": "int"})
138
139 filepath.text = "/etc/lsb-release"
140- pattern.text = "^[\s\S]*DISTRIB_CODENAME=([a-z]+)$"
141+ pattern.text = r"^[\s\S]*DISTRIB_CODENAME=([a-z]+)$"
142 instance.text = "1"
143 else:
144 family_object = etree.Element("")
145@@ -1034,7 +1033,7 @@ class OvalGenerator:
146
147 final_binaries = []
148 if self.oval_format == 'oci':
149- variable_values = '(?::\w+|)\s+(.*)$'
150+ variable_values = r'(?::\w+|)\s+(.*)$'
151 for binary in binaries:
152 final_binaries.append(f'^{binary}{variable_values}')
153 else:
154@@ -1060,9 +1059,9 @@ class OvalGenerator:
155 if self.oval_format == 'oci':
156 if package.is_kernel_pkg:
157 regex = process_kernel_binaries(binaries, 'oci')
158- final_binaries = [f'^{regex}(?::\w+|)\s+(.*)$']
159+ final_binaries = [rf'^{regex}(?::\w+|)\s+(.*)$']
160 else:
161- variable_values = '(?::\w+|)\s+(.*)$'
162+ variable_values = r'(?::\w+|)\s+(.*)$'
163
164 final_binaries = []
165 for binary in binaries:
166@@ -1098,7 +1097,7 @@ class OvalGenerator:
167 concat = etree.SubElement(var, "concat")
168 component = etree.SubElement(concat, "literal_component")
169 regex = etree.SubElement(concat, "regex_capture", attrib={
170- "pattern": "^([\d|\.]+-\d+)[-|\w]+$"
171+ "pattern": r"^([\d|\.]+-\d+)[-|\w]+$"
172 })
173
174 etree.SubElement(regex, "object_component", attrib={
175@@ -1171,7 +1170,7 @@ class OvalGenerator:
176 return object
177
178 def _generate_state_kernel_element(self, comment, id, version) -> None:
179- patched = re.search('([\d|\.]+-\d+)[\.|\d]+', version)
180+ patched = re.search(r'([\d|\.]+-\d+)[\.|\d]+', version)
181 if patched:
182 patched = patched.group(1)
183 else:
184@@ -1285,9 +1284,9 @@ class OvalGenerator:
185 if self.oval_format == 'oci':
186 if package.is_kernel_pkg:
187 regex = process_kernel_binaries(binaries, 'oci')
188- final_binaries = [f'^{regex}(?::\w+|)\s+(.*)$']
189+ final_binaries = [rf'^{regex}(?::\w+|)\s+(.*)$']
190 else:
191- variable_values = '(?::\w+|)\s+(.*)$'
192+ variable_values = r'(?::\w+|)\s+(.*)$'
193
194 final_binaries = []
195 for binary in binaries:
196@@ -2065,7 +2064,7 @@ class OvalGeneratorUSN():
197 def create_release_object(self):
198 if self.oval_format == 'dpkg':
199 _object =\
200- f"""
201+ rf"""
202 <ind:family_object id="{self.ns}:obj:{self.id}" version="1" comment="The singleton family object."/>
203 <ind:textfilecontent54_object id="{self.ns}:obj:{self.id+1}" version="1">
204 <ind:filepath datatype="string">/etc/lsb-release</ind:filepath>
205@@ -2099,7 +2098,7 @@ class OvalGeneratorUSN():
206 bugs = ""
207
208 for url in urls:
209- is_bug = re.match("https?:\/\/(bugs\.)?launchpad\.net\/(.*\/\+bug|bugs)\/\d+", url)
210+ is_bug = re.match(r"https?:\/\/(bugs\.)?launchpad\.net\/(.*\/\+bug|bugs)\/\d+", url)
211
212 if is_bug:
213 bug_urls.append(url)
214@@ -2373,7 +2372,7 @@ class OvalGeneratorUSN():
215
216 elif 'kernelobj' in test_ref:
217 binary_version = test_ref['version']
218- binary_version = re.search('([\d|\.]+-\d+)[\.|\d]+', binary_version)
219+ binary_version = re.search(r'([\d|\.]+-\d+)[\.|\d]+', binary_version)
220 mapping['bversion'] = "0:" + binary_version.group(1)
221
222 state = \
223@@ -2431,7 +2430,7 @@ class OvalGeneratorUSN():
224 if self.oval_format == 'dpkg':
225 if 'kernel' in test_ref:
226 variable = \
227- """
228+ r"""
229 <local_variable id="{ns}:var:{id}" datatype="debian_evr_string" version="1" comment="kernel version in evr format">
230 <concat>
231 <literal_component>0:</literal_component>
232@@ -2453,7 +2452,7 @@ class OvalGeneratorUSN():
233 else:
234 for binary in binaries_list:
235 values += \
236- """<value>^{}(?::\w+|)\s+(.*)$</value>
237+ r"""<value>^{}(?::\w+|)\s+(.*)$</value>
238 """.format(binary)
239
240 mapping['values'] = values.strip()
241@@ -2504,7 +2503,7 @@ class OvalGeneratorUSN():
242 urls = []
243 for cve in cves:
244 # Takes urls from the list
245- is_url = re.match('(www|http:|https:)+[^\s]+[\w]', cve)
246+ is_url = re.match(r'(www|http:|https:)+[^\s]+[\w]', cve)
247
248 if is_url:
249 urls.append(cve)

Subscribers

People subscribed via source and target branches