Beispiel #1
0
    def perform(self, paste, analyzer_name=None):
        """Send a message via Discord to a specified channel, without checking for errors"""
        r = Request()
        if self.template is None:
            text = "New paste matched by analyzer '{0}' - Link: {1}".format(
                analyzer_name, paste.full_url)
        else:
            paste_dict = paste.to_dict()
            paste_dict["analyzer_name"] = analyzer_name
            text = self.template.safe_substitute(DictWrapper(paste_dict))

        if self.webhook is not None:
            # Send to a webhook (no authentication)
            url = self.webhook
        else:
            # Send through Discord bot API (header-based authentication)
            url = 'https://discordapp.com/api/channels/{0}/messages'.format(
                self.channel_id)
            r.headers = {'Authorization': 'Bot {}'.format(self.token)}

        res = r.post(url, {"content": text})
        if res == "":
            # If the response is empty, skip further execution
            return

        res = json.loads(res)

        if res.get(
                'code'
        ) == 40001 and self.bot_available and self.webhook is None and not self.identified:
            # Unauthorized access, bot token hasn't been identified to Discord Gateway
            self.logger.info('Accessing Discord Gateway to initialize token')
            self.initialize_gateway()
            # Retry action
            self.perform(paste, analyzer_name=analyzer_name)
Beispiel #2
0
    def perform(self, paste, analyzer_name=None, matches=None):
        """Send a message via Discord to a specified channel, without checking for errors"""
        r = Request()
        text = TemplatingEngine.fill_template(paste,
                                              analyzer_name,
                                              template_string=self.template,
                                              matches=matches)

        if self.webhook_url is not None:
            # Send to a webhook (no authentication)
            url = self.webhook_url
        else:
            # Send through Discord bot API (header-based authentication)
            url = 'https://discordapp.com/api/channels/{0}/messages'.format(
                self.channel_id)
            r.headers = {'Authorization': 'Bot {}'.format(self.token)}

        res = r.post(url, {"content": text})
        if res == "":
            # If the response is empty, skip further execution
            return

        res = json.loads(res)

        if res.get(
                'code'
        ) == 40001 and self.bot_available and self.webhook_url is None and not self.identified:
            # Unauthorized access, bot token hasn't been identified to Discord Gateway
            self.logger.info('Accessing Discord Gateway to initialize token')
            self.initialize_gateway()
            # Retry action
            self.perform(paste, analyzer_name=analyzer_name)
Beispiel #3
0
 def perform(self, paste, analyzer_name=None, matches=None):
     """
     Sends the event to the MISP instance.
     :param paste: The paste passed by the ActionHandler
     :param analyzer_name: The name of the analyzer which matched the paste
     """
     # Call transformer to construct payload
     event = self.transformer(paste, analyzer_name)
     if self.attributes:
         # Add extra attributes
         event['Attributes'].extend(self.attributes)
     data = json.dumps({"Event": event})
     # Send event to MISP instance
     r = Request()
     r.headers = {
         'Authorization': self.access_key,
         'Accept': 'application/json',
         'Content-Type': 'application/json'
     }
     res = r.post(self.url + "/events", data=data)
     # Error handling
     if not res:
         self.logger.warning("Empty response when adding event")
     else:
         res = json.loads(res)
         if 'Event' in res:
             self.logger.info('Event #%s successfully added to MISP',
                              res['Event']['id'])
         else:
             # An error has happened, but the 'errors' field is not always present
             if 'errors' in res:
                 self.logger.error('Error when adding event: %s',
                                   res['errors'])
             self.logger.warning('Failed to add event: %s',
                                 res.get('message'))
Beispiel #4
0
    def initialize_gateway(self):
        """Initialize the bot token so Discord identifies it properly."""
        if self.webhook is not None:
            raise NotImplementedError(
                'Gateway initialization is only necessary for bot accounts.')

        # Call Get Gateway Bot to get the websocket URL
        r = Request()
        r.headers = {'Authorization': 'Bot {}'.format(self.token)}
        res = json.loads(r.get('https://discordapp.com/api/gateway/bot'))
        ws_url = res.get('url')

        # Start websocket client
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(self._identify(ws_url))
        self.identified = True
Beispiel #5
0
    def perform(self, paste, analyzer_name=None, matches=None):
        """
        Sends the event to the MISP instance.
        :param paste: The paste passed by the ActionHandler
        :param analyzer_name: The name of the analyzer which matched the paste
        """
        # Call transformer to construct payload
        event = self.transformer(paste, analyzer_name)
        if self.attributes:
            # Add extra attributes
            event["Attributes"].extend(self.attributes)
        data = json.dumps({"Event": event})
        # Send event to MISP instance
        r = Request()
        r.headers = {
            "Authorization": self.access_key,
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        events_url = "{0}/events".format(self.url)
        res = r.post(events_url, data=data)

        # Error handling
        if not res:
            self.logger.warning("Empty response when adding event")
            return

        res = json.loads(res)
        if "Event" in res:
            event = res.get("Event")
            self.logger.info("Event #%s successfully added to MISP",
                             event.get("id"))
            return
        # An error has happened, but the 'errors' field is not always present
        if "errors" in res:
            self.logger.error("Error when adding event: %s", res.get("errors"))
        self.logger.warning("Failed to add event: %s", res.get("message"))