#!/usr/bin/env python3
"""Create a clearly labelled ingestion-audit Report, not an intelligence claim.
Adds catalog source references to this report; does not rewrite vendor data.
"""
import hashlib
import json
import os
import urllib.request
from pycti import OpenCTIApiClient

url = 'https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json'
api = OpenCTIApiClient(os.environ['OPENCTI_URL'], os.environ['OPENCTI_TOKEN'], log_level='ERROR')
with urllib.request.urlopen(url, timeout=60) as response:
    raw = response.read()
catalog = json.loads(raw)
digest = hashlib.sha256(raw).hexdigest()
source = api.external_reference.create(source_name='CISA KEV official catalog', url=url,
    external_id=catalog['catalogVersion'], description='Official CISA mirror; retrieved SHA-256 ' + digest)
author = api.identity.create(name='SecTools Tutorial Verification', type='Organization',
    description='Tutorial verification author; not CISA and not a threat actor.')
description = ('Ingestion verification report authored by the tutorial, not a CISA publication.\n'
    'Official catalog: ' + url + '\nCatalog version: ' + catalog['catalogVersion'] +
    '\nSource release: ' + catalog['dateReleased'] + '\nSource count: ' + str(catalog['count']) +
    '\nSHA-256: ' + digest + '\nThis report links three verification samples only; '
    'it does not claim these vulnerabilities affect a particular organization or that all catalog fields were imported.')
report = api.report.create(name='CISA KEV source verification / ' + catalog['catalogVersion'],
    description=description, published=catalog['dateReleased'], report_types=['threat-report'],
    createdBy=author['id'], externalReferences=[source['id']], confidence=50)
sample_rows = [catalog['vulnerabilities'][0], catalog['vulnerabilities'][len(catalog['vulnerabilities'])//2], catalog['vulnerabilities'][-1]]
ids = []
for row in sample_rows:
    candidates = api.vulnerability.list(search=row['cveID'], first=10)
    matches = [x for x in candidates if x['name'] == row['cveID']]
    assert len(matches) == 1, 'Expected one imported CVE'
    ids.append(matches[0]['id'])
    api.report.add_stix_object_or_stix_relationship(id=report['id'], stixObjectOrStixRelationshipId=ids[-1])
fresh = api.query('''query($id:String!){report(id:$id){id name description
  createdBy{... on Identity{name}} externalReferences{edges{node{url external_id}}}
  objects(first:100){edges{node{... on BasicObject{id}}}}}}''', {'id':report['id']})['data']['report']
assert set(ids) == {x['node']['id'] for x in fresh['objects']['edges']}
assert any(x['node']['url'] == url for x in fresh['externalReferences']['edges'])
assert digest in fresh['description']
print('PASS provenance Report source URL, hash, catalog version and three real imported CVE references', flush=True)
print('ARTIFACT ' + json.dumps(fresh, ensure_ascii=False), flush=True)
