#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Dump last CVE entries in RSS 1,RSS 2 or Atom format.
#
# Software is free software released under the "GNU Affero General Public License v3.0"
#
# Copyright (c) 2012-2018  Alexandre Dulaunoy - a@foo.be
# Copyright (c) 2015-2018  Pieter-Jan Moreels - pieterjan.moreels@gmail.com

import argparse
import datetime
import html
import os
import sys
import time

runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

from lib.CVEs import CveHandler

argParser = argparse.ArgumentParser(
    description="Dump last CVE entries in RSS/Atom format or in HTML tables"
)
argParser.add_argument(
    "-f", type=str, help="Output format (rss1,rss2,atom,html)", default="rss1"
)
argParser.add_argument("-l", type=int, help="Last n items (default:10)", default=10)
argParser.add_argument(
    "-n", action="store_false", help="Disable lookup CPE name (default is True)"
)
argParser.add_argument(
    "-r",
    action="store_true",
    help="Enable CVE ranking (default is False) and only print entries with ranking",
)
argParser.add_argument(
    "-c", default=False, action="store_true", help="Display CAPEC values"
)

args = argParser.parse_args()

if args.l:
    last_items = args.l
else:
    last_items = 10

ref = "https://github.com/cve-search/cve-search/"
cvelist = CveHandler(rankinglookup=args.r, namelookup=args.n, capeclookup=args.c)

if not (args.f == "html"):
    from feedformatter import Feed

    feed = Feed()

    feed.feed["title"] = (
        "cve-search Last "
        + str(last_items)
        + " CVE entries generated on "
        + str(datetime.datetime.now())
    )
    feed.feed["link"] = "https://github.com/cve-search/cve-search/"
    feed.feed["author"] = (
        "Generated with cve-search available at https://github.com/cve-search/cve-search/"
    )
    feed.feed["description"] = ""
else:
    print("<html><head>")
    print(
        "<style>.cve table { border-collapse: collapse; text-align: left; width: 100%; } .cve {font: normal 12px/150% "
        "Geneva, Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; "
        "-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }.cve table td, .cve table th { "
        "padding: 3px 10px; }.cve table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: "
        "12px;font-weight: normal; }.cve table tbody .alt td { background: #E1EEF4; color: #00496B; }.cve table tbody "
        "td:first-child { border-left: none; }.cve table tbody tr:last-child td { border-bottom: none; }.cve table "
        "tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .cve table tfoot td { padding: 0; "
        "font-size: 12px } .cve table tfoot td div{ padding: 0px; }</style> "
    )
    print("<title>Last " + str(args.l) + " CVE entries</title>")
    print("</head><body>")
for x in cvelist.get(limit=last_items):
    if not (args.f == "html"):
        item = {
            "title": str(x["id"]) + " " + x["summary"][:90] + "...",
            "description": x["summary"],
        }
        if args.r and x.get("ranking"):
            item["description"] = item["description"] + " Ranking:" + str(x["ranking"])
        item["pubDate"] = time.localtime()
        item["guid"] = x["id"]
        if x["references"]:
            item["link"] = str(x["references"][0])
        else:
            item["link"] = "https://nvd.nist.gov/vuln/detail/" + x["id"]
        feed.items.append(item)
    else:
        print('<div class="cve"><table><tbody>')
        print('<tr class="alt">')
        print(
            "<td>"
            + str(x.get("id", ""))
            + " - "
            + html.escape(x.get("summary", "")[:90])
            + "...</td>"
        )
        print("</tr>")
        print(
            "<tr><td>CVSS: "
            + str(x.get("cvss", "N/A"))
            + " published: "
            + str(x.get("published", "N/A"))
            + "</td></tr>"
        )
        print("<tr>")
        print("<td> Summary: " + html.escape(x.get("summary", "")) + "</td>")
        print("</tr>")

        vc = x.get("vulnerable_configuration", [])
        if vc:
            print("<tr><td>Vulnerable configuration:</td></tr>")
            print("<tr><td><ul>")
            for v in vc:
                if isinstance(v, dict):
                    label = v.get("title") or v.get("id", "")
                    sys.stdout.write(f"<li>{html.escape(label)}</li>")
                else:
                    sys.stdout.write(f"<li>{html.escape(cvelist.getcpe(v))}</li>")
            print("</ul></td></tr>")

        vp = x.get("vulnerable_product", [])
        if vp:
            print("<tr><td>Vulnerable products:</td></tr>")
            print("<tr><td><ul>")
            for p in vp:
                sys.stdout.write(f"<li>{html.escape(cvelist.getcpe(p))}</li>")
            print("</ul></td></tr>")

        if x.get("ranking"):
            print(f"<tr><td>Ranking: {html.escape(str(x['ranking']))}</td></tr>")

        refs = x.get("references", [])
        if refs:
            print("<tr><td>References:</td></tr>")
            print("<tr><td><ul>")
            for r in refs:
                if r:  # ignore empty strings/nulls
                    safe_r = html.escape(str(r))
                    sys.stdout.write(f'<li><a href="{safe_r}">{safe_r}</a></li>')
            print("</ul></td></tr>")

        print("</tbody></table></div><br/>")
if args.f == "rss1":
    print(feed.format_rss1_string())
elif args.f == "atom":
    print(feed.format_atom_string())
elif args.f == "html":
    print(
        'Generated with <a href="https://github.com/cve-search/cve-search/">cve-search</a> at '
        + str(datetime.datetime.today())
        + "."
    )
    print("</body></html>")
else:
    print(feed.format_rss2_string())
