Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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'))
def __init__(self, database=None, proxies=None, store_all_pastes=True):
"""
Basic PastePwn object handling the connection to pastebin and all the analyzers and actions
:param database: Database object extending AbstractDB
:param proxies: Dict of proxies as defined in the requests documentation
:param store_all_pastes: Bool to decide if all pastes should be stored into the db
"""
self.logger = logging.getLogger(__name__)
self.is_idle = False
self.database = database
self.paste_queue = Queue()
self.action_queue = Queue()
self.error_handlers = list()
self.onstart_handlers = list()
self.__exception_event = Event()
self.__request = Request(proxies) # initialize singleton
# Usage of ipify to get the IP - Uses the X-Forwarded-For Header which might
# lead to issues with proxies
try:
ip = self.__request.get("https://api.ipify.org")
self.logger.info("Your public IP is {0}".format(ip))
except Exception as e:
self.logger.warning("Could not fetch public IP via ipify: {0}".format(e))
self.scraping_handler = ScrapingHandler(paste_queue=self.paste_queue,
exception_event=self.__exception_event)
self.paste_dispatcher = PasteDispatcher(paste_queue=self.paste_queue,
action_queue=self.action_queue,
exception_event=self.__exception_event)
self.action_handler = ActionHandler(action_queue=self.action_queue,
exception_event=self.__exception_event)
def perform(self, paste, analyzer_name=None, matches=None):
"""Send a message via a Telegram bot to a specified user, without checking for errors"""
r = Request()
text = TemplatingEngine.fill_template(paste, analyzer_name, template_string=self.template, matches=matches)
api_url = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}".format(self.token, self.receiver, text)
r.get(api_url)
def perform(self, paste, analyzer_name=None, matches=None):
"""
Trigger the webhook
:param paste: The paste passed by the ActionHandler
:param analyzer_name: The name of the analyzer which matched the paste
:param matches: List of matches returned by the analyzer
:return: None
"""
if self.post_data is None:
paste_dict = None
else:
paste_dict = paste.to_dict()
r = Request()
r.post(url=self.url, data=paste_dict)
def _get_paste_content(self, key):
"""Downloads the content of a certain paste"""
r = Request()
endpoint = "api_scrape_item.php"
api_url = "{0}/{1}?i={2}".format(self.api_base_url, endpoint, key)
self.logger.debug("Downloading paste {0}".format(key))
try:
response_data = r.get(api_url)
except Exception as e:
self.logger.error(e)
raise e
self._check_error(response_data, key)
return response_data
def _get_recent(self, limit=100):
"""Downloads a list of the most recent pastes - the amount is limited by the parameter"""
r = Request()
endpoint = "api_scraping.php"
api_url = "{0}/{1}?limit={2}".format(self.api_base_url, endpoint, limit)
try:
response_data = r.get(api_url)
self._check_error(response_data)
pastes_dict = json.loads(response_data)
pastes = []
# Loop through the response and create objects by the data
for paste in pastes_dict:
paste_obj = Paste(key=paste.get("key"),
title=paste.get("title"),
user=paste.get("user"),
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
def perform(self, paste, analyzer_name=None, matches=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})