#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

"""
Faraday Penetration Test IDE
Copyright (C) 2016  Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information

Autor: Ezequiel Tavella

This script get all CVEs of vulns in the active workspace and search
for exploits in the vFeed database.
Support : Exploit-db, Metasploit, Milworm, D2, Saint

Thanks ToolsWatch!!!
www.toolswatch.org
"""

import os
import sqlite3

from persistence.server import models

__description__ = 'Get possible exploits from open services'
__prettyname__ = 'Get Exploits'

faraday_directory = os.path.dirname(os.path.realpath(os.path.join(__file__, "../")))

DB_PATH = os.path.join(faraday_directory, 'data/vfeed.db')
URL_DB = "http://www.toolswatch.org/vfeed/vfeed.db.tgz"


def getExploits(cve_id, cursor):
    result = {
        'exploit-db': [],
        'metasploit': [],
        'milworm': [],
        'd2': [],
        'saint': []
    }

    value = (cve_id.upper(),)

    # D2 exploits
    consult = cursor.execute(
        "SELECT d2_script_file FROM map_cve_d2 WHERE cveid = ?",
        value
    )

    for row in consult:
        for i in row:
            result['d2'].append(i)

    # Exploit-db exploits
    consult = cursor.execute(
        "SELECT exploitdbscript FROM map_cve_exploitdb WHERE cveid = ?",
        value
    )

    for row in consult:
        for i in row:
            result['exploit-db'].append(i)

    # Metasploit exploits
    consult = cursor.execute(
        "SELECT msf_script_file FROM map_cve_msf WHERE cveid = ?",
        value
    )

    for row in consult:
        for i in row:
            result['metasploit'].append(i)

    # Milworm exploits
    consult = cursor.execute(
        "SELECT milw0rmid FROM map_cve_milw0rm WHERE cveid = ?",
        value
    )

    for row in consult:
        for i in row:
            result['milworm'].append(i)

    # Saint exploits
    consult = cursor.execute(
        "SELECT saintexploitlink FROM map_cve_saint WHERE cveid =  ?",
        value
    )

    for row in consult:
        for i in row:
            result['saint'].append(i)

    return result


def printExploits(vuln, references, cursor):
    global getExploits

    for ref in references:
        if ref.startswith('CVE') or ref.startswith('cve'):

            ret = getExploits(ref, cursor)
            if ret:
                print '[Exploits ' + vuln + ' ' + ref + ']\n'

            for tool, info in ret.iteritems():

                if not info:
                    continue
                print '[Tool] ' + tool

                for path in info:
                    print path
                print '\n'


def main(workspace='', args=None, parser=None):
    print '[*]Checking DB...'

    if not os.path.isfile(DB_PATH):
        print '[!]DB not found: please download the DB from: ' + URL_DB
        print '[!]Extract this to $FARADAY/data/ and try again!'
        raise Exception('DB not found', 'Check if DB exists')

    print '[*]DB Found!'
    print '[*]Searching exploits...\n'

    connection = sqlite3.connect(DB_PATH)
    cursor = connection.cursor()

    for host in models.get_hosts(workspace):
        for v in host.getVulns():
            print '[' + host.name + '] ' + v.name
            printExploits(v.name, v.getRefs(), cursor)

        for i in host.getAllInterfaces():
            for s in i.getAllServices():
                for v in s.getVulns():
                    print '[' + host.name + '] ' + v.name
                    printExploits(v.name, v.getRefs(), cursor)

    return 0, None
