|
| 1 | +import os |
| 2 | +import urllib.request |
| 3 | +from urllib.error import HTTPError |
| 4 | +from zipfile import ZipFile |
| 5 | +from io import BytesIO |
| 6 | +import saneyaml |
| 7 | +from dephell_specifier import RangeSpecifier |
| 8 | +from urllib.request import urlopen |
| 9 | + |
| 10 | +RUBYSEC_DB_URL = 'https://github.com/rubysec/ruby-advisory-db/archive/master.zip' |
| 11 | + |
| 12 | + |
| 13 | +def rubygem_advisories(url, prefix='ruby-advisory-db-master/gems/'): |
| 14 | + with urlopen(url) as response: |
| 15 | + with ZipFile(BytesIO(response.read())) as zf: |
| 16 | + for path in zf.namelist(): |
| 17 | + if path.startswith(prefix) and path.endswith('.yml'): |
| 18 | + yield saneyaml.load(zf.open(path)) |
| 19 | + |
| 20 | + |
| 21 | +def get_all_versions_of_package(package_name): |
| 22 | + url_to_load = 'https://rubygems.org/api/v1/versions/' + package_name + '.yaml' |
| 23 | + try: |
| 24 | + page = urllib.request.urlopen(url_to_load) |
| 25 | + package_history = saneyaml.load(page) |
| 26 | + except HTTPError: |
| 27 | + return [] |
| 28 | + for version in package_history: |
| 29 | + yield version['number'] |
| 30 | + |
| 31 | + |
| 32 | +def get_patched_range(spec_list): |
| 33 | + spec_list = [string.replace(' ', '') for string in spec_list] |
| 34 | + for spec in spec_list: |
| 35 | + if 'rc' in spec: |
| 36 | + continue |
| 37 | + yield RangeSpecifier(spec) |
| 38 | + |
| 39 | + |
| 40 | +def import_vulnerabilities(): |
| 41 | + vulnerability_package_dicts = [] |
| 42 | + for vulnerability in rubygem_advisories(RUBYSEC_DB_URL): |
| 43 | + |
| 44 | + package_name = vulnerability.get( |
| 45 | + 'gem') |
| 46 | + |
| 47 | + if not package_name: |
| 48 | + continue |
| 49 | + |
| 50 | + if 'cve' in vulnerability: |
| 51 | + vulnerability_id = 'CVE-{}'.format(vulnerability['cve']) |
| 52 | + else: |
| 53 | + continue |
| 54 | + |
| 55 | + advisory_url = vulnerability.get('url') |
| 56 | + patched_version_ranges = list( |
| 57 | + get_patched_range( |
| 58 | + vulnerability.get('patched_versions', []))) |
| 59 | + all_versions = set(get_all_versions_of_package(package_name)) |
| 60 | + unaffected_versions = set() |
| 61 | + |
| 62 | + if patched_version_ranges: |
| 63 | + for version in all_versions: |
| 64 | + for spec in patched_version_ranges: |
| 65 | + if version in spec: |
| 66 | + unaffected_versions.add(version) |
| 67 | + break |
| 68 | + |
| 69 | + affected_versions = all_versions - unaffected_versions |
| 70 | + vulnerability_package_dicts.append({ |
| 71 | + 'package_name': package_name, |
| 72 | + 'cve_id': vulnerability_id, |
| 73 | + 'fixed_versions': unaffected_versions, |
| 74 | + 'affected_versions': affected_versions, |
| 75 | + 'advisory': advisory_url |
| 76 | + }) |
| 77 | + return vulnerability_package_dicts |
0 commit comments