Skip to content
Snippets Groups Projects
warden3-kippo-sender.py 4.19 KiB
Newer Older
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011-2015 Cesnet z.s.p.o
# Use of this source is governed by a 3-clause BSD-style license, see LICENSE file.

from warden_client import Client, Error, read_cfg
import json
import string
from time import time, gmtime
from math import trunc
from uuid import uuid4
# from pprint import pprint
from os import path
# from random import randint, randrange, choice, random;
# from base64 import b64encode;

import MySQLdb as my
import MySQLdb.cursors as mycursors

def get_precise_timestamp(epoch=None):
    t = epoch if epoch else time()
    us = trunc((t-trunc(t))*1000000)
    g = gmtime(t)
    iso = '%04d-%02d-%02dT%02d:%02d:%02d.%0dZ' % (g[0:6]+(us,))
    return iso

def gen_event_idea(client_name, detect_time, win_start_time, win_end_time, conn_count, src_ip4, dst_ip4):

  event = {
     "Format": "IDEA0",
     "ID": str(uuid4()),
     # "CreateTime": get_precise_timestamp(),
     "DetectTime": detect_time,
     "WinStartTime": win_start_time,
     "WinEndTime": win_end_time,
     # "EventTime": get_precise_timestamp(),
     # "CeaseTime": get_precise_timestamp(),
     "Category": ["Attempt.Login", "Test"],
     # "Ref": ["cve:CVE-%s-%s" % (randstr(string.digits, 4), randstr()), "http://www.example.com/%s" % randstr()],
     # "Confidence": random(),
     "Note": "SSH login attempt",
     "ConnCount": conn_count,
#       "ConnCount": choice([randint(0, 65535), "asdf"]),    # Send wrong event sometimes
     "Source": [
        {
           # "Type": ["Phishing"],
           "IP4": [src_ip4],
           # "IP6": [randip6() for i in range(randrange(1, 5))],
           # "Hostname": ["example.com"],
           # "Port": [src_ip4_port],
           # "AttachHand": ["att1"],
           # "Netname": ["arin:TEST-NET-1"]
        }
     ],
     "Target": [
        {
           "IP4": [dst_ip4],
           # "IP6": [randip6() for i in range(randrange(1, 5))],
           # "URL": ["http://example.com/%s" % randstr()],
           "Proto": ["tcp", "ssh"],
           "Port" : [22]
           # "Netname": ["arin:TEST-NET-1"]
        }
     ],
     # "Attach": [
     #    {
     #       "Handle": "att1",
     #       "FileName": [randstr()],
     #       "Type": ["Malware"],
     #       "ContentType": "application/octet-stream",
     #       "Hash": ["sha1:%s" % randstr(string.hexdigits, 24)],
     #       "Size": 46,
     #       "Ref": ["cve:CVE-%s-%s" % (randstr(string.digits, 4), randstr())],
     #       "ContentEncoding": "base64",
     #       "Content": b64encode(randstr())
     #    }
     # ],
     "Node": [
        {
           "Name": client_name,
           "Tags": ["Connection","Honeypot","Recon"],
           "SW": ["Kippo"],
           "AggrWin": "00:05:00"
        }
     ]
  }

  return event

def main():
    wclient = Client(**read_cfg("warden_client.cfg"))
    appconf = read_cfg("warden_client-kippo.cfg")

    con = my.connect( host=appconf['dbhost'], user=appconf['dbuser'], passwd=appconf['dbpass'],
                      db=appconf['dbname'], port=appconf['dbport'], cursorclass=mycursors.DictCursor)
    
    crs = con.cursor()

    events = []
    query = ["SELECT UNIX_TIMESTAMP(s.starttime) as starttime, s.ip, COUNT(s.id) as attack_scale \
              FROM sessions s \
              LEFT JOIN input i ON s.id = i.session \
              WHERE s.starttime > DATE_SUB(UTC_TIMESTAMP(), INTERVAL + %s MINUTE) \
              GROUP BY s.ip ORDER BY s.starttime ASC;"]


    # crs.execute("".join(query), [appconf['a_win']])
    crs.execute("".join(query), [5])
    rows = crs.fetchall()
    for row in rows:
      dtime = get_precise_timestamp(row['starttime'])
      etime = get_precise_timestamp(time())
      stime = get_precise_timestamp(time() - appconf['a_win'] * 60)
      events.append(gen_event_idea(client_name=appconf['name'], detect_time = dtime, win_start_time = stime, win_end_time = etime, conn_count = row['attack_scale'], src_ip4 = row['ip'], dst_ip4 = appconf['sensor_ip4']))
        
    print "=== Sending ==="
    start = time()
    ret = wclient.sendEvents(events)
    if not ret:
        print "%d event(s) successfully delivered." % len(rows)
    else:
        print ret

    print "Time: %f" % (time()-start)



if __name__ == "__main__":
    main()