Ejemplo n.º 1
0
    def clean(self):
        """ clean directory"""
        print("[+] Cleaning tmp downloads ...")

        try:
            for file in os.listdir(self.path):
                if "tgz" in file or "update" in file:
                    os.remove(os.path.join(self.path, file))
                else:
                    pass

        except Exception as e:
            utility.serialize_error(False, "already cleaned", str(e))
Ejemplo n.º 2
0
    def search_cpe(self):
        """ basic search for CPE identifiers """

        if not self.id.startswith("cpe:/") and not self.id.startswith("cpe:2.3:"):
            response = utility.serialize_error(False, self.id, "Not a valid CPE identifier")
            return response

        # check whether is CPE 2.2 or CPE 2.3
        if "cpe:2.3" in self.id:
            col = "cpe23_id"

        if "cpe:/" in self.id:
            col = "cpe_id"

        # query the database
        self.cur.execute("SELECT cve_id FROM map_cpe_cve WHERE {tn} = ? ORDER BY cve_id DESC".format(tn=col),
                         self.query)
        data = self.cur.fetchall()

        if data:
            # init dict
            cve = []
            for cve_id in data:
                cve.append(cve_id[0])

            # set the response
            response = {"id": self.id, "vulnerability": cve}
            return utility.serialize_data(response)
Ejemplo n.º 3
0
    def check_status(self, file):
        """ check if new db is available"""

        # set the target file
        file = os.path.join(self.path, file)

        try:

            with open(file, 'r') as f:
                checksum_remote = f.read().strip()

                print("\t[-] Checksum verification", checksum_remote)

                if checksum_remote == utility.checksum(self.local_db):
                    print("\t[-] Already updated")
                    self.clean()

                else:
                    print("\t[-] Database update available")
                    self.download(self.remote_db)
                    self.unpack_database()

        except Exception as e:
            response = utility.serialize_error(False, str(e), str(e))
            sys.exit(response)
Ejemplo n.º 4
0
    def update(self):
        """ callable method - initiate the database update in accordance with plan validity """

        # init authorization
        files = self.authorization()

        try:
            for self.file in files:

                if "update" in self.file:
                    self.update_file = self.file
                else:
                    self.remote_db = self.file

            if not os.path.isfile(self.local_db):
                print("[+] Deploying new database ...")
                self.download(self.remote_db)
                self.unpack_database()

            else:
                print("[+] Checking update status ...")
                self.download(self.update_file)
                self.check_status(self.update_file)

        except Exception as e:
            response = utility.serialize_error(False, str(e), str(e))
            sys.exit(response)
Ejemplo n.º 5
0
 def db_init(self):
     try:
         self.conn = sqlite3.connect(self.db)
         self.cur = self.conn.cursor()
         self.query = (self.identifier, )
         return self.cur, self.query
     except sqlite3.OperationalError as e:
         response = utility.serialize_error(False, str(e), str(e))
         sys.exit(response)
Ejemplo n.º 6
0
    def download(self, file):
        """ download files"""

        print("\t[-] Downloading", file)

        # set the target file
        self.target = os.path.join(self.path, file)

        try:
            self.bucket.download_file(file, self.target)

        except Exception as e:
            response = utility.serialize_error(False, str(e), str(e))
            sys.exit(response)
Ejemplo n.º 7
0
    def unpack_database(self):
        """ extract database """

        print("\t[-] Unpacking", self.target)

        try:
            tar = tarfile.open(self.target, 'r:gz')
            tar.extractall('.')
        except Exception as e:
            response = utility.serialize_error(False, str(e), str(e))
            sys.exit(response)

        shutil.move(self.db, self.local_db)
        self.clean()
Ejemplo n.º 8
0
    def search_cwe(self):
        """ basic search CWE identifiers """

        # set the CWE as uppercase
        self.cwe = self.id.upper()

        # check if valid CWE
        if not self.cwe.startswith('CWE-'):
            response = utility.serialize_error(False, self.id,
                                               "Not a valid CWE identifier")
            return response

        # query the database
        self.cur.execute(
            "SELECT title,class,link  FROM cwe_db WHERE cwe_id=? ",
            (self.cwe, ))
        cwe_data = self.cur.fetchone()

        if cwe_data:
            # set the CWE data
            title = cwe_data[0]
            cwe_class = cwe_data[1]
            url = cwe_data[2]

            # query the database
            self.cur.execute(
                "SELECT cve_id from map_cwe_cve where cwe_id=? ORDER BY cve_id DESC",
                (self.cwe, ))
            data = self.cur.fetchall()

            if data:
                # init dict
                cve = []
                for cve_id in data:
                    cve.append(cve_id[0])

                # set the response
                response = {
                    "id": self.cwe,
                    "parameters": {
                        "title": title,
                        "class": cwe_class,
                        "url": url
                    },
                    "vulnerability": cve
                }

                return utility.serialize_data(response)
