Skip to content

Instantly share code, notes, and snippets.

@herrcore
Last active August 9, 2019 02:37
Show Gist options
  • Save herrcore/c762555ea9a9e274c4ca58820a6d7212 to your computer and use it in GitHub Desktop.
Save herrcore/c762555ea9a9e274c4ca58820a6d7212 to your computer and use it in GitHub Desktop.
Slackify your Koodous alerts!!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################################
# Kalert provides a simple Slack alert integration for the amazing Koodous
# platform: https://koodous.com/
#
# Simply add your TOKEN and your SLACK url to the script and setup
# a cronjob to run the script ever 5min or whatever you want.
#
# Example:
# */5 * * * * python Kalert.py
#
# You must first register for API access: https://koodous.com/register
#
# You must also supply a Slack WebHook URL: https://api.slack.com/incoming-webhooks
#
# I'm lazy so we only return the first page (14) notifications. Unless you are
# getting more than 14 notificaitons a minute you should be fine.
#
# NOTE: your alerts will be marked as READ when they are shown in Slack
#
# WARNING! Ksearch uses undocumented APIs that may break at any point!
#
# DOUBLE WARNING!! The Ksearch author is _not_ affiliated with Koodous!!
#
# TRIPLE WARNING!!! Use at your own risk, responsibility is 100% yours!!!
#
#######################################################################
__author__ = '@herrcore'
__version__ = 0.1
import json
import urllib
import urllib2
import urlparse
import hashlib
import argparse
import time
import sys
import os
import hashlib
import time
#silly slack imports
try:
from urllib.parse import urljoin
from urllib.parse import urlencode
import urllib.request as urlrequest
except ImportError:
from urlparse import urljoin
from urllib import urlencode
import urllib2 as urlrequest
try:
import requests
except ImportError:
print "ERROR: You must have the requests installed in your path. For installation see here: http://docs.python-requests.org/en/master/user/install/#install"
class Slack():
SLACK_URL = '**** ADD YOUR SLACK URL HERE ****'
def __init__(self, url=None):
if url != None:
self.SLACK_URL = url
self.opener = urlrequest.build_opener(urlrequest.HTTPHandler())
def notify(self, **kwargs):
"""
Send message to slack API
"""
return self.send(kwargs)
def send(self, payload):
"""
Send payload to slack API
"""
payload_json = json.dumps(payload)
data = urlencode({"payload": payload_json})
req = urlrequest.Request(self.SLACK_URL)
response = self.opener.open(req, data.encode('utf-8')).read()
return response.decode('utf-8')
def send_alert(self, message):
"""
Send a Koodous Alert message to Slack
"""
body = "Koodous Alert:\n%s\n" % message
self.notify(text=body)
class Kalert:
"""
Slackify your Koodous alerts!!
WARNING: relies on undocumented APIs
"""
TOKEN = '!!!!! ADD YOUR TOKEN HERE !!!!!'
API_URL = 'https://koodous.com/api/%s%s%s'
def __init__(self, token=None, slack_url=None):
"""
token: Koodous token
slack_url: Slack WebHook url
"""
if token is not None:
self.TOKEN = token
if slack_url is not None:
self.slack = Slack(url=slack_url)
else:
self.slack = Slack()
self.headers = {'Authorization': 'Token %s' % self.TOKEN}
def read_notification(self, notification_id):
"""
Mark notification as read in Koodous
WARNING: relies on undocumented API
"""
url = self.API_URL % ('notifications/', notification_id, '')
payload = {"read":True}
response = requests.patch(url=url, headers=self.headers, data=payload)
return response
def get_notifications(self):
"""
Slackify your notifications and mark them as read
WARNING: relies on undocumented API
"""
url = self.API_URL % ('notifications', '', '?cursor=&read=False')
r = requests.get(url=url, headers=self.headers)
message = ''
if r.status_code == 200:
for result in r.json().get("results"):
#mark notificaiton as read
n = self.read_notification(result['id'])
#add notificaiton to Slack message body
if result['type'] == 'ruleset':
message += "Rule Hit: " + str(result.get("ruleset")['name']) + " APK: " + str(result.get("apk")['package_name']) + "\n"
elif result['type'] == 'analysis':
message += "Analysis of APK: " + str(result.get("apk")['package_name'])+ "\n"
else:
message += "Unknown: " + result['type']+ "\n"
#only Slack if there is a messag to send
if message != '':
self.slack.send_alert(message)
def main():
parser = argparse.ArgumentParser(description='Slackify your Koodous alerts! Run this as a cronjob every 5min or however often you want.')
parser.add_argument('--key',dest="api_key",default=None,help="Specify Koodous API key. Default is the hardcoded TOKEN in ksearch Class.")
parser.add_argument('--url',dest="slack_url",default=None,help="Specify Slack url.")
args = parser.parse_args()
if args.api_key != None:
if args.slack_url != None:
kalert = Kalert(token=args.api_key, slack_url=args.slack_url)
else:
kalert = Kalert(token=args.api_key)
else:
kalert = Kalert()
kalert.get_notifications()
if __name__ == '__main__':
main()
@herrcore
Copy link
Author

Slackify All The Koodous!

Example cronjob:
*/5 * * * * python kalert.py --key <your_koodous_token> --url https://hooks.slack.com/services/<blah_blah>

The Result (add a nice Koodous icon to your Slack WebHook for extra bling):
the_future

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment