# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:         sfp_malwarepatrol
# Purpose:      SpiderFoot plug-in to search MalwarePatrol's daatabase for
#               potential malicious IPs/hostnames.
#
# Author:      Steve Micallef <steve@binarypool.com>
#
# Created:     25/07/2016
# Copyright:   (c) Steve Micallef 2016
# Licence:     GPL
# -------------------------------------------------------------------------------

import json
from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent


class sfp_malwarepatrol(SpiderFootPlugin):
    """MalwarePatrol:Investigate,Passive:Blacklists:apikey:Searches malwarepatrol.net's database of malicious URLs/IPs."""

    # Default options
    opts = {
        "apikey": ""
    }
    optdescs = {
        "apikey": "malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed."
    }
    results = dict()
    errorState = False

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = dict()

        for opt in userOpts.keys():
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["INTERNET_NAME", "IP_ADDRESS",
                "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
                "CO_HOSTED_SITE"]

    # What events this module produces
    # This is to support the end user in selecting modules based on events
    # produced.
    def producedEvents(self):
        return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
                "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",
                "MALICIOUS_COHOST"]

    def queryAddr(self, qaddr):
        data = dict()
        url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \
              self.opts['apikey'] + "&product=8&list=smoothwall"

        data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)
        if data['content'] is None:
            data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])
            if data['content'] is None:
                self.sf.error("Unable to fetch " + url, False)
                return None
            else:
                self.sf.cachePut("sfmalwarepatrol", data['content'])

        for line in data['content'].split('\n'):
            if len(line) < 2 or line.startswith('#'):
                continue

            if line.startswith(qaddr):
                return True

        return False

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)

        if not self.opts['apikey']:
            self.sf.error("You enabled sfp_malwarepatrol but did not provide an receipt ID!", False)
            self.errorState = True
            return None

        # Don't look up stuff twice
        if eventData in self.results:
            self.sf.debug("Skipping " + eventData + " as already searched.")
            return None
        else:
            self.results[eventData] = True

        evtType = ""
        if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:
            if eventName == 'IP_ADDRESS':
                evtType = 'MALICIOUS_IPADDR'
            else:
                evtType = 'MALICIOUS_AFFILIATE_IPADDR'

        if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',
                         'AFFILIATE_INTERNET_NAME' ]:
            if eventName == "INTERNET_NAME":
                evtType = "MALICIOUS_INTERNET_NAME"
            if eventName == 'AFFILIATE_INTERNET_NAME':
                evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'
            if eventName == 'CO_HOSTED_SITE':
                evtType = 'MALICIOUS_COHOST'

        if self.queryAddr(eventData):
            evt = SpiderFootEvent(evtType, eventData, self.__name__, event)
            self.notifyListeners(evt)

# End of sfp_malwarepatrol class