Ejemplo n.º 9
0
    def authorization(self):
        """ check authorization """

        # init files dict
        files = []

        try:
            session = Session(aws_access_key_id=self.access_key,
                              aws_secret_access_key=self.secret_key)
            s3 = session.resource('s3')
            self.bucket = s3.Bucket(self.plan_license)

            for file in self.bucket.objects.all():
                files.append(file.key)

        except Exception as e:

            if "Could not connect" in str(e):
                reason = "Connectivity error"
            else:
                code_error = e.response["Error"]["Code"]

                if code_error == "403":
                    reason = "Access suspended to: %s" % self.plan_license

                if code_error == "AccessDenied":
                    reason = "Access denied to plan: %s" % self.plan_license

                if code_error == "InvalidAccessKeyId":
                    reason = "Error on access key: %s" % self.access_key

                if code_error == "SignatureDoesNotMatch":
                    reason = "Error on secret key: %s" % self.secret_key

                if code_error == "AuthorizationHeaderMalformed":
                    reason = "Empty access key"

                if code_error == "NoSuchBucket":
                    reason = "Licensed plan not specified."

            response = utility.serialize_error(False, reason, str(e))
            sys.exit(response)

        return files
Ejemplo n.º 10
0
    def search_cve(self):
        """ basic search CVE identifiers """

        # set the CVE as uppercase
        self.id = self.id.upper()

        # check if valid CVE
        if not self.id.startswith('CVE-'):
            response = utility.serialize_error(False, self.id, "Not a valid CVE identifier")
            return response

        # load CVE data
        response = json.loads(Information(self.id).get_info())
        exploits = json.loads(Exploitation(self.id).get_exploits())

        if response['description'] != []:
            # new tag added to search whenever an exploits is available
            if exploits['exploitation'] != []:
                response.update(exploits)

            return utility.serialize_data(response)
Ejemplo n.º 11
0
    def search_cpe(self):
        """ basic search for CPE identifiers """

        if "cpe" not in self.id:
            response = utility.serialize_error(False, self.id,
                                               "Not a valid CPE identifier")
            return response

        # check whether is CPE 2.2 or CPE 2.3
        if "cpe:2.3" in self.id:
            col = "cpe23_id"

        if "cpe:/" in self.id:
            col = "cpe_id"

        self.cur.execute(
            "SELECT count(DISTINCT {tn}) FROM map_cpe_cve WHERE {tn} = ? ORDER BY cve_id DESC"
            .format(tn=col), self.query)
        self.count_cpe = self.cur.fetchone()

        self.cur.execute(
            "SELECT * FROM map_cpe_cve WHERE {tn} = ? ORDER BY cve_id DESC".
            format(tn=col), self.query)
        data = self.cur.fetchall()

        if data:
            for i in range(0, self.count_cpe[0]):
                # init dict
                cve = []
                self.cur.execute(
                    "SELECT cve_id FROM map_cpe_cve WHERE {tn} = ? ORDER BY cve_id DESC"
                    .format(tn=col), self.query)

                for cve_id in self.cur.fetchall():
                    cve.append(cve_id[0])

                item = {"id": self.id, "vulnerability": cve}
                self.result.append(item)

        return utility.serialize_data(self.result)
Ejemplo n.º 12
0
try:
    from core.Risk import Risk
    from lib.Update import Update
    from lib.Search import Search
    from core.Export import Export
    from core.Defense import Defense
    from lib.Version import APIversion
    from common import utils as utility
    from core.Inspection import Inspection
    from core.Information import Information
    from core.Exploitation import Exploitation
    from core.Classification import Classification
except ImportError as e:
    module = str(e).split("'")
    response = utility.serialize_error(False, module[1], module[0])
    sys.exit(response)

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("--version", help="API info", action="store_true", required=False)
    parser.add_argument("--update", help="Database update", action="store_true", required=False)
    parser.add_argument("--information", metavar="CVE, CPE", type=str, help="Get information data",
                        nargs=1)
    parser.add_argument("--classification", metavar="CVE, CPE", type=str, help="Get classification data",
                        nargs=1)
    parser.add_argument("--risk", metavar="CVE, CPE", type=str, help="Get risk data",
                        nargs=1)
    parser.add_argument("--inspection", metavar="CVE, CPE", type=str, help="Get Vulnerability testing data",
                        nargs=1)