#!/usr/bin/python3

"""
CVE checker for libnss

References:
http://www.cvedetails.com/vulnerability-list/vendor_id-452/product_id-4052/Mozilla-Network-Security-Services.html

RSS feed: http://www.cvedetails.com/vulnerability-feed.php?vendor_id=452&product_id=4052&version_id=&orderby=3&cvssscoremin=0
"""
from ..util import regex_find


def guess_contains_nss(lines):
    """Tries to determine if a file includes libnss
    """
    signatures = [
        "Client authentication failed: private key in key database does not match public key in certificate database.",
        "The next protocol negotiation extension was enabled, but the callback was cleared prior to being needed.",
        "# SSL/TLS secrets log file, generated by NSS",
        "Header: NSS ",
        "Version: NSS ",
    ]
    for line in lines:
        for signature in signatures:
            if signature in line:
                return 1

    return 0


def get_version(lines, filename):
    """returns version information for libnss as found in a given file.
    The version info is returned as a tuple:
        [modulename, is_or_contains, version]

    modulename will be libnss if libnss is found (and blank otherwise)
    is_or_contains idicates if the file is a copy of libnss or contains one
    version gives the actual version number

    VPkg: mozilla, network_security_services
    """
    regex = [
        r"\$Header: NSS ([01234]+\.[0-9]+) ",
        r"\$Header: NSS ([01234]+\.[0-9]+\.[0-9]+) ",
        r"\$Header: NSS ([01234]+\.[0-9]+\.[0-9]+)\.[0-9]+ ",
        r"Version: NSS ([01234]+\.[0-9]+) Basic",
        r"Version: NSS ([01234]+\.[0-9]+\.[0-9]+) Basic",
        r"Version: NSS ([01234]+\.[0-9]+\.[0-9]+)\.[0-9]+ Basic",
        r"Version: NSS (\d+\.\d+\.\d+)",
        r"\@\(#\)NSS ([01234]+\.[0-9]+) Basic",
        r"\@\(#\)NSS ([01234]+\.[0-9]+\.[0-9]+) Basic",
        r"\@\(#\)NSS ([01234]+\.[0-9]+\.[0-9]+)\.[0-9]+ Basic",
    ]
    version_info = dict()
    if "libnss.so." in filename or "libssl3.so" in filename:
        version_info["is_or_contains"] = "is"
    elif guess_contains_nss(lines):
        version_info["is_or_contains"] = "contains"

    if "is_or_contains" in version_info:
        version_info["modulename"] = "nss"
        version_info["version"] = regex_find(lines, *regex)

    return version_info
