# -*- 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
# -------------------------------------------------------------------------------

from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent


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

    meta = {
		'name': "MalwarePatrol",
		'summary': "Searches malwarepatrol.net's database of malicious URLs/IPs.",
		'flags': [ "apikey" ],
		'useCases': [ "Investigate", "Passive" ],
		'categories': [ "Reputation Systems" ],
        'dataSource': {
            'website': "https://www.malwarepatrol.net/",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://www.malwarepatrol.net/tech-support/",
                "https://www.malwarepatrol.net/integrations-formats-tip-siem-soar/",
                "https://www.malwarepatrol.net/community-contribution-suspicious-emails/",
                "https://www.malwarepatrol.net/non-commercial/#lists"
            ],
            'apiKeyInstructions': [
                "Visit www.malwarepatrol.net/free-guard-block-list/",
                "Register a free account",
                "The Password/Receipt number will be mailed to your email"
            ],
            'favIcon': "https://www.malwarepatrol.net/wp-content/uploads/2020/02/rsz_12logo-150x150.png",
            'logo': "https://www.malwarepatrol.net/wp-content/uploads/2016/06/rsz_mp_logo_clear_-_small.png",
            'description': "Based in the USA and Brazil, our history is one of community spirit and dedication to "
                                "Internet security that began in 2005 when a group started sharing malicious links using a simple mailing list.\n"
                                "Collecting, analyzing, and sharing data for over a decade has allowed us "
                                "to develop an extensive network of sensors, sharing agreements, and community contributors. "
                                "The result is our vast database of unique and historically rich – “intelligent” – threat data.\n",
        }
	}

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

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

        for opt in list(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['api_key'] + "&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, %s, from %s" % (eventName, srcModuleName))

        if not self.opts['api_key']:
            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, "MalwarePatrol [" + eventData + "]", self.__name__, event)
            self.notifyListeners(evt)

# End of sfp_malwarepatrol class

@@ -737,18 +737,24 @@
 eta = %7B%0A
-%09%09
+        
 'name': 
@@ -770,18 +770,24 @@
 atrol%22,%0A
-%09%09
+        
 'summary
@@ -853,18 +853,24 @@
 /IPs.%22,%0A
-%09%09
+        
 'flags':
@@ -884,18 +884,24 @@
 key%22 %5D,%0A
-%09%09
+        
 'useCase
@@ -938,10 +938,16 @@
  %5D,%0A
-%09%09
+        
 'cat
@@ -2556,9 +2556,12 @@
   %7D%0A
-%09
+    
 %7D%0A%0A 

Update sfp_malwarepatrol.py