#!/usr/bin/env python
import json
import colorama
import sys
from termcolor import colored
from tabulate import tabulate

'''
Quick script to format the result of a RetireJS JSON report:
    retire --path . --outputformat json --outputpath retire.json --nocache --ignore "*target*"

Dependencies:
    pip install tabulate colorama termcolor
'''
retirejs_json_report = sys.argv[1]
colorama.init()
with open(retirejs_json_report) as f:
    content = f.read()
v = json.loads(content)
print(colored("[+] Vulnerabilities:", "yellow"))
table_headers = ["Severity", "Description", "CVE"]
cve_list = []
severities_distribution = {}
for f in v["data"]:
    name = f["file"]
    version = f["results"][0]["version"]
    print(colored(f"\nFILE '{name}' - VERSION '{version}'", "green", attrs=["bold"]))
    table_rows = []
    for vuln in f["results"][0]["vulnerabilities"]:
        desc = vuln["identifiers"]["summary"]
        if len(desc) > 100:
            desc = f"{desc[0:100]}..."
        severity = vuln["severity"].upper()
        if severity == "HIGH":
            severity_color = "red"
        elif severity == "MEDIUM":
            severity_color = "yellow"
        elif severity == "LOW":
            severity_color = "cyan"
        else:
            severity_color = "white"
        severity = colored(f"{severity}", severity_color, attrs=["bold"])
        if severity not in severities_distribution:
            severities_distribution[severity] = 0
        severities_distribution[severity] += 1
        cves = "NONE"
        if "CVE" in vuln["identifiers"]:
            cve_list.extend(vuln["identifiers"]["CVE"])
            cves = ",".join(vuln["identifiers"]["CVE"])
        table_rows.append([severity, desc, cves])
        table_rows.sort()
    print(tabulate(table_rows, headers=table_headers))
cve_list = list(set(cve_list))
print("")
print(colored("[+] Vulnerabilities severity distribution:", "yellow"))
table_headers = ["Severity", "Vulnerability count"]
table_rows.clear()
for severity_name, severity_count in severities_distribution.items():
    table_rows.append([severity_name, severity_count])
table_rows.sort()
print(tabulate(table_rows, headers=table_headers))
print(" ")
print(colored(f"[+] List of CVE ({len(cve_list)}):", "yellow"))
cve_list.sort(reverse=True)
print("\n".join(cve_list))
print(" ")
