-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrender_doc.py
1328 lines (1071 loc) · 40.3 KB
/
render_doc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import configparser
import datetime
import glob
import itertools
import json
import os.path
import re
import subprocess
import shutil
import sys
import urllib.parse
import urllib.request
import xmlrpc.client
import github
import yaml
# Last update: 2022-09-14
# https://devguide.python.org/versions/
MAINTAINED_BRANCHES = ['3.7', '3.8', '3.9', '3.10']
PSF_ADVISORY_DATABASE = """
.. warning::
This resource is maintained for historical reference and **does not contain the latest vulnerability info for Python**.
The `canonical database for vulnerabilities affecting Python <https://github.com/psf/advisory-database>`_ is available on GitHub
in the Open Source Vulnerability (OSV) format. This database can be viewed online at the
`Open Source Vulnerability Database <https://osv.dev/list?ecosystem=&q=PSF>`_.
""".strip()
PSF_ADVISORY_DATABASE_WITH_CVE = """
.. warning::
This resource is maintained for historical reference and **does not contain the latest vulnerability info for Python**.
The `canonical database for vulnerabilities affecting Python <https://github.com/psf/advisory-database>`_ is available on GitHub
in the Open Source Vulnerability (OSV) format. This vulnerability can be viewed online at the
`Open Source Vulnerability Database <https://osv.dev/list?ecosystem=&q={cve}>`_.
""".strip()
STATUS_BRANCHES = """
`Status of Python branches
<https://devguide.python.org/versions/>`_ lists Python
branches which get security fixes.
""".strip()
OFFLINE = True
CVE_REGEX = re.compile('(?<!`)CVE-[0-9]+-[0-9]+')
CVE_URL = 'https://nvd.nist.gov/vuln/detail/%s/'
CVE_API = 'http://cve.circl.lu/api/cve/%s'
BPO_URL = 'https://bugs.python.org/issue{}'
GH_ISSUE_URL = 'https://github.com/python/cpython/issues/{}'
CVSS_SCORE_URL = 'https://nvd.nist.gov/cvss.cfm'
RED_HAT_IMPACT_URL = ('https://access.redhat.com/security/'
'updates/classification/')
BUGS_API = 'https://bugs.python.org/xmlrpc'
BUGS_DATE_REGEX = re.compile(r'<Date (.*)>')
# Create a token at https://github.com/settings/tokens
GITHUB_API_TOKEN = None
GITHUB_REPO = "python/cpython"
class OfflineError(Exception):
pass
def create_slug(name):
slug = name.lower()
slug = re.sub(r'[#(),]', '', slug)
slug = re.sub(r"[ :']", '_', slug)
slug = re.sub(r'__+', '_', slug)
if not re.match('^[a-z0-9._-]+$', slug):
raise ValueError("invalid slug: %r" % slug)
return slug
def try_mkdir(path):
try:
os.mkdir(path)
except FileExistsError:
pass
def download(url):
response = urllib.request.urlopen(url)
with response:
return response.read()
def load_json(filename):
with open(filename, encoding="utf-8") as fp:
return json.load(fp)
def dump_json(filename, data):
with open(filename, "w", encoding="utf-8") as fp:
return json.dump(data, fp, sort_keys=True, indent=4)
def load_yaml(filename):
with open(filename, encoding="utf-8") as fp:
return yaml.safe_load(fp)
def dump_yaml(filename, data):
with open(filename, "w", encoding="utf-8") as fp:
return yaml.dump(data, fp, indent=4, default_flow_style=False)
def timedelta_days(delta):
return delta.days
def parse_date(text):
if isinstance(text, datetime.date):
return text
try:
dt = datetime.datetime.strptime(text, "%Y-%m-%d")
return dt.date()
except ValueError:
pass
try:
# Mon Apr 18 03:45:18 2016 +0000
dt = datetime.datetime.strptime(text, "%a %b %d %H:%M:%S %Y %z")
dt = (dt - dt.utcoffset()).replace(tzinfo=datetime.timezone.utc)
return dt.date()
except ValueError:
pass
try:
# CVE date: 2016-09-02T10:59:00.127-04:00
if len(text) == 29 and text.count('.') == 1:
text2 = re.sub(r'\.[0-9]{3}', '', text)
def replace_timezone(regs):
text = regs.group(0)
return text[:2] + text[3:]
text2 = re.sub(r'[0-9]{2}:[0-9]{2}$', replace_timezone, text2)
dt = datetime.datetime.strptime(text2, "%Y-%m-%dT%H:%M:%S%z")
dt = (dt - dt.utcoffset()).replace(tzinfo=datetime.timezone.utc)
return dt.date()
except ValueError:
pass
try:
# CVE date: '2016-05-26T12:59:00'
# CVE date: '2016-05-26T12:59:00.133000'
text2 = re.sub(r'\.[0-9]{6}$', '', text)
dt = datetime.datetime.strptime(text2, "%Y-%m-%dT%H:%M:%S")
dt = dt.replace(tzinfo=datetime.timezone.utc)
return dt.date()
except ValueError:
pass
raise ValueError("unable to parse date: %r" % text)
def format_date(date):
return date.strftime("%Y-%m-%d")
def run(cmd, cwd, text=True):
kw = {}
if text:
kw['universal_newlines'] = True
proc = subprocess.run(cmd,
stdout=subprocess.PIPE,
cwd=cwd,
**kw)
if proc.returncode:
print("Command %r failed with exit code %s"
% (' '.join(cmd), proc.returncode))
sys.exit(proc.returncode)
return proc
class Commit:
def __init__(self, revision, branch, date):
self.revision = revision
self.branch = branch
self.date = date
def short(self):
return self.revision[:7]
def url(self):
return 'https://github.com/python/cpython/commit/' + self.revision
def format(self):
label = 'commit {}'.format(self.short())
if self.branch:
label = '{} (branch {})'.format(label, self.branch)
return "`{} <{}>`_".format(label, self.url())
def __repr__(self):
revision = self.revision
if self.branch:
revision = '%s in %s' % (revision, self.branch)
return '<Commit %s at %s>' % (revision, format_date(self.date))
class CommitDates:
def __init__(self, python_path, cache_filename):
self.python_path = python_path
self.cache_filename = cache_filename
# commit (sha1) => date
self.cache = {}
self.read_cache()
def read_cache(self):
try:
fp = open(self.cache_filename, encoding="utf-8")
except FileNotFoundError:
return
with fp:
for line in fp:
line = line.rstrip()
if not line:
continue
commit, date = line.split(':', 1)
commit = commit.strip()
date = date.strip()
self.cache[commit] = date
def write_cache(self):
commits = list(self.cache.items())
commits.sort()
with open(self.cache_filename, "w", encoding="utf-8") as fp:
for commit, date in commits:
print("%s: %s" % (commit, date), file=fp)
def _get_commit_date(self, commit):
print("Get %s date" % commit)
cmd = ["git", "show", commit]
proc = run(cmd, self.python_path, text=False)
for line in proc.stdout.splitlines():
if not line.startswith(b'Date:'):
continue
line = line[5:].strip()
line = line.decode()
return line
print("ERROR: failed to get commit date")
print(proc.stdout)
sys.exit(1)
def get_commit_date(self, commit):
if commit in self.cache:
date = self.cache[commit]
return parse_date(date)
if OFFLINE:
return None
date = self._get_commit_date(commit)
self.cache[commit] = date
self.write_cache()
return parse_date(date)
def version_info(version):
info = tuple(map(int, version.split('.')))
if len(info) == 2:
info += (0,)
return info
def python_major_version(version):
# Return (2, 7) from '2.7.3'
return version_info(version)[:2]
class CommitTags:
def __init__(self, python_releases, python_path, cache_filename):
self.python_releases = python_releases
self.python_path = python_path
self.cache_filename = cache_filename
# commit (sha1) => tag list
# tag list: list of (version: tuple, tag: str)
self.cache = {}
self.read_cache()
def read_cache(self):
try:
fp = open(self.cache_filename, encoding="utf-8")
except FileNotFoundError:
return
with fp:
commit = None
tags = []
for line in fp:
line = line.rstrip()
if not line:
continue
if line.startswith(' ') and commit:
tag = line[1:]
tags.append(tag)
else:
if commit:
self.cache[commit] = tags
commit = line
tags = []
if commit and tags:
self.cache[commit] = tags
def write_cache(self):
with open(self.cache_filename, "w", encoding="utf-8") as fp:
items = sorted(self.cache.items())
for commit, tags in items:
# Don't cache commits which have no tag yet
if not tags:
continue
print(commit, file=fp)
for tag in tags:
print(" %s" % tag, file=fp)
def _get_tags(self, commit, ignore_python3):
print("Get commit %s tags" % commit)
cmd = ["git", "tag", "--contains", commit]
proc = run(cmd, self.python_path)
tags = []
for line in proc.stdout.splitlines():
line = line.rstrip()
if not line.startswith("v"):
continue
tag = line[1:]
# strip alpha part,
# 'c' is needed for v2.5.6c1
for suffix in ('a', 'b', 'rc', 'c'):
if suffix in tag:
tag = tag.partition(suffix)[0]
tag = version_info(tag)
if ignore_python3 and tag >= (3,):
continue
tags.append(tag)
tags.sort()
tags2 = []
seen = set()
major = None
for tag_info in tags:
key = tag_info[:2]
if key in seen:
continue
seen.add(key)
if tag_info[0] == major:
continue
if tag_info[2] == 0:
major = tag_info[0]
tag = '.'.join(map(str, tag_info))
try:
self.python_releases.get_date(tag)
except KeyError:
print("WARNING: Ignore tag %s: not released yet" % tag)
continue
tags2.append(tag)
tags = tags2
self.cache[commit] = tags
self.write_cache()
return tags
def get_tags(self, commit, ignore_python3=False):
if commit in self.cache:
return self.cache[commit]
if OFFLINE:
return []
tags = self._get_tags(commit, ignore_python3)
self.cache[commit] = tags
return tags
class Fix:
def __init__(self, commit, python_version, release_date):
self.commit = commit
self.python_version = python_version
self.release_date = release_date
def __repr__(self):
return '<Fix %r>' % self.commit
@staticmethod
def sort_key(fix):
return version_info(fix.python_version or "")
class DateComment:
def __init__(self, date, comment):
self.date = date
self.comment = comment
def __str__(self):
text = format_date(self.date)
if self.comment:
text = '%s (%s)' % (text, self.comment)
return text
def parse_date_comment(date):
comment = None
if isinstance(date, datetime.date):
return DateComment(date, comment)
# date is a string
date, _, comment = date.partition('(')
date = date.strip()
if comment:
if not comment.endswith(')'):
raise ValueError("date comment must be written in (...)")
comment = comment[:-1].strip()
date = parse_date(date)
return DateComment(date, comment)
class SpecialTransport(xmlrpc.client.SafeTransport):
def send_content(self, connection, request_body):
connection.putheader("Referer", "https://bugs.python.org/")
connection.putheader("Origin", "https://bugs.python.org")
connection.putheader("X-Requested-With", "XMLHttpRequest")
super().send_content(connection, request_body)
class PythonBugs:
def __init__(self, filename, bugs_api):
self.filename = filename
self.bugs_api = bugs_api
self.bugs = {}
self.github_api = None
self.load()
def load(self):
try:
bugs = load_yaml(self.filename)
except FileNotFoundError:
return
if not bugs:
return
bugs = {number: PythonBug.from_yaml(number, bug)
for number, bug in bugs.items()}
for number, bug in bugs.items():
self.bugs[number] = bug
def _get_bpo_bug(self, number):
if OFFLINE:
return None
print("Download Python issue bpo-%s" % number)
bug = {}
server = xmlrpc.client.ServerProxy(self.bugs_api, allow_none=True,
transport=SpecialTransport())
with server:
issue = server.display('issue%s' % number)
bug['title'] = issue['title']
msg = issue['messages'][0]
msg = server.display('msg%s' % msg)
match = BUGS_DATE_REGEX.match(msg['date'])
if not match:
raise Exception("unable to parse bug msg date: %r"
% msg['date'])
bug['date'] = match.group(1)
user = server.display('user%s' % msg['author'], 'username',
'realname')
bug['author'] = user['realname'] or user['username']
date = bug['date']
date = datetime.datetime.strptime(date[:19], "%Y-%m-%d.%H:%M:%S")
return PythonBug(f"bpo-{number}", bug['author'], bug['title'], date)
def _get_bug(self, key, func, number):
try:
return self.bugs[key]
except KeyError:
pass
bug = func(number)
if bug is None:
return None
self.bugs[key] = bug
self.dump()
return bug
def get_bpo_bug(self, number):
return self._get_bug(f"bpo-{number}", self._get_bpo_bug, number)
def _get_gh_bug(self, number):
print(f"Get GitHub issue #{number}")
if self.github_api is None:
self.github_api = github.Github(GITHUB_API_TOKEN)
project = self.github_api.get_repo(GITHUB_REPO)
issue = project.get_issue(number)
author = issue.user.login
date = issue.created_at
return PythonBug(f"gh-{number}", author, issue.title, date)
def get_gh_bug(self, number):
return self._get_bug(f"gh-{number}", self._get_gh_bug, number)
def dump(self):
data = {number: bug.to_yaml() for number, bug in self.bugs.items()}
dump_yaml(self.filename, data)
class PythonBug:
def __init__(self, number, author, title, date):
if number.startswith("gh-"):
url = GH_ISSUE_URL.format(int(number[3:]))
elif number.startswith("bpo-"):
url = BPO_URL.format(int(number[4:]))
else:
raise ValueError(f"unknown bug number: {number!r}")
self.number = number
self.author = author
self.date = date
self.datetime = datetime
self.title = title
self.url = url
@staticmethod
def from_yaml(number, data):
date = data['date']
return PythonBug(number, data['author'], data['title'], date)
def to_yaml(self):
return dict(author=self.author,
date=self.date,
title=self.title)
class CVERegistry:
def __init__(self, path):
self.path = path
self.cves = {}
try_mkdir(self.path)
self.load()
def load_cve(self, number, filename):
if os.path.getsize(filename) == 0:
# special case: empty file used as a marker to avoid
# downloading again, use None
cve = None
else:
cve = load_json(filename)
self.cves[number] = cve
def load(self):
for filename in glob.glob(os.path.join(self.path, '*.json')):
number = os.path.basename(filename[:-5])
if not number.startswith("CVE-"):
continue
self.load_cve(number, filename)
def dump(self):
for number, cve in self.cves.items():
if cve is None:
continue
filename = os.path.join(self.path, number + '.json')
dump_json(filename, cve)
def get_cve(self, number):
try:
cve = self.cves[number]
except KeyError:
if OFFLINE:
return None
url = CVE_API % number
print("Download %s" % url)
data = download(url)
data = data.decode('utf-8')
cve = json.loads(data)
if not cve:
print(f"WARNING: {url} returns empty JSON")
cve = None
self.cves[number] = cve
self.dump()
if cve is None:
return None
return CVE(number, cve)
class CVE:
def __init__(self, number, data):
self.number = number
try:
self.published = parse_date(data['Published'])
self.summary = data['summary']
self.cvss = data['cvss']
except Exception:
raise Exception("failed to parse %s" % self.number)
def __repr__(self):
return '<%s>' % self.number
class Vulnerability:
def __init__(self, app, data):
self.name = data.pop('name')
self.fixes = None
self.unreleased_commits = []
try:
self.parse(app, data)
except KeyError as exc:
raise Exception("failed to parse %r: missing key %s"
% (self.name, exc))
except OfflineError:
raise
except Exception as exc:
raise Exception("failed to parse %r: %s" % (self.name, exc))
def __repr__(self):
return '<Vulnerability %r>' % self.name
def parse(self, app, data):
self.python_bug = None
gh = int(data.pop('gh', 0))
if gh:
self.python_bug = app.bugs.get_gh_bug(gh)
else:
bpo = int(data.pop('bpo', 0))
if bpo:
self.python_bug = app.bugs.get_bpo_bug(bpo)
disclosure = data.pop('disclosure', None)
if disclosure:
self.disclosure = parse_date_comment(disclosure)
elif self.python_bug:
self.disclosure = None
else:
msg = "bug has no bpo no disclosure date"
if OFFLINE:
raise OfflineError(msg)
else:
raise Exception(msg)
reported_at = data.pop('reported-at', None)
if reported_at is not None:
self.reported_at = parse_date_comment(reported_at)
else:
self.reported_at = None
self.description = data.pop('description').strip()
self.links = data.pop('links', None)
if not self.links:
self.links = []
self.redhat_impact = data.pop('redhat-impact', None)
reported_by = data.pop('reported-by', None)
if reported_by is not None:
self.reported_by = reported_by.strip()
if not self.reported_by:
raise Exception("empty reported-by")
elif self.python_bug:
self.reported_by = None
else:
raise Exception("no reported-by nor bpo")
# CVE
cves = set()
self.cve_list = []
cve_ids = data.pop('cve', None)
if cve_ids is not None:
if isinstance(cve_ids, str):
cve_ids = [cve_ids]
for cve_id in cve_ids:
if not CVE_REGEX.match(cve_id):
raise ValueError("invalid CVE number: %r" % cve_id)
# get_cve() can return None
cve_obj = app.cves.get_cve(cve_id)
if cve_obj is not None:
self.cve_list.append(cve_obj)
else:
# Add a link if there is no CVE detail
cves.add(cve_id)
self.cve_list.sort(key=lambda cve: cve.number)
for cve in CVE_REGEX.findall(self.description):
cves.add(cve)
for cve in sorted(cves):
url = CVE_URL % cve
self.links.append(url)
self.find_fixes(app, data)
self.slug = data.pop('slug', None)
if not self.slug:
raise ValueError("%r has not slug" % self)
if not re.match("^[a-z][a-z0-9_]+(-[a-z0-9._]+)*$", self.slug):
raise ValueError("invalid slug: %r" % self.slug)
if data:
raise Exception("Vulnerability %r has unknown keys: %s"
% (self.name, ', '.join(sorted(data))))
def find_fixes(self, app, data):
fixes = []
ignore_python3 = data.pop('ignore-python3', None)
commits_branches = data.pop('fixed-in', ())
commits = []
if commits_branches:
# [{branch: commit}] => [(branch, commit)]
for commit_branches in commits_branches:
for branch, commit in commit_branches.items():
commits.append((branch, commit))
for branch, revision in commits:
date = app.commit_dates.get_commit_date(revision)
if date is None:
# offline mode and the date is unknown
continue
if isinstance(branch, float):
# convert 3.2 (float) to '3.2' (str)
raise Exception(f"Branch {branch!r} must be written "
f"as a string in YAML")
commit = Commit(revision, branch, date)
versions = app.commit_tags.get_tags(commit.revision,
ignore_python3=ignore_python3)
added = False
for version in versions:
try:
release_date = app.python_releases.get_date(version)
except KeyError:
print("WARNING: Ignore version %s: not released yet"
% version)
continue
fix = Fix(commit, version, release_date)
fixes.append(fix)
added = True
if not added:
self.unreleased_commits.append(commit)
fixes.sort(key=Fix.sort_key)
self.fixes = []
seen = set()
seen_major = set()
major = None
for fix in fixes:
pyver_info = version_info(fix.python_version)
key = version_info(fix.python_version)
if key not in seen:
seen.add(key)
key = python_major_version(fix.python_version)
if key in seen_major:
continue
seen_major.add(key)
if pyver_info[0] == major:
continue
if pyver_info[2] == 0:
major = pyver_info[0]
self.fixes.append(fix)
affected_versions = data.pop('affected-versions', ())
affected_versions = ['%.1f' % version if isinstance(version, float)
else version
for version in affected_versions]
affected_versions = list(map(version_info, affected_versions))
def is_fixed(ver1, ver2):
if ver1[0] != ver2[0]:
return False
if ver1[1] == ver2[1]:
# 3.5 is fixed if 3.5.6 is fixed
return True
# 3.6 is fixed if 3.5.0 is fixed
return ((len(ver2) == 2 or ver2[2] == 0)
and ver1 >= ver2)
def is_affected(version, affected):
version = version_info(version)
if version[0] > affected[0]:
# "affected=(2, 0)" means that Python 3.x is not affected
return False
return (version[:2] == affected[:2])
vulnerable = []
for version in MAINTAINED_BRANCHES:
major = python_major_version(version)
if major in seen:
continue
if any(is_fixed(major, fixed) for fixed in seen):
continue
if affected_versions:
if not any(is_affected(version, affected)
for affected in affected_versions):
continue
if any(commit.branch == version
for commit in self.unreleased_commits):
reason = "need release"
else:
reason = "need commit"
vulnerable.append((version, reason))
vulnerable.sort()
need_commit_versions = [version for version, reason in vulnerable
if reason == 'need commit']
if need_commit_versions:
print("%r vulnerable versions (need commit): %s"
% (self.name, ', '.join(need_commit_versions)))
self.vulnerable_versions = vulnerable
def get_disclosure_date(self):
if self.disclosure:
return self.disclosure.date
else:
return self.python_bug.date.date()
@staticmethod
def sort_key(vuln):
date = datetime.date.min - vuln.get_disclosure_date()
return (date, vuln.name)
class PythonReleases:
def __init__(self, python_path):
self.dates = {}
self.python_path = python_path
if OFFLINE:
self.load()
else:
self.update()
def get_date(self, version):
if version.count('.') == 1:
version += '.0'
try:
return self.dates[version]
except KeyError:
raise KeyError("missing release date of Python %s" % version)
@staticmethod
def is_release_tag(tag):
return all(v not in tag and 'v' in tag for v in ['a', 'b', 'c', 'rc'])
@staticmethod
def format_version(version):
if version.count('.') == 1:
version += '.0'
return version[1:] if version.startswith('v') else version
def get_release_tags(self):
cmd = ["git", "tag", "-l"]
proc = run(cmd, self.python_path, text=False)
tags = []
for line in proc.stdout.splitlines():
tag = line.decode()
if self.is_release_tag(tag):
tags.append(tag)
return tags
def get_date_from_tag(self, tag):
cmd = ["git", "show", tag]
proc = run(cmd, self.python_path, text=False)
for line in proc.stdout.splitlines():
if not line.startswith(b'Date:'):
continue
line = line[5:].decode().strip()
return parse_date(line)
def load(self):
with open("python_releases.txt", encoding="utf-8") as fp:
for line in fp:
line = line.strip()
if not line:
continue
parts = line.split(":", 1)
version = parts[0].strip()
date = parts[1].strip()
date = parse_date(date)
self.dates[version] = date
def update(self):
tags = self.get_release_tags()
tags.sort(key=lambda tag:version_info(tag[1:]))
with open("python_releases.txt", mode='w+', encoding="utf-8") as fp:
last_key = ''
for tag in tags:
version = self.format_version(tag)
key = version.rsplit('.', 1)[0]
if key != last_key and last_key:
# Group by major version X.Y
print(file=fp)
date = self.get_date_from_tag(tag)
self.dates[version] = date
print('{}: {}'.format(version, date), file=fp)
last_key = key
def render_title(fp, title, line='='):
print(title, file=fp)
print(line * len(title), file=fp)
print(file=fp)
def render_timeline(fp, vuln):
render_title(fp, "Timeline", "-")
day0 = vuln.get_disclosure_date()
# list of (date, sort_order, show_days, text)
dates = []
if vuln.reported_at:
text = "Reported"
if vuln.reported_at.comment:
text = '%s (%s)' % (text, vuln.reported_at.comment)
dates.append((vuln.reported_at.date, 0, True, text))
if vuln.disclosure:
text = "Disclosure date"
if vuln.disclosure.comment:
text = '%s (%s)' % (text, vuln.disclosure.comment)
dates.append((vuln.disclosure.date, 1, False, text))
if vuln.python_bug:
bug = vuln.python_bug
text = ("`Python issue %s <%s>`_ reported by %s"
% (bug.number, bug.url, bug.author))
dates.append((bug.date.date(), 2, bool(vuln.disclosure), text))
for cve in vuln.cve_list:
text = "%s published" % cve.number
dates.append((cve.published, 3, True, text))
commit_seen = set()
for commit in vuln.unreleased_commits:
if commit.revision in commit_seen:
continue
commit_seen.add(commit.revision)
text = commit.format()
dates.append((commit.date, 4, True, text))
for fix in vuln.fixes:
if fix.commit.revision in commit_seen:
continue
commit_seen.add(fix.commit.revision)
text = fix.commit.format()
dates.append((fix.commit.date, 5, True, text))
for index, fix in enumerate(vuln.fixes):
pyver_info = version_info(fix.python_version)
# Don't show the date/days fort 3.x.0 releases, except
# if it's the first (and so the only) version having
# the fix (ex: CVE-2013-7040)
show_days = (pyver_info[2] != 0 or index == 0)
text = "Python %s released" % fix.python_version
dates.append((fix.release_date, 6, show_days, text))
dates.sort()
print("Timeline using the disclosure date **%s** as reference:"
% (format_date(day0)), file=fp)
print(file=fp)
for date, sort_order, show_days, text in dates:
days = timedelta_days(date - day0)
date = format_date(date)
if show_days and days:
date = "%s (**%+i days**)" % (date, days)
print("* %s: %s" % (date, text), file=fp)
print(file=fp)
def render_info(fp, vuln):
if vuln.disclosure: