Skip to main content
Sign in
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
  • devel
  • hruska-feature-clients-api
  • malostik-#5066-deduplicate-idea-ids
  • warden-postgresql-port
  • hruska-feature-#6799-filter-keys
  • hruska-feature-5066-duplicateIdeaID
  • warden-client-1.1.0
  • warden-client-1.2.0
  • warden-client-2.0
  • warden-client-2.0.0-beta1
  • warden-client-2.0.0-beta2
  • warden-client-2.1
  • warden-client-2.1-beta
  • warden-client-2.2
  • warden-client-2.2-final
  • warden-client-3.0-beta0
  • warden-client-3.0-beta1
  • warden-client-3.0-beta2
  • warden-client-3.0-beta3
  • warden-server-0.1.0
  • warden-server-2.0
  • warden-server-2.0.0-beta1
  • warden-server-2.1
  • warden-server-2.1-aplha1
  • warden-server-2.1-beta1
  • warden-server-2.1-beta2
  • warden-server-2.1-beta3
  • warden-server-2.1-beta4
  • warden-server-2.1-beta5
  • warden-server-2.1-beta6
  • warden-server-2.1-patch1
  • warden-server-2.2
  • warden-server-2.2-final
  • warden-server-2.2-patch1
  • warden-server-2.2-patch3
  • warden-server-3.0-beta0
  • warden-server-3.0-beta1
  • warden-server-3.0-beta2
  • warden-server-3.0-beta3
40 results

Target

Select target project
  • Pavel Valach / Warden-archive
1 result
Select Git revision
  • master
  • devel
  • hruska-feature-clients-api
  • malostik-#5066-deduplicate-idea-ids
  • warden-postgresql-port
  • hruska-feature-#6799-filter-keys
  • hruska-feature-5066-duplicateIdeaID
  • warden-client-1.1.0
  • warden-client-1.2.0
  • warden-client-2.0
  • warden-client-2.0.0-beta1
  • warden-client-2.0.0-beta2
  • warden-client-2.1
  • warden-client-2.1-beta
  • warden-client-2.2
  • warden-client-2.2-final
  • warden-client-3.0-beta0
  • warden-client-3.0-beta1
  • warden-client-3.0-beta2
  • warden-client-3.0-beta3
  • warden-server-0.1.0
  • warden-server-2.0
  • warden-server-2.0.0-beta1
  • warden-server-2.1
  • warden-server-2.1-aplha1
  • warden-server-2.1-beta1
  • warden-server-2.1-beta2
  • warden-server-2.1-beta3
  • warden-server-2.1-beta4
  • warden-server-2.1-beta5
  • warden-server-2.1-beta6
  • warden-server-2.1-patch1
  • warden-server-2.2
  • warden-server-2.2-final
  • warden-server-2.2-patch1
  • warden-server-2.2-patch3
  • warden-server-3.0-beta0
  • warden-server-3.0-beta1
  • warden-server-3.0-beta2
  • warden-server-3.0-beta3
40 results
Show changes

Commits on Source 557

457 additional commits have been omitted to prevent performance issues.
794 files
+ 14592
136843
Compare changes
  • Side-by-side
  • Inline

Files

.gitignore

0 → 100644
+24 −0
Original line number Original line Diff line number Diff line
# Python related
*~
*.py[cod]
*.egg-info
__pycache__

# Safety net
*.log
*.pem
*.cert
*.key
*.gpg
*.tmp

# Archives
*.tar
*.gz
*.bz2
*.xz
*.tgz
*.tbz2
*.txz
*.rpm
*.deb
+11 −0
Original line number Original line Diff line number Diff line
---
server_admin: "{{ root@inventory_hostname }}"
warden_filer_bin_path: /opt/warden-filer
warden_filer_lib_path: /var/lib/warden_filer
warden_filer_run_path: /run/warden_filer
warden_client_cert_path: /etc/ssl/certs/warden.cert.pem
warden_client_key_path: /etc/ssl/private/warden.key.pem
warden_client_id_store: /var/lib/warden_filer/warden_filer.id
warden_filer_pid_file: /run/warden_filer/receiver.pid
warden_filer_uid: 1
warden_filer_gid: 1
 No newline at end of file
+63 −0
Original line number Original line Diff line number Diff line
---
- name: Checkout Warden repository
  git:
    repo: https://gitlab.cesnet.cz/713/warden/warden.git
    version: warden-client-3.0-beta3
    dest: /tmp/warden_client_repository

- name: Create bin dir for warden_filer
  file:
    path: "{{ warden_filer_bin_path }}"
    state: directory
    owner: root
    group: root
    mode: "755"

- name: Create lib and run dir for warden_filer
  file:
    path: "{{ item }}"
    state: directory
    owner: "{{ warden_filer_uid }}"
    group: "{{ warden_filer_gid }}"
    mode: "755"
  with_items: 
    - "{{ warden_filer_lib_path }}"
    - "{{ warden_filer_run_path }}"

- name: Install Filer binaries
  copy:
    remote_src: true
    src: "/tmp/warden_client_repository/{{ item.src }}"
    dest: "{{ warden_filer_bin_path }}/{{ item.dest }}"
    mode: "755"
  with_items:
    - src: warden_client/warden_client.py
      dest: warden_client.py
    - src: warden_filer/warden_filer.py
      dest: warden_filer.py
    - src: warden_filer/check_file_count
      dest: check_file_count

- name: Link Filer binary to /usr/local/bin
  file:
    src: "{{ warden_filer_bin_path }}/warden_filer.py"
    dest: "/usr/local/bin/warden_filer.py"
    state: link
    owner: root
    group: root
    mode: "755"

- name: Install Warden Filer config
  template:
    src: "{{ item }}"
    dest: "/{{ item }}"
  with_items:
    - etc/warden_filer.cfg
    - etc/default/warden_filer_receiver

- name: Install Warden Filer init script
  copy:
    remote_src: true
    src: /tmp/warden_client_repository/warden_filer/warden_filer_receiver
    dest: /etc/init.d/warden_filer_receiver
    mode: "755"
+1 −0
Original line number Original line Diff line number Diff line
PYTHONPATH={{ warden_filer_bin_path }}
+23 −0
Original line number Original line Diff line number Diff line
{
    // Warden config can be also referenced as:
    // "warden": "/path/to/warden_client.cfg"
    "warden": {
        "url": "{{ warden_server_url | mandatory }}",
        "keyfile": "{{ warden_client_key_path }}",
        "certfile": "{{ warden_client_cert_path }}",
        "timeout": 30,
        "send_events_limit": 1000,
        "get_events_limit": 1000,
        "syslog": {"level": "debug", "facility": "local7"},
        "idstore": "{{ warden_client_id_store }}",
        "name": "{{ warden_client_name | mandatory }}"
    },
    "receiver": {
        "dir": "{{ warden_filer_output_dir | mandatory }}",
        "pid_file": "{{ warden_filer_pid_file }}",
        "uid": {{ warden_filer_uid }},
        "gid": {{ warden_filer_gid }},
        "file_limit": 10000,
        "limit_wait_time": 20
    }
}
+21 −0
Original line number Original line Diff line number Diff line
---
server_admin: "{{ root@inventory_hostname }}"

warden_server_hostname: "{{ inventory_hostname }}"
warden_server_virtual_host: "{{ ansible_default_ipv4 }}:443 {{ ansible_default_ipv6 }}:443"

warden_server_dir_path: /opt/warden-server
warden_ra_dir_path: /opt/warden-ra

warden_db_name: warden3
warden_db_user: warden

warden_ra_ejbca_url: https://ejbca.cesnet-ca.cz:8443/ejbca/ejbcaws/ejbcaws?wsdl
warden_ra_cert: /etc/ssl/certs/warden_ra.cert.pem
warden_ra_key: /etc/ssl/private/warden_ra.key.pem
warden_ra_ca_name: "Warden CA"
warden_ra_ejbca_certificate_profile: "Warden"
warden_ra_ejbca_end_entity_profile: "Warden EE"
warden_ra_subject_dn_template: "DC=test,DC=snakeoil,DC=warden,CN=%s"
warden_ra_ejbca_username_suffix: "@warden"
+82 −0
Original line number Original line Diff line number Diff line
---
- name: Checkout Warden repository
  git:
    repo: https://gitlab.cesnet.cz/713/warden/warden.git
    version: warden-server-3.0-beta3
    dest: /tmp/warden_server_repository

- name: Populate Warden server directory
  copy:
    src: "/tmp/warden_server_repository/warden_server"
    dest: "{{ warden_server_dir_path }}"

- name: Populate Warden RA directory
  copy:
    src: "/tmp/warden_server_repository/warden_ra"
    dest: "{{ warden_ra_dir_path }}"
  
- name: Install Warden server config
  template:
    src: opt/warden-server/warden_server.cfg
    dest: "{{ warden_server_dir_path }}/warden_server.cfg"

- name: Install Warden RA config
  template:
    src: opt/warden-ra/warden_ra.cfg
    dest: "{{ warden_ra_dir_path }}/warden_ra.cfg"

- name: Ensure PyMySQL module
  apt:
    pkg: python-mysqldb
    state: present

- name: Check whether Warden database already exists
  command: |
    mysql
      --batch --skip-column-names
      --user="{{ warden_db_user }}" --password="{{ warden_db_password | mandatory }}"
      "{{ warden_db_name }}"
      --execute "SELECT 1;"
  register: warden_db_exists
  changed_when: False

- name: Create Warden database
  mysql_db:
    name: "{{ warden_db_name }}"
    state: present

- name: Create Warden database user
  mysql_user:
    name: "{{ warden_db_user }}"
    password: "{{ warden_db_password | mandatory }}"
    priv: "{{ warden_db_name }}.*:ALL"
    state: present

- name: Prepare initial Warden tables and fixtures
  mysql_db:
    name: "{{ warden_db_name }}"
    login_user: "{{ warden_db_user }}"
    login_password: "{{ warden_db_password | mandatory }}"
    state: import
    target: "{{ warden_server_dir_path }}/warden_3.0.sql"
  # Import is not idempotent, so run it only when db does not exist
  when: "warden_db_exists is defined and warden_db_exists.rc != 0 and warden_db_exists.stderr.find('ERROR 1049')"

- name: Install https config
  template:
    src: "etc/apache2/sites-available/warden.conf"
    dest: "/etc/apache2/sites-available/warden.conf"
    validate: "{{ ansible_apache_include_check.dest }} sites-enabled/ %s"
  notify: Reload Apache

- name: Activate http/s config
  command: a2ensite warden
  args:
    creates: /etc/apache2/sites-enabled/warden.conf
  notify: Reload Apache

- name: Deactivate default site
  command: a2dissite default-ssl
  args:
    removes: /etc/apache2/sites-enabled/default-ssl.conf
  notify: Reload Apache
+40 −0
Original line number Original line Diff line number Diff line
<VirtualHost {{ warden_server_virtual_host }} >
    ServerAdmin {{ server_admin }}
    DocumentRoot /var/www

    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>

    ServerName {{ warden_server_hostname }}

    ErrorLog /var/log/apache2/ssl_error_warden3.log
    CustomLog /var/log/apache2/ssl_access_warden3.log common

    SSLEngine on

    SSLVerifyClient optional
    SSLVerifyDepth 4
    SSLOptions +StdEnvVars +ExportCertData

    SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On

    SSLCertificateFile      /etc/ssl/certs/cert.pem
    SSLCertificateKeyFile   /etc/ssl/certs/key.pem
    SSLCACertificateFile    /etc/ssl/certs/root_cert_chain.pem

    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    WSGIScriptAlias /warden3 {{ warden_server_dir_path }}/warden_server.wsgi
    <Directory /opt/warden-server/warden_server.wsgi>
        Require all granted
    </Directory>

    WSGIScriptAlias /warden-ra {{ warden_ra_dir_path }}/warden_ra.wsgi
    <Directory /opt/warden-ra/warden_ra.wsgi>
        Require all granted
    </Directory>
</VirtualHost>
+18 −0
Original line number Original line Diff line number Diff line
{
    "Log": {
        "type": "SysLogger",
        "facility": "local6",
        "level": "debug"
    },
    "Registry": {
        "type": "EjbcaRegistry",
        "url": "{{ warden_ra_ejbca_url }}
        "cert": "{{ warden_ra_cert }}",
        "key": "{{ warden_ra_key }}",
        "ca_name": "{{ warden_ra_ca_name }}",
        "certificate_profile_name": "{{ warden_ra_ejbca_certificate_profile }}",
        "end_entity_profile_name": "{{ warden_ra_ejbca_end_entity_profile }}",
        "subject_dn_template": "{{ warden_ra_subject_dn_template }}",
        "username_suffix": "{{ warden_ra_ejbca_username_suffix }}"
    }
}
+20 −0
Original line number Original line Diff line number Diff line
{
    "Log": {
        "type": "SysLogger",
	"facility": "local7",
        "level": "debug"
    },
    "Auth": {
        "type": "X509MixMatchAuthenticator"
    },
    "Handler": {
        "send_events_limit": 1000,
        "get_events_limit": 1000,
        "description": "Warden 3 Server"
    },
    "DB": {
        "user": "warden",
        "password": "{{ warden_db_password }}",
        "dbname": "{{ warden_db_user }}"
    }
}
+4647 −0

File added.

File size exceeds preview limit.

+119 −0
Original line number Original line Diff line number Diff line
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  banner.py
#
#  Copyright 2015 CESNET z. s. p. o.
#  Author Jakub Cegan cegan@ics.muni.cz
#
#


def main(args):

    SVGNS = "http://www.w3.org/2000/svg"

    # We set up path and names
    banner_path = "/var/www/banner/"
    banner_name_cz = "banner-cz.svg"
    banner_name_en = "banner-en.svg"
    template_name  = "banner-template.svg"

    banners = [{'name': banner_name_en, 'database' : "Database Size:", 'events' : "Number of Events:", 'senders' : "Number of Senders:", 'receivers' : "Number of Receivers:", 'created' : "Banner Created:"}, {'name': banner_name_cz, 'database' : "Velikost databáze:", 'events' : "Suma všech událostí:", 'senders' : "Odesílající klienti:", 'receivers' : "Přijímající klienti:", 'created' : "Banner vytvořen:"}]

    # We have DB credentials
    host, database, user, password = sys.argv[1:]

    db = MySQLdb.connect(host = host, user = user, passwd = password, db = database)
    cursor = db.cursor()

    cursor.execute('SELECT count(*) AS reader_count FROM clients WHERE clients.read <> 0 AND clients.valid <> 0 AND clients.test = 0;')
    row = cursor.fetchone()
    receivers = str(row[0])
    #receivers = str(random.randint(0,100))

    cursor.execute('SELECT count(*) AS writer_count FROM clients WHERE clients.write <> 0 AND clients.valid <> 0 AND clients.test = 0;')
    row = cursor.fetchone()
    senders = str(row[0])
    #senders = str(random.randint(0,100))

    cursor.execute('SELECT sum(round(((data_length + index_length) / 1024 / 1024 / 1024), 2)) AS db_size FROM information_schema.tables WHERE table_schema = "warden3" AND table_name="events"')
    row = cursor.fetchone()
    database_size = str(row[0]) + ' GB'
    #database_size = str(random.randint(0,50)) + ' GB'

    cursor.execute('SELECT max(id) - min(id) AS event_count FROM events;')
    row = cursor.fetchone()
    events =  str(row[0])
    #events = str(random.randint(0,10000000))

    #cursor.execute('SELECT max(id) AS last_id FROM events;')
    #row = cursor.fetchone()
    #last_event =  str(row[0])

    time = datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S%Z")

    for banner in banners:

      xml_data = etree.parse(template_name)

      # We search for element 'text' with id='tile_text' in SVG namespace

      # Fill texts
      find_text = etree.ETXPath("//{%s}text[@id='database-text']" % (SVGNS))
      find_text(xml_data)[0].text = banner['database']
      find_text = etree.ETXPath("//{%s}text[@id='events-text']" % (SVGNS))
      find_text(xml_data)[0].text = banner['events']
      find_text = etree.ETXPath("//{%s}text[@id='senders-text']" % (SVGNS))
      find_text(xml_data)[0].text = banner['senders']
      find_text = etree.ETXPath("//{%s}text[@id='receivers-text']" % (SVGNS))
      find_text(xml_data)[0].text = banner['receivers']
      find_text = etree.ETXPath("//{%s}text[@id='latest-text']" % (SVGNS))
      find_text(xml_data)[0].text = banner['created']

      # Insert values from database
      find_text = etree.ETXPath("//{%s}text[@id='database']" % (SVGNS))
      find_text(xml_data)[0].text = database_size
      find_text = etree.ETXPath("//{%s}text[@id='events']" % (SVGNS))
      find_text(xml_data)[0].text = events
      find_text = etree.ETXPath("//{%s}text[@id='senders']" % (SVGNS))
      find_text(xml_data)[0].text = senders
      find_text = etree.ETXPath("//{%s}text[@id='receivers']" % (SVGNS))
      find_text(xml_data)[0].text = receivers
      find_text = etree.ETXPath("//{%s}text[@id='latest']" % (SVGNS))
      find_text(xml_data)[0].text = time

      # Write edited svg into file
      new_svg = etree.tostring(xml_data)
      xml_data.write(banner_path + banner['name'])

    # We will not use pygal graphs for now
    #chart = pygal.StackedLine(fill=True, style=CleanStyle, x_label_rotation=40, tooltip_border_radius=10) # Setting style here is not necessary
    #chart.title = 'Events in last 24 hours'
    #chart.x_labels = map(lambda d: d.strftime('%H:%M:%S'), reversed([base - datetime.timedelta(hours=x) for x in range(0, 24)]))
    #chart.add('Event type  A', [random.randint(0,5000) for r in xrange(24)])
    #chart.add('Event type B', [random.randint(0,5000) for r in xrange(24)])
    #chart.add('Event type C', [random.randint(0,5000) for r in xrange(24)])
    #chart.add('Other types',  [random.randint(0,5000) for r in xrange(24)])
    #chart.render_to_file('chart_hours.svg') # Save the svg to a file

    #chart = pygal.StackedLine(fill=True, style=CleanStyle, x_label_rotation=40, tooltip_border_radius=10) # Setting style here is not necessary
    #chart.title = 'Events in last month'
    #chart.x_labels = map(lambda d: d.strftime('%d. %m. %Y'), reversed([base - datetime.timedelta(days=x) for x in range(0, 31)]))
    #chart.add('Event type A', [random.randint(0,5000) for r in xrange(31)])
    #chart.add('Event type B', [random.randint(0,5000) for r in xrange(31)])
    #chart.add('Event type C', [random.randint(0,5000) for r in xrange(31)])
    #chart.add('Other types',  [random.randint(0,5000) for r in xrange(31)])
    #chart.render_to_file('chart_month.svg') # Save the svg to a file

    return 0

if __name__ == '__main__':
    import sys
    import random
    import datetime
    import MySQLdb
    from lxml import etree
    #import pygal
    #from pygal.style import CleanStyle
    sys.exit(main(sys.argv))
+14 −0
Original line number Original line Diff line number Diff line
# haas2warden

Warden connector for data of [CZ.NIC HaaS project](https://haas.nic.cz/).

It downloads daily [HaaS data dumps](https://haas.nic.cz/stats/export/),
converts them to IDEA messages and sends them to CESNET's Warden server.

It should be run from `cron` every night when data from previous day are
available (at 3:30).

The script just writes IDEA messages as files into a "filer" directory.
A _warden_filer_ daemon must be configured to pick up the messages
and send them to Warden server.
There is a systemd file which can be used to run the warden_filer.
+2 −0
Original line number Original line Diff line number Diff line
# Run every day at 03:30
30 03 * * * haas2warden python3 /data/haas2warden/haas2warden.py -p /data/haas2warden/warden_filer/ -n org.example.ext.cznic_haas -t >> /data/haas2warden/haas2warden.log 2>&1 
+139 −0
Original line number Original line Diff line number Diff line
#!/usr/bin/env python3
from gzip import decompress
from json import loads
from datetime import datetime, timedelta
import argparse
import logging
import uuid
import json
import os
import requests


data_date = datetime.date(datetime.utcnow()) - timedelta(days=1)

LOGFORMAT = "%(asctime)-15s,%(name)s [%(levelname)s] %(message)s"
LOGDATEFORMAT = "%Y-%m-%dT%H:%M:%S"
logging.basicConfig(level=logging.INFO, format=LOGFORMAT, datefmt=LOGDATEFORMAT)

logger = logging.getLogger('haas2warden')

def createIDEAFile(idea_id, idea_msg):
    """
    Creates file for IDEA message in .../tmp folder, then move it to .../incoming folder
    """
    tmp_dir_path = os.path.join(args.path, "tmp")
    idea_file_path = os.path.join(tmp_dir_path, idea_id+".idea")
    os.makedirs(tmp_dir_path, exist_ok=True)
    idea_file = open(idea_file_path, "w")
    idea_file.write(idea_msg)
    idea_file.close()

    incoming_dir_path = os.path.join(args.path, "incoming")
    incoming_file_path = os.path.join(incoming_dir_path,idea_id+".idea")
    os.makedirs(incoming_dir_path, exist_ok=True) 
    os.rename(idea_file_path,incoming_file_path)


def createIDEA(time, time_closed, ip, login_successful, commands):
    """
    Creates IDEA message 
    """ 
    idea_id = str(uuid.uuid4())

    if login_successful:
        category = "[\"Intrusion.UserCompromise\"]" 
        description = "SSH login on honeypot (HaaS)"
        if args.test:
            category = "[\"Intrusion.UserCompromise\", \"Test\"]"
        attach = f''',
   "Attach": [
        {{
            "Note": "commands",
            "Type": ["ShellCode"],
            "ContentType": "application/json",
            "Content": {json.dumps(commands)}
        }}
    ]''' #              ^-- "commands" is already serialiezed into a json string, we want to include it into a bigger JSON so we must encode it again (to escape quotes and any other special charaters)

    else:
        category = "[\"Attempt.Login\"]" 
        description = "Unsuccessful SSH login attempt on honeypot (HaaS)"
        if args.test:
            category = "[\"Attempt.Login\", \"Test\"]"
        attach = ""

    if time_closed: # sometimes time_closed is empty, in such case we must omit CeaseTime completely from IDEA msg
        cease_time = f'"CeaseTime": "{time_closed}",'
    else:
        cease_time = ""

    idea_msg = f"""\
{{
    "Format": "IDEA0",
    "ID": "{idea_id}",
    "Category": {category},
    "Description": "{description}",
    "Note": "Extracted from data of CZ.NIC HaaS project",
    "DetectTime": "{time}",
    "EventTime": "{time}",
    {cease_time}
    "CreateTime": "{datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')}",
    "Source": [
        {{
            "IP4": ["{ip}"],
            "Proto": ["tcp", "ssh"]
        }}
    ],
    "Node": [
        {{
            "Name": "{args.name}",
            "SW": ["CZ.NIC HaaS"],
            "Type": ["Connection", "Auth", "Honeypot"],
            "Note": "A script converting daily HaaS data dumps from https://haas.nic.cz/stats/export/"
        }}
    ]{attach}
}}
"""
    createIDEAFile(idea_id, idea_msg)

    
def processJSON():
    """
    Downloads data from https://haas.nic.cz/stats/export/ and process json files.
    """
    date = datetime.strptime(args.date, '%Y-%m-%d').date()
    # get url
    url = "https://haas.nic.cz/stats/export/{}/{}/{}.json.gz".format(str(date).split('-')[0],str(date).split('-')[1], str(date))
    # get data 
    logger.info("Downloading {}".format(url))
    response = requests.get(url)
    if response.status_code == 200:
        # unzip and read json file
        json_objects = loads(decompress(response.content))
        logger.info("Found {} records, converting to IDEA messages".format(len(json_objects)))
        # go through all json objects
        for json_object in json_objects:
            createIDEA(json_object["time"], json_object["time_closed"], json_object["ip"], json_object["login_successful"], json.dumps(json_object["commands"]))

if __name__ == "__main__":
    
    # parse arguments
    parser = argparse.ArgumentParser(
        prog="haas_receiver.py",
        description="A script converting daily HaaS data dumps from https://haas.nic.cz/stats/export/"
    )

    parser.add_argument('-d', '--date', metavar='DATE', default = str(data_date),
                        help='To download data from date YYYY-MM-DD, use date + 1 day (default: utcnow - 1 day)')
    parser.add_argument('-p', '--path', metavar='DIRPATH', default = "/data/haas2warden/warden_filer/",
                        help='Target folder for Idea messages (default: "/data/haas2warden/warden_filer/")')
    parser.add_argument('-n', '--name', metavar='NODENAME', default = "undefined",
                        help='Name of the node (default: undefined)')
    parser.add_argument('-t', '--test', action="store_true",
                        help='Test category')                                        

    args = parser.parse_args()
    
    processJSON()
    logger.info("Done")
+18 −0
Original line number Original line Diff line number Diff line
# Template of Systemd unit for Warden filer daemon
#
# TODO: set paths, username and mode (receiver/sender) in the last two lines
# and uncomment them. Then copy the file to:
#   /etc/systemd/system/warden-filer.service
# and run:
#   systemctl daemon-reload

[Unit]
Description=Warden filer for haas2warden
After=syslog.target network.target

[Service]
Type=forking
User=haas2warden
PIDFile=/data/haas2warden/warden_filer.pid
ExecStart=/opt/warden_filer/warden_filer.py --daemon -c "/data/haas2warden/warden_filer.cfg" --pid_file "/data/haas2warden/warden_filer.pid" sender
+21 −0
Original line number Original line Diff line number Diff line
{
    // Warden config can be also referenced as:
    // "warden": "/path/to/warden_client.cfg"
    "warden": {
        "url": "https://warden-hub.cesnet.cz/warden3",
        "cafile": "/etc/pki/tls/certs/ca-bundle.crt",
        "keyfile": "/data/haas2warden/key.pem",
        "certfile": "/data/haas2warden/cert.pem",
        "timeout": 10,
        "errlog": {"level": "warning"},
        "filelog": {"level": "info", "file": "/data/haas2warden/warden_filer.log"},
        "idstore": "/data/haas2warden/warden_filer.id",
        "name": "org.example.cznic_haas"
    },
    "sender": {
        // Maildir like directory, whose "incoming" subdir will be checked
        // for Idea events to send out
        "dir": "/data/haas2warden/warden_filer",
        "poll_time": 60
    }
}
+45 −0
Original line number Original line Diff line number Diff line
Support scripts for fail2ban
============================

Introduction
------------

Fail2ban is a logfile watcher, which is able to run various actions,
based on too many patterns occured in the log file.
Those helper shell scripts can be used as action to report events to
Warden_.

Dependencies
------------

 1. Python packages

    warden_filer 3.0+

Usage
-----

 * f2ban_spam.sh is meant to be used in cooperation with the default
   "postfix" rule.
 * f2ban_ssh.sh is meant to be used in cooperation with the default
   "ssh" rule. 

In the corresponding action following invocation can be used:

   actionban = /usr/local/bin/f2ban_XXX.sh <ip> <failures> <time>

Please, edit corresponding paths and Warden names in the corresponding
script preamble and check/edit contents of the IDEA template (e.g. Target IP 
address in f2ban_ssh.sh).

Scripts write generated Idea_ events into warden_filer compatible
directory, so you will need to run properly configured (and registered
into Warden server) warden_filer instance, which will take care for
picking up the events and submitting them.

.. _Warden: https://warden.cesnet.cz/
.. _Idea: https://idea.cesnet.cz/

------------------------------------------------------------------------------

Copyright (C) 2017 Cesnet z.s.p.o
+54 −0
Original line number Original line Diff line number Diff line
#!/bin/bash

umask 0111

filer_dir="/var/mentat/spool/_wardenout"
src_ip=$1
failures=$2
detect_time=$(date --date="@$3" --rfc-3339=seconds)
create_time=$(date --rfc-3339=seconds)
node_name="org.example.fail2ban.blacklist"

uuid() {
        for ((n=0; n<16; n++)); do  
                read -n1 c < /dev/urandom
                LC_CTYPE=C d=$(printf '%d' "'$c")
                s=''
                case $n in
                        6) ((d = d & 79 | 64));;   
                        8) ((d = d & 191 | 128));;  
                        3|5|9|7) s='-';; 
                esac
                printf '%02x%s' $d "$s"
        done
}

event_id=$(uuid)

cat >"$filer_dir/tmp/$event_id" <<EOF
{
   "Format" : "IDEA0",
   "ID" : "$event_id",
   "DetectTime" : "$detect_time",
   "CreateTime" : "$create_time",
   "Category" : ["Abusive.Spam"],
   "Description" : "Blacklisted host",
   "Note" : "Block duration: 3600. IP was blacklisted, is listed on more than 5 public blacklists",
   "Source" : [{
      "Type": ["Spam"],
      "IP4" : ["$src_ip"],
      "Proto": ["tcp", "smtp"]
   }],
   "Node" : [{
         "Name" : "$node_name",
         "SW" : ["Fail2Ban"],
         "Type" : ["Log", "Statistical"]
   }],
   "_CESNET" : {
      "Impact" : "IP was blacklisted, is listed on more than 5 public blacklists",
      "EventTemplate" : "f2b-001"
   }
}
EOF

mv "$filer_dir/tmp/$event_id" "$filer_dir/incoming"
+57 −0
Original line number Original line Diff line number Diff line
#!/bin/bash

umask 0111

filer_dir="/var/spool/warden_sender"
src_ip=$1
failures=$2
detect_time=$(date --date="@$3" --rfc-3339=seconds)
create_time=$(date --rfc-3339=seconds)
node_name="org.example.fail2ban.ssh"

uuid() {
        for ((n=0; n<16; n++)); do  
                read -n1 c < /dev/urandom
                LC_CTYPE=C d=$(printf '%d' "'$c")
                s=''
                case $n in
                        6) ((d = d & 79 | 64));;   
                        8) ((d = d & 191 | 128));;  
                        3|5|9|7) s='-';; 
                esac
                printf '%02x%s' $d "$s"
        done
}

event_id=$(uuid)

cat >"$filer_dir/tmp/$event_id" <<EOF
{
   "Format": "IDEA0",
   "ID": "$event_id",
   "DetectTime": "$detect_time",
   "CreateTime": "$create_time",
   "Category": ["Attempt.Login"],
   "Description": "SSH dictionary/bruteforce attack",
   "ConnCount": $failures,
   "Note": "IP attempted $failures logins to SSH service",
   "Source": [{
      "IP4": ["$src_ip"],
      "Proto": ["tcp", "ssh"]
   }],
   "Target": [{
       "Type": ["Anonymised"],
       "IP4": ["192.0.2.0/24"],
       "Anonymised": true,
       "Proto": ["tcp", "ssh"],
       "Port": [22]
   }],
   "Node": [{
         "Name": "$node_name",
         "SW": ["Fail2Ban"],
         "Type": ["Log", "Statistical"]
   }]
}
EOF

mv "$filer_dir/tmp/$event_id" "$filer_dir/incoming"
+1 −1
Original line number Original line Diff line number Diff line
BSD License
BSD License


Copyright © 2011-2013 Cesnet z.s.p.o
Copyright © 2011-2015 Cesnet z.s.p.o
All rights reserved.
All rights reserved.


Redistribution and use in source and binary forms, with or without modification,
Redistribution and use in source and binary forms, with or without modification,
+67 −0
Original line number Original line Diff line number Diff line
+---------------------------------------------+
| Warden Dionaea connector 0.1 for Warden 3.X |
+---------------------------------------------+

Content

  A. Introduction
  B. Dependencies
  C. Usage
  D. Configuration

------------------------------------------------------------------------------
A. Introduction

   Warden Dionaea connector (executable warden3-dio-sender.py) is a one-shot 
   script to send events from Dionaea honeypot toward the Warden server.

------------------------------------------------------------------------------
B. Dependencies

 1. Platform

    Python 2.7+

 2. Python packages

    warden_client 3.0+

------------------------------------------------------------------------------
C. Usage

   warden3-dio-sender.py 

   This script does not run as a daemon, for regularly run use job scheduler cron.

------------------------------------------------------------------------------
D. Configuration
   
   warden_client-dio.cfg
    warden - path to warden-client config, e.g. 'warden/warden_client.cfg'
    name - sensor's source id used as a source of events, e.g. 'cz.cesnet.server.dionaea'
    secret - secret to authenticate client
           - if 'secret' is non empty, is used instead of value in client's configuration
           - useful while using more sensors with single client's configuration

    anonymised - no | yes | omit
               - no (default value)
               - yes = anonymize to 'target_net' (see below)
               - omit = completely omit target field

    target_net - anonymized network used as target if 'anonymized' option is 'yes'

    dbfile - path to sqlite database file, e.g. '/opt/dionaea/var/dionaea/logsql.sqlite'
    binaries_path - path to stored malware, e.g. '/opt/dionaea/var/dionaea/binaries'
    report_binaries - 'true' if malware attachment have to be included in event, otherwise 'false'
    con_attempts - number of attempts connection to the database, it may be exclusive locked
    con_retry_interval - interval between each attempt (in seconds)
    awin - aggregation window (in minutes), e.g. 5 for events in the last 5 minutes
    
   cron
    SCRIPT_PATH=/opt/warden_client/
    */5  *   * * *  root cd $SCRIPT_PATH; python warden3-dio-sender.py > /dev/null 2>&1

    Note: Repeat interval must be the same as value of 'awin'.

------------------------------------------------------------------------------
Copyright (C) 2011-2015 Cesnet z.s.p.o
+223 −0
Original line number Original line Diff line number Diff line
#!/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, format_timestamp
import json
import string
import urllib
from time import time, gmtime, strftime, sleep
from math import trunc
from uuid import uuid4
from os import path
import base64
import sqlite3
import sys

DEFAULT_ACONFIG = 'warden_client-dio.cfg'
DEFAULT_WCONFIG = 'warden_client.cfg'
DEFAULT_BINPATH = '/opt/dionaea/var/dionaea/binaries'
DEFAULT_DBFILE  = '/opt/dionea/var/dionea/logsql.sqlite'
DEFAULT_NAME = 'org.example.warden.test'
DEFAULT_REPORT_BINARIES = 'false'
DEFAULT_AWIN = 5
DEFAULT_CON_ATTEMPTS = 3
DEFAULT_CON_RETRY_INTERVAL = 5
DEFAULT_ATTACH_NAME = 'att1'
DEFAULT_HASHTYPE = 'md5'
DEFAULT_CONTENT_TYPE = 'application/octet-stream'
DEFAULT_CONTENT_ENCODING = 'base64'
DEFAULT_ANONYMISED = 'no'
DEFAULT_TARGET_NET = '0.0.0.0/0'
DEFAULT_SECRET = ''


def gen_attach_idea(logger, report_binaries, binaries_path, filename, hashtype, hashdigest, vtpermalink, avref):
    
  refs = []
  attach = { 
         "Handle": DEFAULT_ATTACH_NAME,
         "FileName": [filename],
         "Type": ["Malware"],
         "Hash": ["%s:%s" % (hashtype, hashdigest)],
      }
  
  if vtpermalink is not None:
    refs.append('url:' + vtpermalink)
  
  if avref is not None:
    refs.extend(avref.split(';'))
  
  if refs:
    refs = [urllib.quote(ref, safe=':') for ref in refs]
    refs = list(set(refs))
    attach['Ref'] = refs

  if report_binaries == 'true':
    try:
      fpath = path.join(binaries_path, hashdigest)
      with open(fpath, "r") as f:
        fdata = f.read()
        attach['ContentType'] = DEFAULT_CONTENT_TYPE
        attach['ContentEncoding'] = DEFAULT_CONTENT_ENCODING
        attach['Size'] = len(fdata)
        attach['Content'] = base64.b64encode(fdata)
    except (IOError) as e:
      logger.info("Reading id file \"%s\" with malware failed, information will not be attached." % (fpath))

  return attach

def gen_event_idea(logger, binaries_path, report_binaries, client_name, anonymised, target_net, detect_time, win_start_time, win_end_time, aggr_win, data):

  category = []
  event = {
     "Format": "IDEA0",
     "ID": str(uuid4()),
     "DetectTime": detect_time,
     "WinStartTime": win_start_time,
     "WinEndTime": win_end_time,
     "ConnCount": data['attack_scale'],
     "Source": [{}],
     "Target": [{}],
     "Node": [
        {
           "Name": client_name,
           "Type": ["Connection","Honeypot","Recon"],
           "SW": ["Dionaea"],
           "AggrWin": strftime("%H:%M:%S", gmtime(aggr_win))
        }
     ]
  }

  # Determine IP address family
  af = "IP4" if not ':' in data['src_ip'] else "IP6"
  
  # Extract & save proto and service name
  proto = [data['proto']]

  if data['service'] in ['mysql', 'mssql']:
    proto.append(data['service'])
  elif data['service'] in ['httpd', 'smbd']:
    proto.append(data['service'][:-1])

  # Choose correct category
  if data['service'] != 'pcap':
    category.append('Attempt.Exploit')
  else:
    category.append('Recon.Scanning')

  # smbd allows save malware
  if data['service'] == 'smbd' and data['download_md5_hash'] is not None:
    category.append('Malware')
    event['Source'][0]['URL'] = [data['download_url']]
    filename = data['download_url'].split('/')[-1]

    if filename != '' and data['download_md5_hash'] != '':
      # Generate "Attach" part of IDEA
      a = gen_attach_idea(logger, report_binaries, binaries_path, filename, DEFAULT_HASHTYPE, data['download_md5_hash'], data['virustotal_permalink'], data['scan_result'])
    
      event['Source'][0]['AttachHand'] = [DEFAULT_ATTACH_NAME]
      event['Attach'] = [a]


  event['Source'][0][af]      = [data['src_ip']]
  event['Source'][0]['Port']  = [data['src_port']]

  if anonymised != 'omit':
    if anonymised == 'yes':
      event['Target'][0]['Anonymised'] = True
      event['Target'][0][af] = [target_net]
    else:
      event['Target'][0][af] = [data['dst_ip']]

  event['Target'][0]['Port']  = [data['dst_port']]
  event['Target'][0]['Proto'] = proto

  event['Category'] = category

  return event

def main():
  aconfig = read_cfg(DEFAULT_ACONFIG)
  wconfig = read_cfg(aconfig.get('warden', DEFAULT_WCONFIG))
  
  aname = aconfig.get('name', DEFAULT_NAME)
  wconfig['name'] = aname   

  asecret = aconfig.get('secret', DEFAULT_SECRET)
  if asecret:
    wconfig['secret'] = asecret
  
  wclient = Client(**wconfig)

  awin = aconfig.get('awin', DEFAULT_AWIN) * 60
  abinpath = aconfig.get('binaries_path', DEFAULT_BINPATH)
  adbfile = aconfig.get('dbfile', DEFAULT_DBFILE)
  aconattempts = aconfig.get('con_attempts', DEFAULT_CON_ATTEMPTS)
  aretryinterval = aconfig.get('con_retry_interval', DEFAULT_CON_RETRY_INTERVAL)
  areportbinaries = aconfig.get('report_binaries', DEFAULT_REPORT_BINARIES)
  
  aanonymised = aconfig.get('anonymised', DEFAULT_ANONYMISED)
  if aanonymised not in ['no', 'yes', 'omit']:
    wclient.logger.error("Configuration error: anonymised: '%s' - possible typo? use 'no', 'yes' or 'omit'" % aanonymised)
    sys.exit(2)

  atargetnet  = aconfig.get('target_net', DEFAULT_TARGET_NET)
  aanonymised = aanonymised if (atargetnet != DEFAULT_TARGET_NET) or (aanonymised == 'omit') else DEFAULT_ANONYMISED



  con = sqlite3.connect(adbfile)
  con.row_factory = sqlite3.Row
  crs = con.cursor()

  events = []
  
  query =  "SELECT c.connection_timestamp AS timestamp, c.remote_host AS src_ip, c.remote_port AS src_port, c.connection_transport AS proto, \
            c.local_host AS dst_ip, c.local_port AS dst_port, COUNT(c.connection) as attack_scale, c.connection_protocol AS service, d.download_url, d.download_md5_hash, \
            v.virustotal_permalink, GROUP_CONCAT('urn:' || vt.virustotalscan_scanner || ':' || vt.virustotalscan_result,';') AS scan_result \
            FROM connections AS c LEFT JOIN downloads AS d ON c.connection = d.connection \
            LEFT JOIN virustotals AS v ON d.download_md5_hash = v.virustotal_md5_hash \
            LEFT JOIN virustotalscans vt ON v.virustotal = vt.virustotal \
            WHERE datetime(connection_timestamp,'unixepoch') > datetime('now','-%d seconds') AND c.remote_host != '' \
            GROUP BY c.remote_host, c.local_port ORDER BY c.connection_timestamp ASC;" % (awin)

  attempts = 0
  while attempts < aconattempts:
    try:
      crs.execute(query)
      break
    except sqlite3.Error, e:
      attempts += 1
      wclient.logger.info("Info: %s - attempt %d/%d." % (e.args[0], attempts, aconattempts))
      if attempts == aconattempts:
        wclient.logger.error("Error: %s (dbfile: %s)" % (e.args[0], adbfile))

      sleep(aretryinterval)

  rows = crs.fetchall()

  if con:
    con.close

  etime = format_timestamp(time())
  stime = format_timestamp(time() - awin)

  for row in rows:
    dtime = format_timestamp(row['timestamp'])
    events.append(gen_event_idea(logger = wclient.logger, binaries_path = abinpath, report_binaries = areportbinaries, client_name = aname, anonymised = aanonymised, target_net = atargetnet, detect_time = dtime, win_start_time = stime, win_end_time = etime, aggr_win = awin, data = row))
      
  print "=== Sending ==="
  start = time()
  ret = wclient.sendEvents(events)
  
  if ret:
    wclient.logger.info("%d event(s) successfully delivered." % len(rows))

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


if __name__ == "__main__":
    main()
+15 −0
Original line number Original line Diff line number Diff line
{
    "warden": "warden_client.cfg",
    "name": "cz.cesnet.server.dionaea",
    "secret": "",

    "anonymised": "no",
    "target_net": "195.113.0.0/16",

    "dbfile": "/opt/dionaea/var/dionaea/logsql.sqlite",
    "binaries_path" : "/opt/dionaea/var/dionaea/binaries",
    "report_binaries" : "true",
    "con_attempts" : 3,
    "con_retry_interval" : 5,
    "awin": 5
}
+1 −1
Original line number Original line Diff line number Diff line
BSD License
BSD License


Copyright © 2011-2013 Cesnet z.s.p.o
Copyright © 2011-2015 Cesnet z.s.p.o
All rights reserved.
All rights reserved.


Redistribution and use in source and binary forms, with or without modification,
Redistribution and use in source and binary forms, with or without modification,
+67 −0
Original line number Original line Diff line number Diff line
+-------------------------------------------+
| Warden Kippo connector 0.1 for Warden 3.X |
+-------------------------------------------+

Content

  A. Introduction
  B. Dependencies
  C. Usage
  D. Configuration

------------------------------------------------------------------------------
A. Introduction

   Warden Kippo connector (executable warden3-kippo-sender.py) is a one-shot 
   script to send events from Kippo honeypot toward the Warden server.

------------------------------------------------------------------------------
B. Dependencies

 1. Platform

    Python 2.7+

 2. Python packages

    warden_client 3.0+

------------------------------------------------------------------------------
C. Usage

   warden3-kippo-sender.py 

   This script does not run as a daemon, for regularly run use job scheduler cron.

------------------------------------------------------------------------------
D. Configuration
   
   warden_client-kippo.cfg
    warden - path to warden-client config, e.g. 'warden/warden_client.cfg'
    name - sensor's source id used as a source of events, e.g. 'cz.cesnet.server.kippo'
    secret - secret to authenticate client
           - if 'secret' is non empty, is used instead of value in client's configuration
           - useful while using more sensors with single client's configuration 

    anonymised - no | yes | omit
               - no (default value)
               - yes = anonymize to 'target_net' (see below)
               - omit = completely omit target field

    target_net - anonymized network used as target if 'anonymized' option is 'yes' 

    dbhost - hostname/IP of MySQL DB server 
    dbuser - username 
    dbpass - password
    dbname - database
    dbport - db port
    awin   - aggregation window, e.g. 5 for events in the last 5 minutes
    
   cron
    SCRIPT_PATH=/opt/warden_client/
    */5  *   * * *  root cd $SCRIPT_PATH; python warden3-kippo-sender.py > /dev/null 2>&1

    Note: Repeat interval must be the same as value of 'awin'.

------------------------------------------------------------------------------
Copyright (C) 2011-2015 Cesnet z.s.p.o
+121 −0
Original line number Original line Diff line number Diff line
#!/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, format_timestamp
import json
import string
from time import time, gmtime, strftime
from math import trunc
from uuid import uuid4
from os import path
import sys

import MySQLdb as my
import MySQLdb.cursors as mycursors

DEFAULT_ACONFIG = 'warden_client-kippo.cfg'
DEFAULT_WCONFIG = 'warden_client.cfg'
DEFAULT_NAME = 'org.example.warden.test'
DEFAULT_AWIN = 5
DEFAULT_ANONYMISED = 'no'
DEFAULT_TARGET_NET = '0.0.0.0/0'
DEFAULT_SECRET = ''


def gen_event_idea(client_name, detect_time, win_start_time, win_end_time, conn_count, src_ip, dst_ip, aggr_win, anonymised, target_net):

  event = {
     "Format": "IDEA0",
     "ID": str(uuid4()),
     "DetectTime": detect_time,
     "WinStartTime": win_start_time,
     "WinEndTime": win_end_time,
     "Category": ["Attempt.Login"],
     "Note": "SSH login attempt",
     "ConnCount": conn_count,
     "Source": [{}],
     "Target": [
        {
           "Proto": ["tcp", "ssh"],
           "Port" : [22]
        }
     ],
     "Node": [
        {
           "Name": client_name,
           "Type": ["Connection","Honeypot","Recon"],
           "SW": ["Kippo"],
           "AggrWin": strftime("%H:%M:%S", gmtime(aggr_win))
        }
     ]
  }

  af = "IP4" if not ':' in src_ip else "IP6"
  event['Source'][0][af] = [src_ip]

  if anonymised != 'omit':
    if anonymised == 'yes':
      event['Target'][0]['Anonymised'] = True
      event['Target'][0][af] = [target_net]
    else:
      event['Target'][0][af] = [dst_ip]
  
  return event

def main():
  aconfig = read_cfg(DEFAULT_ACONFIG)
  wconfig = read_cfg(aconfig.get('warden', DEFAULT_WCONFIG))
  
  aname = aconfig.get('name', DEFAULT_NAME)
  awin = aconfig.get('awin', DEFAULT_AWIN) * 60
  wconfig['name'] = aname

  asecret = aconfig.get('secret', DEFAULT_SECRET)
  if asecret:
    wconfig['secret'] = asecret

  wclient = Client(**wconfig)   

  aanonymised = aconfig.get('anonymised', DEFAULT_ANONYMISED)
  if aanonymised not in ['no', 'yes', 'omit']:
    wclient.logger.error("Configuration error: anonymised: '%s' - possible typo? use 'no', 'yes' or 'omit'" % aanonymised)
    sys.exit(2)

  atargetnet  = aconfig.get('target_net', DEFAULT_TARGET_NET)
  aanonymised = aanonymised if (atargetnet != DEFAULT_TARGET_NET) or (aanonymised == 'omit') else DEFAULT_ANONYMISED

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

  events = []
  query =  "SELECT MIN(UNIX_TIMESTAMP(s.starttime)) as starttime, s.ip, COUNT(s.id) as attack_scale, sn.ip as sensor \
            FROM sessions s \
            LEFT JOIN sensors sn ON s.sensor=sn.id \
            WHERE s.starttime > DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL + %s SECOND) \
            GROUP BY s.ip, sn.ip ORDER BY starttime ASC;"

  crs.execute(query, (awin,))
  rows = crs.fetchall()
  for row in rows:
    dtime = format_timestamp(row['starttime'])
    etime = format_timestamp(time())
    stime = format_timestamp(time() - awin)
    events.append(gen_event_idea(client_name = aname, detect_time = dtime, win_start_time = stime, win_end_time = etime, conn_count = row['attack_scale'], src_ip = row['ip'], dst_ip = row['sensor'], aggr_win = awin, anonymised = aanonymised, target_net = atargetnet))
      
  print "=== Sending ==="
  start = time()
  ret = wclient.sendEvents(events)
  
  if ret:
    wclient.logger.info("%d event(s) successfully delivered." % len(rows))

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


if __name__ == "__main__":
    main()
+15 −0
Original line number Original line Diff line number Diff line
{
    "warden": "warden_client.cfg",
    "name": "cz.cesnet.server.kippo",
    "secret": "",

    "anonymised": "no",
    "target_net": "195.113.0.0/16",

    "dbhost": "localhost",
    "dbuser": "kippo",
    "dbpass": "kippopass",
    "dbname": "kippo",
    "dbport": 3306,
    "a_win": 5
}
+67 −0
Original line number Original line Diff line number Diff line
Warden LaBrea connector 0.1 for Warden 3.X
==========================================

Introduction
------------

labrea-idea.py is a daemon, meant for continuous watching of LaBrea log files
and generation of Idea_ format of corresponding security events. It is
usually run in correspondence with warden_filer daemon, which picks the
resulting events up and feeds them to the Warden_ server. Connector supports
sliding window aggregation, so sets of connections with the same source are
reported as one event (within aggregation window).


Dependencies
------------

 1. Platform

    Python 2.7+

 2. Python packages

    warden_filer 3.0+ (recommended)


Usage
-----

        ./labrea-idea.py [options] logfile ...

        Options:
          -h, --help            show this help message and exit
          -w WINDOW, --window=WINDOW
                                max detection window (default: 900)
          -t TIMEOUT, --timeout=TIMEOUT
                                detection timeout (default: 300)
          -n NAME, --name=NAME  Warden client name
          --test                Add Test category
          -o, --oneshot         process files and quit (do not daemonize)
          --poll=POLL           log file polling interval
          -d DIR, --dir=DIR     Target directory (mandatory)
          -p PID, --pid=PID     create PID file with this name (default: /var/run
                                /labrea-idea.pid)
          -u UID, --uid=UID     user id to run under
          -g GID, --gid=GID     group id to run under
          -v, --verbose         turn on debug logging
          --log=LOG             syslog facility or log file name (default: local7)
          --realtime            use system time along with log timestamps (default)
          --norealtime          don't system time, use solely log timestamps


Configuration
-------------

However, the daemon is usually run by init script (example one is a part of
the distribution, along with sample logrotate definition). Options then can
be configured by /etc/sysconfig/labrea-idea or /etc/defaults/labrea-idea,
depending on your distribution custom, where at least PARAMS variable has
to be specified (for others, see the init script).
    
.. _Warden: https://warden.cesnet.cz/
.. _Idea: https://idea.cesnet.cz/

------------------------------------------------------------------------------

Copyright (C) 2017 Cesnet z.s.p.o
+58 −0
Original line number Original line Diff line number Diff line
#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          labrea-idea
# Required-Start:    $local_fs $syslog
# Required-Stop:     $local_fs $syslog
# Should-Start:      $network
# Should-Stop:       $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Labrea-Idea aggregator/converter
### END INIT INFO

DAEMON_NAME=labrea-idea
DAEMON_PATH=/usr/local/bin/"$DAEMON_NAME".py
PID=/var/run/"$DAEMON_NAME".pid

# Try Debian & Fedora/RHEL/Suse sysconfig
for n in default sysconfig; do
	[ -f /etc/$n/"$DAEMON_NAME" ] && . /etc/$n/"$DAEMON_NAME"
done

# Fallback
function log_daemon_msg () { echo -n "$@"; }
function log_end_msg () { [ $1 -eq 0 ] && echo " OK" || echo " Failed"; }
function status_of_proc () { [ -f "$PID" ] && ps u -p $(<"$PID") || echo "$PID not found."; }

[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions

ACTION="$1"

case "$ACTION" in
	start)
		if [ -z "$PARAMS" ]; then
			log_daemon_msg "Unconfigured $DAEMON_NAME, not starting."
			exit 2
		fi
		mkdir -p "${PID%/*}"
		log_daemon_msg "Starting $DAEMON_NAME"
		start_daemon -p "$PID" "$DAEMON_PATH" --pid "$PID" $PARAMS
		log_end_msg $?
		;;
	stop)
		log_daemon_msg "Stopping $DAEMON_NAME"
		killproc -p "$PID" "$DAEMON_PATH"
		log_end_msg $?
		;;
	restart|force-reload)
		$0 stop && sleep 2 && exec $0 start
		;;
	status)
		status_of_proc -p "$PID" "$DAEMON_PATH"
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 2
		;;
esac
+11 −0
Original line number Original line Diff line number Diff line
/var/log/labrea-idea.log
{
	rotate 52
	weekly
	missingok
	notifempty
	compress
	delaycompress
	dateext
	create 640 mentat mentat
}
+678 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −1
Original line number Original line Diff line number Diff line
BSD License
BSD License


Copyright © 2011-2013 Cesnet z.s.p.o
Copyright © 2011-2015 Cesnet z.s.p.o
All rights reserved.
All rights reserved.


Redistribution and use in source and binary forms, with or without modification,
Redistribution and use in source and binary forms, with or without modification,
+51 −0
Original line number Original line Diff line number Diff line
+-----------------------------------------------------------------+
| Warden client Request Tracker connector 20150903 for Warden 3.X |
+-----------------------------------------------------------------+

Content

  A. Introduction
  B. Dependencies
  C. Usage
  D. Configuration

------------------------------------------------------------------------------
A. Introduction

   Warden client Request Tracker connector (executable warden_client-rt.py) is a one-shot 
   script to send events from Warden queue toward the Request Tracker.

------------------------------------------------------------------------------
B. Dependencies

 1. Platform

    Python 2.7+

 2. Python packages

    warden_client 3.0+

------------------------------------------------------------------------------
C. Usage

   warden_client-rt.py

   This script does not run as a daemon, for regularly run use job scheduler cron.

------------------------------------------------------------------------------
D. Configuration

    warden_client-rt.cfg

    warden - path to warden-client config, e.g. 'warden/warden_client.cfg'
    bt - templates for request tracker tickets and array of cidrs for reporting
    rt - requestr tracker account section
    filter - filtering warden events

   cron
    SCRIPT_PATH=/opt/warden_client/
    0  */1   * * *  root cd $SCRIPT_PATH; python warden_client-rt.py > /dev/null 2>&1

------------------------------------------------------------------------------
Copyright (C) 2011-2015 Cesnet z.s.p.o
+32 −0
Original line number Original line Diff line number Diff line
Dobrý den,

přišlo nám upozornění od cizí organizace, že Váš počítač nabízel produkty uvedené níže.
Do doby než nám zašlete vysvětlení Vám byla zablokována registrace.

Notice ID: {id}
Protocol: BitTorrent
IP Address: {ip} 
File Name: {filename}
Timestamp: {timestamp}

Chtěli bychom Vás požádat o prověření, zda nedochází k porušování autorských práv z této stanice.
Prosíme, ověřte stav Vaší stanice, a zašlete nám vysvětlující zprávu, kde uvedete kroky, které jste realizoval, aby dále k tomuto jevu nedocházelo.

Bližší informace o problematice naleznete na adrese:
http://idoc.vsb.cz/cit/tuonet/pravidla/az/

---

Hello,

we received an information from foreign organization, that your PC shared (uploaded) copyrighted material listed below.
Your registration (access to computer network and internet) will be suppressed until you send us an explanation.

Notice ID: {id}
Protocol: BitTorrent
IP Address: {ip} 
File Name: {filename}
Timestamp: {timestamp}

We would like to ask you for verify your PC (installed software), if there is some software which may be the cause for breaking the copyright act.
Please check your PC and send us your deliverance, including the steps you realized to avoid this in the future.
+32 −0
Original line number Original line Diff line number Diff line
{
	"warden": {
		"url": "https://warden-hub.cesnet.cz/warden3",
		"certfile": "/etc/ssl/mentat.vsb.cz/server.crt",
		"keyfile": "/etc/ssl/mentat.vsb.cz/serverkey_de.pem",
		"cafile": "/etc/ssl/mentat.vsb.cz/tcs-ca-bundle.pem",
		"timeout": 60,
		#"recv_events_limit": 6000,
		"errlog": {"level": "debug"},
		"filelog": {"file": "/var/log/warden_client.log", "level": "warning"},
		"idstore": "/var/lib/warden/warden_client.id",
		"name": "cz.vsb.bittorrent",
		"secret": "TAJNE"
	},
	"bt": {
		"template": "bittorrent.tpl",
		"matching_cidrs": ["158.196.0.0/16", "89.0.0.0/8"]
	},
	"rt": {
		"rtrest": "https://idesk.vsb.cz/REST/1.0/",
		"rtuser": "LOGIN",
		"rtpass": "HESLO",
		# <option value="3">Bezpečnostní síťové incidenty</option>
		"rtqueue": 7,
		"category": "sdileni",
		"other": " - zablokovano",
		"rtsubject": "{category} {ip}{login}{other}"
	},
	"filter": {
		"cat": ["Fraud.Copyright"]
	}
}
+87 −0
Original line number Original line Diff line number Diff line
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys
from netaddr import all_matching_cidrs # apt-get install python-netaddr

from warden_client import Client, Error, read_cfg

# pip install python-rtkit
from rtkit.resource import RTResource
from rtkit.authenticators import QueryStringAuthenticator
from rtkit.errors import RTResourceError
from rtkit import set_logging

import logging
set_logging('debug')
logger = logging.getLogger('rtkit')

def createTicket (config, body, ip):

        template = config.get('rtsubject') 
	# "rtsubject": "{category} {ip} {login} {other}"
	subject = template.format(category=config.get("category", "sdileni"), ip="("+ip+")", login="", other=config.get("other", " - zablokovano"))

	content = {
	    'content': {
			'Queue': config.get('rtqueue'),
			'Subject': subject, 
			'Text': body,
	    }
	}
	
	try:
	    resource = RTResource(config.get('rtrest'), config.get('rtuser'), config.get('rtpass'), QueryStringAuthenticator)
	    response = resource.post(path='ticket/new', payload=content,)

	    logger.info(response.parsed)

	except RTResourceError as e:
	    logger.error(e.response.status_int)
	    logger.error(e.response.status)
	    logger.error(e.response.parsed)


def main():
	config = read_cfg("warden_client-rt.cfg")

	# Allow inline or external Warden config
	wconfig = config.get("warden", "warden_client.cfg")

	if isinstance(wconfig, basestring):
		wconfig = read_cfg(wconfig)

	wclient = Client(**wconfig) 

	btconfig = config.get("bt", None)
	matching_cidrs = btconfig.get('matching_cidrs')

	with open(btconfig.get('template', None)) as f:
	       template = f.read()


	filt = {}
	conf_filt = config.get("filter", {})
	# Extract filter explicitly to be sure we have right param names for getEvents
	for s in ("cat", "nocat", "tag", "notag", "group", "nogroup"):
		filt[s] = conf_filt.get(s, None)

	ret = wclient.getEvents(**filt)
	
	for e in ret:
		try:
			ip = e.get("Source")[0].get("IP4")[0]
			id = e.get("ID")
			timestamp = e.get("DetectTime")
			filename = e['Attach'][0]['FileName'][0]
		except:
			pass	

		message = template.format(id=id, ip=ip, filename=filename, timestamp=timestamp)
		#print message

		if all_matching_cidrs(ip, btconfig.get('matching_cidrs', None)):
			createTicket(config.get('rt',None), message, ip)

if __name__ == "__main__":
    main()

contrib/map/LICENSE

0 → 100644
+27 −0
Original line number Original line Diff line number Diff line
BSD License

Copyright © 2016 Cesnet z.s.p.o
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the Cesnet z.s.p.o nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE Cesnet z.s.p.o BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

contrib/map/README

0 → 100644
+68 −0
Original line number Original line Diff line number Diff line
+---------------------------------+
| Warden Map Client 1.0           |
+---------------------------------+

Content

  A. Introduction
  B. Configuration
  C. Usage & Help

------------------------------------------------------------------------------
A. Introduction

  Warden Map Client is very simple client for drawing a map with events from
  database of the Warden server. It consists of a Python 2.7 backend and
  a javascript/jquery frontend.

  Backend uses Warden API for downloading of events. Events are processed and
  enhanced with a geodata via freegeoip.net API. Finally warden-map.json file
  with information for the frontend is created.

  Frontend uses datamaps project (http://datamaps.github.io/) for visualisation
  of events on a map. It is possible to check details of the event by moving
  cursor on a arc. It is also possible to zoom map via scrolling and/or clicking
  on the plus, minus and, home buttons.

------------------------------------------------------------------------------
B. Configuration

  1. Copy frontend folder into desired location.

  2. Copy html snippet into your web page, or use it as an iframe.
     NOTE: If necessary, change css/js paths in a html snippet.

  3. Copy backend folder into desired location.

  4. Setup backend call (warden-map.py) in a crontab.
     NOTE: Please make sure you will have stored warden-map.json file
           in the frontend folder.
     EXAMPLE: ./warden-map.py --client cz.cesnet.warden.map \
                              --key certs/key.pem \
                              --cert certs/cert.pem \
                              --output ../frontend/

  5. Enjoy your map.

------------------------------------------------------------------------------
C. Usage & Help

usage: warden-map.py [-h] [--output /path/] --events <number> --client
                     <org.ex.cl> --key /path/key.pem --cert /path/cert.pem
                     --cacert /path/cacert.pem --secret <SeCreT>

optional arguments:
  -h, --help                 show this help message and exit
  --output path/            path where warden-map.json should be saved

required arguments:
  --events <number>          count of events for a map
  --client <org.ex.cl>       client name
  --key path/key.pem        SSL key for a client
  --cert path/cert.pem      SSL cert for a client
  --cacert path/cacert.pem  SSL cacert for a client
  --secret <SeCreT>          secret key for a client


------------------------------------------------------------------------------
Copyright (C) 2016 Cesnet z.s.p.o
+125 −0
Original line number Original line Diff line number Diff line
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# warden-map.py
#
# Copyright (C) 2016 Cesnet z.s.p.o
# Use of this source is governed by a 3-clause BSD-style license, see LICENSE file.

import json
import codecs
import time
import argparse
import GeoIP
import requests

def getLastEvents(client, key, cert):

  res = requests.post(
      'https://warden-hub.cesnet.cz/warden3/getEvents?client=%s' % (client,),
      cert=(cert, key)
  )

  data = res.json()
  i = 0
  eventsList = []
  for p in data['events']:
    event = {}
    for key, value in { 'event': 'Category', 'time': 'DetectTime', 'origin': 'Source', 'destination': 'Target'}.items():
      if value in p:
        if (key == 'origin') or (key == 'destination'):
          event[key] = {}
          if 'IP4' in p[value][0]:
            event[key]['ip'] = p[value][0]['IP4'][0]
          else:
            event[key] = {}
        elif (key == 'event'):
          event[key] = ', '.join(p[value])
        else:
          event[key] = p[value]
      else:
        if (key == 'origin') or (key == 'destination'):
          event[key] = {}
        else:
          event[key] = {}
    if 'ip' in event['origin']:
      eventsList.append(event)
      i += 1

  return eventsList

def getGeolocation(ip, db):

  data = db.record_by_addr(ip)

  if not data:
    return {}
  else:
    return {
      'latitude': data['latitude'], 
      'longitude': data['longitude'], 
      'country_name': data['country_name'] if data['country_name'] else None, 
      'city': data['city'] if data['city'] else None
    }

def main(args):

  client = args.client[0]
  key    = args.key[0]
  cert   = args.cert[0]

  if args.output is not None:
    path = args.output[0] + 'warden-map.json'
  else:
    path = 'warden-map.json'

  db = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_MEMORY_CACHE)
  db.set_charset(GeoIP.GEOIP_CHARSET_UTF8)

  wardenEvents = getLastEvents(client, key, cert)

  for p in wardenEvents:
    for target in {'origin', 'destination'}:
      geoData = {}
      if 'ip' in p[target]:
        geoData = getGeolocation(p[target]['ip'], db)
        for value in {'latitude', 'longitude', 'country_name', 'city'}:
          if value in geoData:
            if not geoData[value]:
              p[target][value] = "???"
            else:
              p[target][value] = geoData[value]
          else:
            p[target][value] = "???"

      else:
        p[target]['ip'] = "???"
        p[target]['country_name'] = "Czech Republic"
        p[target]['city'] = "???"
        p[target]['latitude'] = 49.743
        p[target]['longitude'] = 15.338

  wardenEvents.append(int(time.time()));

  with open(path, 'w') as outfile:
    json.dump(wardenEvents, outfile)


if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Creates warden-map.json for warden-map.html frontend.',
                                  formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=30))

  parser.add_argument('--output', metavar='path/', type=str,
                    nargs=1, help='path where warden-map.json should be saved')

  requiredNamed = parser.add_argument_group('required arguments')

  requiredNamed.add_argument('--client', metavar='<org.ex.cl>', type=str, required=True,
                    nargs=1, help='client name')
  requiredNamed.add_argument('--key', metavar='path/key.pem', type=str, required=True,
                    nargs=1, help='SSL key for a client')
  requiredNamed.add_argument('--cert', metavar='path/cert.pem', type=str, required=True,
                    nargs=1, help='SSL cert for a client')

  args = parser.parse_args()
  main(args)
+138 −0
Original line number Original line Diff line number Diff line
/*
 *
 * -*- coding: utf-8 -*-
 *
 * warden-map.css
 *
 * Copyright (C) 2016 Cesnet z.s.p.o
 * Use of this source is governed by a 3-clause BSD-style license, see LICENSE file.
 *
*/

body {
  font-family: 'Oswald', sans-serif;
  background: #00253D;
  border: 0px;
  padding: 0px;
  margin: 0px;
}

h2 {
 color: #0062a2;
}

.hoverinfo {
  font-family: 'Oswald', sans-serif;
}

#country {
  color: #0062a2;	/* Cesnet blue */
  font-weight: bold;
}


table {
  text-align: left;
  margin: 0;
  padding: 0;
  font-size: 12px;
}

table th {
  color: #0062a2;	/* Cesnet blue */
  padding: 0;
}

table td {
  color: #4b4d4a;	/* Greenish gray */
  padding: 0;
}

#container {
  overflow: hidden;
/*  border: 2px solid #0062a2;
  border: 0px;
  padding: 0px;
  margin: 0px;
  border-radius: 5px;*/
  position: relative;
/*  width: 1280px;
  height: 720px;*/
  max-width: 100%;
  max-height: 100%
  width: 100%;
  height: 100vh;*/
}

.zoom-button {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  border: none;
  background: #dcdcda;
  font-size: 23px;
  font-weight: bold;
  color: white;
  cursor: pointer;
}

.zoom-button:hover {
  background-color: #0062a2;
}

#zoom-info {
  display: inline-block;
  padding: 10px;
  color: #0062a2;
}

#warden-logo {
  position: absolute;
  top: 30px;
  left: 30px;
  background: white;
  padding: 10px;
  border-radius: 10px;
  width: 240px;
  height: 92px;
  text-align: center;
}

#cesnet-logo {
  position: absolute;
  top: 30px;
  right: 30px;
  background: white;
  padding: 10px;
  border-radius: 10px;
  width: 240px;
  height: 92px;
  text-align: center;
}

#legend-box {
  position: absolute;
  bottom: 30px;
  left: 30px;
  background-color: rgba(0,0,0,0.3);
  color: white;
  padding: 10px;
  border-radius: 10px;
  /*width: 240px;
  height: 92px;
  text-align: center;*/
}

#heading {
  position: absolute;
  top: 30px;
  left: 50%;
  width: 40em;
  height: 92px;
  margin-left: -20em;
  font-size: xx-large;
  color: white;
  text-align: center;
  vertical-align: middle;
  line-height: 92px;
}
+474 −0
Original line number Original line Diff line number Diff line
/*
 *
 * -*- coding: utf-8 -*-
 *
 * warden-map.js
 *
 * Copyright (C) 2016 Cesnet z.s.p.o
 * Use of this source is governed by a 3-clause BSD-style license, see LICENSE file.
 *
*/

// NOTE: Change path in a function d3.json() if you separate backend and frontend!

// Zooming functionality is based on WunderBart's implementation
// Please see following links:
// https://github.com/wunderbart
// https://jsfiddle.net/wunderbart/Lom3b0gb/

  function Zoom(args) {
  $.extend(this, {
    $buttons:   $(".zoom-button"),
    $info:      $("#zoom-info"),
    scale:      { max: 50, currentShift: 0 },
    $container: args.$container,
    datamap:    args.datamap
  });

  this.init();
}

Zoom.prototype.init = function() {
  var paths = this.datamap.svg.selectAll("path"),
      subunits = this.datamap.svg.selectAll(".datamaps-subunit");

  // preserve stroke thickness
  paths.style("vector-effect", "non-scaling-stroke");

  // disable click on drag end
  subunits.call(
    d3.behavior.drag().on("dragend", function() {
      d3.event.sourceEvent.stopPropagation();
    })
  );

  this.scale.set = this._getScalesArray();
  this.d3Zoom = d3.behavior.zoom().scaleExtent([ 1, this.scale.max ]);

  this._displayPercentage(1);
  this.listen();
};

Zoom.prototype.listen = function() {
  this.$buttons.off("click").on("click", this._handleClick.bind(this));

  this.datamap.svg
    .call(this.d3Zoom.on("zoom", this._handleScroll.bind(this)))
    .on("dblclick.zoom", null); // disable zoom on double-click
};

Zoom.prototype.reset = function() {
  this._shift("reset");
};

Zoom.prototype._handleScroll = function() {
  var translate = d3.event.translate,
      scale = d3.event.scale,
      limited = this._bound(translate, scale);

  this.scrolled = true;

  this._update(limited.translate, limited.scale);
};

Zoom.prototype._handleClick = function(event) {
  var direction = $(event.target).data("zoom");

  this._shift(direction);
};

Zoom.prototype._shift = function(direction) {
  var center = [ this.$container.width() / 2, this.$container.height() / 2 ],
      translate = this.d3Zoom.translate(), translate0 = [], l = [],
      view = {
        x: translate[0],
        y: translate[1],
        k: this.d3Zoom.scale()
      }, bounded;

  translate0 = [
    (center[0] - view.x) / view.k,
    (center[1] - view.y) / view.k
  ];

  if (direction == "reset") {
    view.k = 1;
    this.scrolled = true;
  } else {
    view.k = this._getNextScale(direction);
  }

l = [ translate0[0] * view.k + view.x, translate0[1] * view.k + view.y ];

  view.x += center[0] - l[0];
  view.y += center[1] - l[1];

  bounded = this._bound([ view.x, view.y ], view.k);

  this._animate(bounded.translate, bounded.scale);
};

Zoom.prototype._bound = function(translate, scale) {
  var width = this.$container.width(),
      height = this.$container.height();

  translate[0] = Math.min(
    (width / height)  * (scale - 1),
    Math.max( width * (1 - scale), translate[0] )
  );

  translate[1] = Math.min(0, Math.max(height * (1 - scale), translate[1]));

  return { translate: translate, scale: scale };
};

Zoom.prototype._update = function(translate, scale) {
  this.d3Zoom
    .translate(translate)
    .scale(scale);

  this.datamap.svg.selectAll("g")
    .attr("transform", "translate(" + translate + ")scale(" + scale + ")");

  this._displayPercentage(scale);
};

Zoom.prototype._animate = function(translate, scale) {
  var _this = this,
      d3Zoom = this.d3Zoom;

  d3.transition().duration(350).tween("zoom", function() {
    var iTranslate = d3.interpolate(d3Zoom.translate(), translate),
        iScale = d3.interpolate(d3Zoom.scale(), scale);

    return function(t) {
      _this._update(iTranslate(t), iScale(t));
    };
  });
};

Zoom.prototype._displayPercentage = function(scale) {
  var value;

  value = Math.round(Math.log(scale) / Math.log(this.scale.max) * 100);
  this.$info.text(value + "%");
};

Zoom.prototype._getScalesArray = function() {
  var array = [],
      scaleMaxLog = Math.log(this.scale.max);

  for (var i = 0; i <= 10; i++) {
    array.push(Math.pow(Math.E, 0.1 * i * scaleMaxLog));
  }

  return array;
};

Zoom.prototype._getNextScale = function(direction) {
  var scaleSet = this.scale.set,
      currentScale = this.d3Zoom.scale(),
      lastShift = scaleSet.length - 1,
      shift, temp = [];

  if (this.scrolled) {

    for (shift = 0; shift <= lastShift; shift++) {
      temp.push(Math.abs(scaleSet[shift] - currentScale));
    }

    shift = temp.indexOf(Math.min.apply(null, temp));

    if (currentScale >= scaleSet[shift] && shift < lastShift) {
      shift++;
    }

    if (direction == "out" && shift > 0) {
      shift--;
    }

    this.scrolled = false;

  } else {

    shift = this.scale.currentShift;

    if (direction == "out") {
      shift > 0 && shift--;
    } else {
      shift < lastShift && shift++;
    }
  }

  this.scale.currentShift = shift;

  return scaleSet[shift];
};


 function defaults(obj) {
    Array.prototype.slice.call(arguments, 1).forEach(function(source) {
      if (source) {
        for (var prop in source) {
          // Deep copy if property not set
          if (obj[prop] == null) {
            if (typeof source[prop] == 'function') {
              obj[prop] = source[prop];
            }
            else {
              obj[prop] = JSON.parse(JSON.stringify(source[prop]));
            }
          }
        }
      }
    });
    return obj;
  }

function val( datumValue, optionsValue, context ) {
    if ( typeof context === 'undefined' ) {
      context = optionsValue;
      optionsValues = undefined;
    }
    var value = typeof datumValue !== 'undefined' ? datumValue : optionsValue;

    if (typeof value === 'undefined') {
      return  null;
    }

    if ( typeof value === 'function' ) {
      var fnContext = [context];
      if ( context.geography ) {
        fnContext = [context.geography, context.data];
      }
      return value.apply(null, fnContext);
    }
    else {
      return value;
    }
  }
  
var cat_color = {
  "Abusive": "MediumPurple",
  "Malware": "Red",
  "Recon": "LightSlateGray",
  "Attempt": "GhostWhite",
  "Intrusion": "DarkTurquoise",
  "Availability": "HotPink",
  "Information": "PaleTurquoise",
  "Fraud": "Yellow",
  "Vulnerable": "DarkGoldenRod",
  "Anomaly": "Brown",
  "Other": "Green"
}

var cat_desc = {
  "Abusive": "spam",
  "Malware": "virus, worm, trojan, malware",
  "Recon": "scanning, sniffing",
  "Attempt": "bruteforce, exploitation attempt",
  "Intrusion": "botnet, successful exploit",
  "Availability": "(D)DOS",
  "Information": "wiretapping, spoofing, hijacking",
  "Fraud": "phishing, scam",
  "Vulnerable": "open for abuse",
  "Anomaly": "unusual traffic",
  "Other": "unknown/unidentified"
}

 function handleArcs (layer, data, options) {
    var self = this,
        svg = this.svg;

    if ( !data || (data && !data.slice) ) {
      throw "Datamaps Error - arcs must be an array";
    }

    // For some reason arc options were put in an `options` object instead of the parent arc
    // I don't like this, so to match bubbles and other plugins I'm moving it
    // This is to keep backwards compatability
    for ( var i = 0; i < data.length; i++ ) {
      data[i] = defaults(data[i], data[i].options);
      delete data[i].options;
    }

    if ( typeof options === "undefined" ) {
      options = defaultOptions.arcConfig;
    }

    var arcs = layer.selectAll('path.datamaps-arc').data( data, JSON.stringify );

    var path = d3.geo.path()
        .projection(self.projection);

    arcs
      .enter()
        .append('svg:path')
        .attr('class', 'datamaps-arc')
        .style('stroke-linecap', 'round')
        .style('stroke', function(datum) {
/*          return val(datum.strokeColor, options.strokeColor, datum);*/
          for (cat in cat_color) {
            if (datum.event.startsWith(cat)) {
              return cat_color[cat];
            }
          }
          return "Green";
        })
        .style('fill', 'none')
        .style('stroke-width', function(datum) {
            return val(datum.strokeWidth, options.strokeWidth, datum);
        })
        .attr('d', function(datum) {

            var originXY, destXY;

            originXY = self.latLngToXY(val(datum.origin.latitude, datum), val(datum.origin.longitude, datum))

            destXY = self.latLngToXY(val(datum.destination.latitude, datum), val(datum.destination.longitude, datum));

            var midXY = [ (originXY[0] + destXY[0]) / 2, (originXY[1] + destXY[1]) / 2];
            if (options.greatArc) {
                  // TODO: Move this to inside `if` clause when setting attr `d`
              var greatArc = d3.geo.greatArc()
                  .source(function(d) { return [val(d.origin.longitude, d), val(d.origin.latitude, d)]; })
                  .target(function(d) { return [val(d.destination.longitude, d), val(d.destination.latitude, d)]; });

              return path(greatArc(datum))
            }
            var sharpness = val(datum.arcSharpness, options.arcSharpness, datum);
            return "M" + originXY[0] + ',' + originXY[1] + "S" + (midXY[0] + (50 * sharpness)) + "," + (midXY[1] - (75 * sharpness)) + "," + destXY[0] + "," + destXY[1];
        })
        .attr('data-info', function(datum) {
          return JSON.stringify(datum);
        })
        .on('mouseover', function ( datum ) {
          var $this = d3.select(this);

          if (options.popupOnHover) {
            self.updatePopup($this, datum, options, svg);
          }
        })
        .on('mouseout', function ( datum ) {
          var $this = d3.select(this);

          d3.selectAll('.datamaps-hoverover').style('display', 'none');
        })
        .transition()
          .style('fill', function(datum, i) {
            /*
              Thank you Jake Archibald, this is awesome.
              Source: http://jakearchibald.com/2013/animated-line-drawing-svg/
            */
            var length = this.getTotalLength();
            this.style.transition = this.style.WebkitTransition = 'none';
            this.style.strokeDasharray = length + ' ' + length;
            this.style.strokeDashoffset = length;
            this.getBoundingClientRect();
            this.style.transition = this.style.WebkitTransition = 'stroke-dashoffset ' + val(datum.animationSpeed, options.animationSpeed, datum) + 'ms ' + datum.delay*1000 + 'ms ease-out';
            this.style.strokeDashoffset = '0';
            return 'none';
          });

    arcs.exit()
      .transition()
      .duration(1000)
      .style('opacity', 0)
      .remove();
  }

var main_data = [];
var prev_data = 0;

// Configuration of datamap canvas
// Futher reading can be found at https://datamaps.github.io/
function Datamap() {
  this.$container = $("#container");
  instance = this.instance = new Datamaps({
    scope: 'world',
    element: this.$container.get(0),
    done: this._handleMapReady.bind(this),
    projection: 'mercator',
        fills: {
          /*defaultFill: '#454545'*/
          defaultFill: 'black'
        },
        geographyConfig: {
          hideAntarctica: true,
          borderColor: '#0062a2',
          highlightFillColor: '#4b4d4a',
          highlightBorderColor: '#fdfdfd',
          popupOnHover: true,
          popupTemplate: function(geography, data) {
          return '<div class="hoverinfo" id="country">' + geography.properties.name + '</div>';
        },
        },
        ph_arcConfig: {
          strokeColor: '#0062a2',
          strokeWidth: 2,
          arcSharpness: 2, /* 5 */
          animationSpeed: 3000, // Milliseconds
          popupOnHover: true,
          // Case with latitude and longitude
          popupTemplate: function(geography, data) {
            if ( ( data.origin && data.destination ) && data.origin.latitude && data.origin.longitude && data.destination.latitude && data.destination.longitude ) {
              // Content of info table
              str = '<div class="hoverinfo"><table id="event"><tr><th>Warden Event</th></tr><tr><td>Type</td><td>'+ JSON.stringify(data.event) +'</td></tr><tr><td>Detect Time</td><td>'+ JSON.stringify(data.time) +'</td></tr><tr><th>Event origin</th></tr><tr><td>IP</td><td>' + JSON.stringify(data.origin.ip) +  '</td></tr><tr><td>City & Country</td><td>' + JSON.stringify(data.origin.city) + ',&nbsp;' + JSON.stringify(data.origin.country_name) + '</td></tr><tr><td>GPS</td><td>' + JSON.stringify(data.origin.latitude) + ',&nbsp;' + JSON.stringify(data.origin.longitude) + '</td></tr><tr><th>Event Destination</th></tr><tr><td>IP</td><td>' + JSON.stringify(data.destination.ip) + '</td></tr><tr><td>City & Country</td><td>' + JSON.stringify(data.destination.city) + ',&nbsp;' + JSON.stringify(data.destination.country_name) + '</td></tr><tr><td>GPS</td><td>' + JSON.stringify(data.destination.latitude) + ',&nbsp;' + JSON.stringify(data.destination.longitude) + '</td></tr></table></div>';
              return str.replace(/&quot;/g,"");
            }
            // Missing information
            else {
              return '';
            }
          }
        }
      });

  legend_data = d3.select("#legend")
    .selectAll("li")
    .data(Object.keys(cat_color).sort())
    .enter()
      .append("li")
        .append("span")
          .style("color", function(datum) { return cat_color[datum]})
          .text(function(datum) { return datum; })
          .append("span")
          .text(function(datum) { return "" + cat_desc[datum]})
          .style("color", "white");
  
    instance.addPlugin('ph_arc', handleArcs);

  setInterval(function(){
      d3.json("./warden-map.json", function(error, data) {
          if (data) {
              var cur_data = data.pop()
              var cur_time = new Date().getTime();
              if (cur_data != prev_data) {
                  prev_data = cur_data;
                  for (var i=0; i<data.length; i++) {
                      data[i].arrivalTime = cur_time;
                      data[i].delay = i/data.length;
                  }
                  main_data = main_data.concat(data);
              }
          }
          var trimmed_data = [];
          for (var i=0; i<main_data.length; i++) {
              if (main_data[i].arrivalTime + 3500 > cur_time) {
                  trimmed_data.push(main_data[i]);
              }
          }
          main_data = trimmed_data;
          trimmed_data = cur_time = cur_data = error = data = null;
          instance.ph_arc(main_data);
      });
  }, 1000);

};

Datamap.prototype._handleMapReady = function(datamap) {
  this.zoom = new Zoom({
    $container: this.$container,
    datamap: datamap
  });
}
+48 −0
Original line number Original line Diff line number Diff line
<!--                                                                                   -->
<!--                                                                                   -->
<!-- -*- coding: utf-8 -*-                                                             -->
<!--                                                                                   -->
<!--  warden-map.html                                                                  -->
<!--                                                                                   -->
<!-- Copyright (C) 2016 Cesnet z.s.p.o                                                 -->
<!-- Use of this source is governed by a 3-clause BSD-style license, see LICENSE file. -->
<!--                                                                                   -->
<!--                                                                                   -->


<!DOCTYPE html>
<meta name="robots" content="noindex">
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Oswald&amp;subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="./css/warden-map.css"/>
<body>

<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./js/datamaps.world.min.js"></script>
<script src="./js/warden-map.js"></script>

<!--
<h2>Warden Map</h2>
<div id="tools">
  <button class="zoom-button" data-zoom="reset">&#x2302</button>
  <button class="zoom-button" data-zoom="out">-</button>
  <button class="zoom-button" data-zoom="in">+</button>
  <div id="zoom-info"></div>
</div>
-->
<div id="container"></div>
<div id="heading">Attacks, detected in CESNET network<br/>
SABU - Sharing and Analysis of Security Events
</div>
<div id="legend-box">
	<p><b>Reported to Warden right <i>now</i>.</b></p>
	<ul id="legend"></ul>
</div>

<!-- Draw datamap into id="container" -->
<script>new Datamap();</script>

</body>
</html>

packages/build-client.sh

deleted100755 → 0
+0 −98
Original line number Original line Diff line number Diff line
#!/bin/bash
#
# build-client.sh
#
# Copyright (C) 2011-2012 Cesnet z.s.p.o
#
# Use of this source is governed by a BSD-style license, see LICENSE file.

VERSION="1.2"

#-------------------------------------------------------------------------------
#				FUNCTIONS
#-------------------------------------------------------------------------------
err()
{
  echo "FAILED!"
  cat $err
  rm -rf $err $package $tar $sig
  echo
  echo "Build of $package package FAILED!!!"
  exit 1
}


#-------------------------------------------------------------------------------
#				MAIN
#-------------------------------------------------------------------------------

# edit when you build new package
version="2.2-beta"

package_name="warden-client"
package="${package_name}-${version}"
doc="${package}/${package_name}/doc"
etc="${package}/${package_name}/etc"
lib="${package}/${package_name}/lib"
var="${package}/${package_name}/var"
tar="${package}.tar.gz"
sig="${tar}.sig"
err="/tmp/${package}-err"

# make directory structure
echo "Building $package_name package version $version ..."
echo

echo -n "Building 'base' directory ... "
mkdir -p $package 2> $err || err
cp -R ../src/${package_name}/sh/* $package 2> $err || err
cp ../src/${package_name}/doc/CHANGELOG $package 2> $err || err
cp ../src/${package_name}/doc/INSTALL $package 2> $err || err
cp ../src/${package_name}/doc/LICENSE $package 2> $err || err
cp ../src/${package_name}/doc/README $package 2> $err || err
cp ../src/${package_name}/doc/README.cesnet $package 2> $err || err
echo "OK"


echo -n "Building '${doc}' directory ... "
mkdir -p $doc 2> $err || err
cp -R ../src/${package_name}/doc/* $doc 2> $err || err
echo "OK"


echo -n "Building '${etc}' directory ... "
mkdir -p $etc 2> $err || err
cp ../src/${package_name}/etc/package_version $etc 2> $err || err
echo "OK"


echo -n "Building '${lib}' directory ... "
mkdir -p $lib 2> $err || err
cp -R ../src/${package_name}/lib/*.pm $lib 2> $err || err
echo "OK"


echo -n "Building '${var}' directory ... "
mkdir -p $var 2> $err || err
echo "OK"


# create tarball
echo -n "Creating $tar tarball ... "
tar czf $tar $package 2> $err || err
echo "OK"


# create sign of tarball
echo -n "Creating $sig file ... "
sha1sum $tar > $sig 2> $err || err
echo "OK"


echo
echo "Building of $package package was SUCCESSFULL"

# cleanup section
rm -rf $package $err

exit 0

packages/build-server.sh

deleted100755 → 0
+0 −108
Original line number Original line Diff line number Diff line
#!/bin/bash
#
# build-server.sh
#
# Copyright (C) 2011-2012 Cesnet z.s.p.o
#
# Use of this source is governed by a BSD-style license, see LICENSE file.

VERSION="2.2"

err()
{
  echo "FAILED!"
  cat "$err"
  rm -f "$err" "$tar" "$sig"
  rm -rf "$package"
  echo
  echo "Build of $package package FAILED!!!"
  exit 1
}


#-------------------------------------------------------------------------------
#				MAIN
#-------------------------------------------------------------------------------

if [ -z "$1" ]; then
	echo "Usage: ${0##*/} <package_version_number>"
	echo
	echo "Example: ${0##*/} \"2.2\""
	exit 1
fi

package_name="warden-server"
package="${package_name}-$1"
bin="${package}/bin"
doc="${package}/doc"
etc="${package}/etc"
lib="${package}/lib"
sh="${package}/sh"
tar="${package}.tar.gz"
sig="${tar}.sig"
err="/tmp/${package}-err"

# make directory structure
echo "Building $package package..."
echo

echo -n "Building 'base' directory ... "
mkdir -p "$package" 2> "$err" || err
cp "../src/${package_name}/sh/install.sh" "$package" 2> "$err" || err
cp "../src/${package_name}/sh/update.sh" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/INSTALL" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/README" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/UPDATE" "$package" 2> "$err" || err
echo "OK"

echo -n "Building '${bin}' directory ... "
mkdir -p "$bin" 2> "$err" || err
cp -R "../src/${package_name}/bin/"* "$bin" 2> "$err" || err
echo "OK"

echo -n "Building '${doc}' directory ... "
mkdir -p "$doc" 2> "$err" || err
cp -R "../src/${package_name}/doc/"* "$doc" 2> "$err" || err
echo "OK"

echo -n "Building '${etc}' directory ... "
mkdir -p "$etc" 2> "$err" || err
cp "../src/${package_name}/etc/"* "$etc" 2> "$err" || err
rm -f "${etc}/"*.conf 2> "$err" || err
echo "OK"

echo -n "Building '${lib}' directory ... "
mkdir -p "$lib" 2> "$err" || err
cp -R "../src/${package_name}/lib/"* "$lib" 2> "$err" || err
rm -f "${lib}/"*.t 2> "$err" || err
echo "OK"

echo -n "Building '${sh}' directory ... "
mkdir -p "$sh" 2> "$err" || err
cp "../src/${package_name}/sh/uninstall.sh" "$sh" 2> "$err" || err
echo "OK"

echo -n "Creating MANIFEST file ... "
cd "$package" && find . -mindepth 2 -type f | sed 's/.tmpl//' | sed 's/.\///' > "doc/MANIFEST" && cd $OLDPWD || err
echo "OK"


# create tarball
echo -n "Creating $tar tarball ... "
tar czf "$tar" "$package" 2> "$err" || err
echo "OK"


#  create sign of tarball
echo -n "Creating $sig file ... "
sha1sum "$tar" > "$sig" 2> "$err" || err
echo "OK"


echo
echo "Building of $package package was SUCCESSFULL!!!"

# cleanup section
rm -rf "$package" "$err"

exit 0

packages/chck_modules_version.sh

deleted100755 → 0
+0 −24
Original line number Original line Diff line number Diff line
#!/bin/bash
#
# The script automatically obtain Perl modules and their local version
# in set directory (recursively)
#

if [[ -z $1 || ! -d $1 ]]; then
	echo "Usage: ${0##*/} <directory>"
	echo
	echo "Example: ${0##*/} ../src/warden-server/"
	exit 1
fi

modules_file="/tmp/warden-modules.txt"
sed '/^use [A-Z]/!d; /Warden/d' $(find $1 -type f) 2>/dev/null | cut -f 2 -d " " | sed 's/;//' | sort -u | \
while read module;
do
	perl -e "eval { require $module; }; if (\$@) { print \"$module: version not found\n\"; } else { print \"$module >= \$$module::VERSION\n\"}"
done

# cleanup section
rm -f "$modules_file"

exit 0

packages/warden-app-0.1.tar.gz

deleted100644 → 0
−11.5 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
7fba331d3678e8874c20d66af3992bbe90faabca  warden-app-0.1.tar.gz
−10.4 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
f04ba44e48b5d9efc754c2332362e2a82a86f387  warden-client-1.0.0.tar.gz
−22.3 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
2448a581f61e9169400de2c4d248d76319facfc1  warden-client-1.1.0.tar.gz
−15.4 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
623a7b5e610f024d5813befd496c966234998dca  warden-client-1.2.0.tar.gz
−18.4 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
c2d0cc933a689504f4146debbd6046dfd4773f7f  warden-client-2.0.0-beta.tar.gz
−18.6 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
9bca641d8c71f24a0010576fec2808a7ed055594  warden-client-2.0.0-beta2.tar.gz

packages/warden-client-2.0.tar.gz

deleted100644 → 0
−14.9 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
72dafef0ed1a625f11cda121abf3c2d970c26ca0  warden-client-2.0.tar.gz
−21.8 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
24cc18c69a7fdb6f59bc31bf00a046a396eae3ba  warden-client-2.1-beta.tar.gz

packages/warden-client-2.1.tar.gz

deleted100644 → 0
−21.9 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
79bcb17ca5b81df49c1c94b9b9ef83fecff31c69  warden-client-2.1.tar.gz
−24.6 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
6d750f5c16d1b3465279a24c03dd07c540f7bbdd  warden-server-0.1.0.tar.gz
−21.8 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
01bfc44ba12f04f1a56386e4efca8e626f1cdbd1  warden-server-2.0.0-beta.tar.gz

packages/warden-server-2.0.tar.gz

deleted100644 → 0
−19 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
9ad83d6d136358179d68c49255af0f426b564edc  warden-server-2.0.tar.gz
−23.9 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
3bf719d1f0887f7feb394aafc8a85b48a66e2498  warden-server-2.1-beta4.tar.gz
−23.5 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
e4e6cd82c07aa02f4a73aa37f5da13e7d04ab0fe  warden-server-2.1-beta5.tar.gz
−30.4 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
47f95f7e738cf5eb2d8faf3a98e7db6decb1c936  warden-server-2.1-beta6.tar.gz

packages/warden-server-2.1.tar.gz

deleted100644 → 0
−25.7 KiB

File deleted.

+0 −1
Original line number Original line Diff line number Diff line
b80714a0ba3ebddc46d0a05fea7593aed82fab05  warden-server-2.1.tar.gz

src/contrib/meta/README

deleted100644 → 0
+0 −11
Original line number Original line Diff line number Diff line
* customize wrapper's clown computing nodes selector
** set SERVER, IP, BASE (2x) variables in scripts
** http://meta.cesnet.cz/wiki/Pl%C3%A1novac%C3%AD_syst%C3%A9m_-_detailn%C3%AD_popis
* connect to any job submitter frontend (arda, skirit, ...)
** submit a job `qsub wtw-lenny-meta.sh`
** monitor it `qstat -u $USER`

* populate clients table
** set USER, PASS, DB (other/importMetaClients.sh)
** 'meta-nodes' must be in the same directory
** run;)
+0 −16
Original line number Original line Diff line number Diff line
#!/bin/bash

USER=""
PASS=""
DB="warden"

if [ -z $PASS ]; then
	MYSQL_CMD="mysql -u$USER $DB";
else
	MYSQL_CMD="mysql -u$USER -p$PASS $DB";
fi

for host in `cat meta-nodes`; do
	IP=`host $host | grep -v 'handle' | awk '{print $4}'`
	echo "INSERT INTO clients VALUES (NULL, '$host', now(),'automatic', 'test', 's', NULL, 'n', 'bruteforce', '$IP/32');" | $MYSQL_CMD
done 

src/contrib/meta/other/meta-nodes

deleted100644 → 0
+0 −802
Original line number Original line Diff line number Diff line
tarkil10-1.cesnet.cz
tarkil10-2.cesnet.cz
tarkil11-1.cesnet.cz
tarkil11-2.cesnet.cz
tarkil12-1.cesnet.cz
tarkil12-2.cesnet.cz
tarkil13-1.cesnet.cz
tarkil13-2.cesnet.cz
tarkil14-1.cesnet.cz
tarkil14-2.cesnet.cz
tarkil15-1.cesnet.cz
tarkil15-2.cesnet.cz
tarkil17-1.cesnet.cz
tarkil17-2.cesnet.cz
tarkil18-1.cesnet.cz
tarkil18-2.cesnet.cz
tarkil19-1.cesnet.cz
tarkil19-2.cesnet.cz
tarkil20-1.cesnet.cz
tarkil20-2.cesnet.cz
tarkil21-1.cesnet.cz
tarkil21-2.cesnet.cz
tarkil22-1.cesnet.cz
tarkil22-2.cesnet.cz
tarkil23-1.cesnet.cz
tarkil23-2.cesnet.cz
tarkil24-1.cesnet.cz
tarkil24-2.cesnet.cz
tarkil25-1.cesnet.cz
tarkil25-2.cesnet.cz
tarkil26-1.cesnet.cz
tarkil26-2.cesnet.cz
tarkil27-1.cesnet.cz
tarkil27-2.cesnet.cz
tarkil5-1.cesnet.cz
tarkil5-2.cesnet.cz
tarkil7-1.cesnet.cz
tarkil7-2.cesnet.cz
tarkil9-1.cesnet.cz
tarkil9-2.cesnet.cz
konos20-1.fav.zcu.cz
perian55-1.ncbr.muni.cz
skirit51-1.ics.muni.cz
skirit51-2.ics.muni.cz
skirit52-1.ics.muni.cz
skirit52-2.ics.muni.cz
skirit53-1.ics.muni.cz
skirit53-2.ics.muni.cz
skirit54-1.ics.muni.cz
skirit54-2.ics.muni.cz
skirit55-1.ics.muni.cz
skirit55-2.ics.muni.cz
skirit56-1.ics.muni.cz
skirit56-2.ics.muni.cz
skirit57-1.ics.muni.cz
skirit57-2.ics.muni.cz
skirit58-1.ics.muni.cz
skirit58-2.ics.muni.cz
skirit59-1.ics.muni.cz
skirit59-2.ics.muni.cz
skirit60-1.ics.muni.cz
skirit60-2.ics.muni.cz
skirit61-1.ics.muni.cz
skirit61-2.ics.muni.cz
skirit62-1.ics.muni.cz
skirit62-2.ics.muni.cz
skirit63-1.ics.muni.cz
skirit63-2.ics.muni.cz
skirit64-1.ics.muni.cz
skirit64-2.ics.muni.cz
skirit65-1.ics.muni.cz
skirit65-2.ics.muni.cz
skirit67-1.ics.muni.cz
skirit67-2.ics.muni.cz
skirit68-1.ics.muni.cz
skirit68-2.ics.muni.cz
skirit69-1.ics.muni.cz
skirit69-2.ics.muni.cz
skirit70-1.ics.muni.cz
skirit70-2.ics.muni.cz
skirit71-1.ics.muni.cz
skirit71-2.ics.muni.cz
skirit72-1.ics.muni.cz
skirit72-2.ics.muni.cz
skirit73-1.ics.muni.cz
skirit73-2.ics.muni.cz
skirit74-1.ics.muni.cz
skirit74-2.ics.muni.cz
skirit75-1.ics.muni.cz
skirit75-2.ics.muni.cz
skirit76-1.ics.muni.cz
skirit76-2.ics.muni.cz
skirit77-1.ics.muni.cz
skirit77-2.ics.muni.cz
skirit78-1.ics.muni.cz
skirit78-2.ics.muni.cz
skirit79-1.ics.muni.cz
skirit79-2.ics.muni.cz
skirit84-1.ics.muni.cz
skirit84-2.ics.muni.cz
perian10-1.ncbr.muni.cz
perian10-2.ncbr.muni.cz
perian11-1.ncbr.muni.cz
perian11-2.ncbr.muni.cz
perian1-1.ncbr.muni.cz
perian12-1.ncbr.muni.cz
perian12-2.ncbr.muni.cz
perian1-2.ncbr.muni.cz
perian13-1.ncbr.muni.cz
perian13-2.ncbr.muni.cz
perian14-1.ncbr.muni.cz
perian14-2.ncbr.muni.cz
perian15-1.ncbr.muni.cz
perian15-2.ncbr.muni.cz
perian16-1.ncbr.muni.cz
perian16-2.ncbr.muni.cz
perian17-1.ncbr.muni.cz
perian17-2.ncbr.muni.cz
perian18-1.ncbr.muni.cz
perian18-2.ncbr.muni.cz
perian19-1.ncbr.muni.cz
perian19-2.ncbr.muni.cz
perian20-1.ncbr.muni.cz
perian20-2.ncbr.muni.cz
perian21-1.ncbr.muni.cz
perian21-2.ncbr.muni.cz
perian2-1.ncbr.muni.cz
perian22-1.ncbr.muni.cz
perian22-2.ncbr.muni.cz
perian2-2.ncbr.muni.cz
perian23-1.ncbr.muni.cz
perian23-2.ncbr.muni.cz
perian24-1.ncbr.muni.cz
perian24-2.ncbr.muni.cz
perian25-1.ncbr.muni.cz
perian25-2.ncbr.muni.cz
perian26-1.ncbr.muni.cz
perian26-2.ncbr.muni.cz
perian27-1.ncbr.muni.cz
perian27-2.ncbr.muni.cz
perian28-1.ncbr.muni.cz
perian28-2.ncbr.muni.cz
perian29-1.ncbr.muni.cz
perian29-2.ncbr.muni.cz
perian30-1.ncbr.muni.cz
perian30-2.ncbr.muni.cz
perian31-1.ncbr.muni.cz
perian31-2.ncbr.muni.cz
perian3-1.ncbr.muni.cz
perian32-1.ncbr.muni.cz
perian32-2.ncbr.muni.cz
perian3-2.ncbr.muni.cz
perian33-1.ncbr.muni.cz
perian33-2.ncbr.muni.cz
perian34-1.ncbr.muni.cz
perian34-2.ncbr.muni.cz
perian35-1.ncbr.muni.cz
perian35-2.ncbr.muni.cz
perian36-1.ncbr.muni.cz
perian36-2.ncbr.muni.cz
perian37-1.ncbr.muni.cz
perian37-2.ncbr.muni.cz
perian38-1.ncbr.muni.cz
perian38-2.ncbr.muni.cz
perian39-1.ncbr.muni.cz
perian39-2.ncbr.muni.cz
perian40-1.ncbr.muni.cz
perian40-2.ncbr.muni.cz
perian4-1.ncbr.muni.cz
perian4-2.ncbr.muni.cz
perian5-1.ncbr.muni.cz
perian5-2.ncbr.muni.cz
perian6-1.ncbr.muni.cz
perian6-2.ncbr.muni.cz
perian7-1.ncbr.muni.cz
perian7-2.ncbr.muni.cz
perian8-1.ncbr.muni.cz
perian8-2.ncbr.muni.cz
perian9-1.ncbr.muni.cz
perian9-2.ncbr.muni.cz
loslab1-1.ics.muni.cz
loslab1-2.ics.muni.cz
loslab2-1.ics.muni.cz
loslab2-2.ics.muni.cz
loslab3-1.ics.muni.cz
loslab3-2.ics.muni.cz
loslab4-1.ics.muni.cz
loslab4-2.ics.muni.cz
loslab5-1.ics.muni.cz
loslab5-2.ics.muni.cz
loslab6-1.ics.muni.cz
loslab6-2.ics.muni.cz
manwe3.ics.muni.cz
manwe4.ics.muni.cz
loslab1.ics.muni.cz
loslab2.ics.muni.cz
loslab3.ics.muni.cz
loslab4.ics.muni.cz
loslab5.ics.muni.cz
loslab6.ics.muni.cz
perian55-2.ncbr.muni.cz
skirit50.ics.muni.cz
skirit51.ics.muni.cz
skirit52.ics.muni.cz
skirit53.ics.muni.cz
skirit54.ics.muni.cz
skirit55.ics.muni.cz
skirit56.ics.muni.cz
skirit57.ics.muni.cz
skirit58.ics.muni.cz
skirit59.ics.muni.cz
skirit60.ics.muni.cz
skirit61.ics.muni.cz
skirit62.ics.muni.cz
skirit63.ics.muni.cz
skirit64.ics.muni.cz
skirit65.ics.muni.cz
skirit66.ics.muni.cz
skirit67.ics.muni.cz
skirit68.ics.muni.cz
skirit69.ics.muni.cz
skirit70.ics.muni.cz
skirit71.ics.muni.cz
skirit72.ics.muni.cz
skirit73.ics.muni.cz
skirit74.ics.muni.cz
skirit75.ics.muni.cz
skirit76.ics.muni.cz
skirit77.ics.muni.cz
skirit78.ics.muni.cz
skirit79.ics.muni.cz
skirit80.ics.muni.cz
skirit84.ics.muni.cz
perian10.ncbr.muni.cz
perian11.ncbr.muni.cz
perian12.ncbr.muni.cz
perian13.ncbr.muni.cz
perian14.ncbr.muni.cz
perian15.ncbr.muni.cz
perian16.ncbr.muni.cz
perian17.ncbr.muni.cz
perian18.ncbr.muni.cz
perian19.ncbr.muni.cz
perian1.ncbr.muni.cz
perian20.ncbr.muni.cz
perian21.ncbr.muni.cz
perian22.ncbr.muni.cz
perian23.ncbr.muni.cz
perian24.ncbr.muni.cz
perian25.ncbr.muni.cz
perian26.ncbr.muni.cz
perian27.ncbr.muni.cz
perian28.ncbr.muni.cz
perian29.ncbr.muni.cz
perian2.ncbr.muni.cz
perian30.ncbr.muni.cz
perian31.ncbr.muni.cz
perian32.ncbr.muni.cz
perian33.ncbr.muni.cz
perian34.ncbr.muni.cz
perian35.ncbr.muni.cz
perian36.ncbr.muni.cz
perian37.ncbr.muni.cz
perian38.ncbr.muni.cz
perian39.ncbr.muni.cz
perian3.ncbr.muni.cz
perian40.ncbr.muni.cz
perian4.ncbr.muni.cz
perian5.ncbr.muni.cz
perian6.ncbr.muni.cz
perian7.ncbr.muni.cz
perian8.ncbr.muni.cz
perian9.ncbr.muni.cz
tarkil10.cesnet.cz
tarkil11.cesnet.cz
tarkil12.cesnet.cz
tarkil13.cesnet.cz
tarkil14.cesnet.cz
tarkil15.cesnet.cz
tarkil17.cesnet.cz
tarkil18.cesnet.cz
tarkil19.cesnet.cz
tarkil20.cesnet.cz
tarkil21.cesnet.cz
tarkil22.cesnet.cz
tarkil23.cesnet.cz
tarkil24.cesnet.cz
tarkil25.cesnet.cz
tarkil26.cesnet.cz
tarkil27.cesnet.cz
tarkil5.cesnet.cz
tarkil7.cesnet.cz
tarkil9.cesnet.cz
konos10.fav.zcu.cz
konos1.fav.zcu.cz
konos2.fav.zcu.cz
konos3.fav.zcu.cz
konos4.fav.zcu.cz
konos5.fav.zcu.cz
konos6.fav.zcu.cz
konos7.fav.zcu.cz
konos8.fav.zcu.cz
konos9.fav.zcu.cz
tarkil8-1.cesnet.cz
tarkil8-2.cesnet.cz
tarkil8.cesnet.cz
alela1-1.feec.vutbr.cz
alela1-2.feec.vutbr.cz
alela1.feec.vutbr.cz
alela10-1.feec.vutbr.cz
alela10-2.feec.vutbr.cz
alela10.feec.vutbr.cz
alela11-1.feec.vutbr.cz
alela11-2.feec.vutbr.cz
alela11.feec.vutbr.cz
alela12-1.feec.vutbr.cz
alela12-2.feec.vutbr.cz
alela12.feec.vutbr.cz
alela2-1.feec.vutbr.cz
alela2-2.feec.vutbr.cz
alela2.feec.vutbr.cz
alela3-1.feec.vutbr.cz
alela3-2.feec.vutbr.cz
alela3.feec.vutbr.cz
alela4-1.feec.vutbr.cz
alela4-2.feec.vutbr.cz
alela4.feec.vutbr.cz
alela5-1.feec.vutbr.cz
alela5-2.feec.vutbr.cz
alela5.feec.vutbr.cz
alela6-1.feec.vutbr.cz
alela6-2.feec.vutbr.cz
alela6.feec.vutbr.cz
alela7-1.feec.vutbr.cz
alela7-2.feec.vutbr.cz
alela7.feec.vutbr.cz
alela8-1.feec.vutbr.cz
alela8-2.feec.vutbr.cz
alela8.feec.vutbr.cz
alela9-1.feec.vutbr.cz
alela9-2.feec.vutbr.cz
alela9.feec.vutbr.cz
konos15-1.fav.zcu.cz
konos15-2.fav.zcu.cz
konos15.fav.zcu.cz
konos17-1.fav.zcu.cz
konos17-2.fav.zcu.cz
konos17.fav.zcu.cz
konos18-1.fav.zcu.cz
konos18-2.fav.zcu.cz
konos18.fav.zcu.cz
konos20-2.fav.zcu.cz
konos20.fav.zcu.cz
konos22-1.fav.zcu.cz
konos22-2.fav.zcu.cz
konos22.fav.zcu.cz
konos27-1.fav.zcu.cz
konos27-2.fav.zcu.cz
konos27.fav.zcu.cz
konos30-1.fav.zcu.cz
konos30-2.fav.zcu.cz
konos30.fav.zcu.cz
konos34-1.fav.zcu.cz
konos34-2.fav.zcu.cz
konos34.fav.zcu.cz
hermes05-1.prf.jcu.cz
hermes05-2.prf.jcu.cz
hermes05.prf.jcu.cz
orca1-1.ics.muni.cz
orca1-2.ics.muni.cz
orca1.ics.muni.cz
orca10-1.ics.muni.cz
orca10-2.ics.muni.cz
orca10.ics.muni.cz
orca11-1.ics.muni.cz
orca11-2.ics.muni.cz
orca11.ics.muni.cz
orca12-1.ics.muni.cz
orca12-2.ics.muni.cz
orca12.ics.muni.cz
orca13-1.ics.muni.cz
orca13-2.ics.muni.cz
orca13.ics.muni.cz
orca14-1.ics.muni.cz
orca14-2.ics.muni.cz
orca14.ics.muni.cz
orca15-1.ics.muni.cz
orca15-2.ics.muni.cz
orca15.ics.muni.cz
orca16-1.ics.muni.cz
orca16-2.ics.muni.cz
orca16.ics.muni.cz
orca17-1.ics.muni.cz
orca17-2.ics.muni.cz
orca17.ics.muni.cz
orca18-1.ics.muni.cz
orca18-2.ics.muni.cz
orca18.ics.muni.cz
orca2-1.ics.muni.cz
orca2-2.ics.muni.cz
orca2.ics.muni.cz
orca3-1.ics.muni.cz
orca3-2.ics.muni.cz
orca3.ics.muni.cz
orca5-1.ics.muni.cz
orca5-2.ics.muni.cz
orca5.ics.muni.cz
orca6-1.ics.muni.cz
orca6-2.ics.muni.cz
orca6.ics.muni.cz
orca7-1.ics.muni.cz
orca7-2.ics.muni.cz
orca7.ics.muni.cz
orca8-1.ics.muni.cz
orca8-2.ics.muni.cz
orca8.ics.muni.cz
orca9-1.ics.muni.cz
orca9-2.ics.muni.cz
orca9.ics.muni.cz
quark11-1.video.muni.cz
quark11-2.video.muni.cz
quark11.video.muni.cz
quark12-1.video.muni.cz
quark12-2.video.muni.cz
quark12.video.muni.cz
quark13-1.video.muni.cz
quark13-2.video.muni.cz
quark13.video.muni.cz
quark14-1.video.muni.cz
quark14-2.video.muni.cz
quark14.video.muni.cz
quark15-1.video.muni.cz
quark15-2.video.muni.cz
quark15.video.muni.cz
quark6-1.video.muni.cz
quark6-2.video.muni.cz
quark6.video.muni.cz
quark7-1.video.muni.cz
quark7-2.video.muni.cz
quark7.video.muni.cz
hermes07-1.prf.jcu.cz
hermes07-2.prf.jcu.cz
hermes07.prf.jcu.cz
hermes08-1.prf.jcu.cz
hermes08-2.prf.jcu.cz
hermes08.prf.jcu.cz
hermes09-1.prf.jcu.cz
hermes09-2.prf.jcu.cz
hermes09.prf.jcu.cz
hermes10-1.prf.jcu.cz
hermes10-2.prf.jcu.cz
hermes10.prf.jcu.cz
hermes03-1.prf.jcu.cz
hermes03-2.prf.jcu.cz
hermes03.prf.jcu.cz
konos37-1.fav.zcu.cz
konos37-2.fav.zcu.cz
konos37.fav.zcu.cz
tarkil1-1.cesnet.cz
tarkil1-2.cesnet.cz
tarkil1.cesnet.cz
nympha1-1.zcu.cz
nympha1-2.zcu.cz
nympha1.zcu.cz
nympha2-1.zcu.cz
nympha2-2.zcu.cz
nympha2.zcu.cz
nympha3-1.zcu.cz
nympha3-2.zcu.cz
nympha3.zcu.cz
nympha4-1.zcu.cz
nympha4-2.zcu.cz
nympha4.zcu.cz
nympha5-1.zcu.cz
nympha5-2.zcu.cz
nympha5.zcu.cz
nympha6-1.zcu.cz
nympha6-2.zcu.cz
nympha6.zcu.cz
nympha7-1.zcu.cz
nympha7-2.zcu.cz
nympha7.zcu.cz
nympha8-1.zcu.cz
nympha8-2.zcu.cz
nympha8.zcu.cz
nympha9-1.zcu.cz
nympha9-2.zcu.cz
nympha9.zcu.cz
hermes06-1.prf.jcu.cz
hermes06-2.prf.jcu.cz
hermes06.prf.jcu.cz
quark9-1.video.muni.cz
quark9-2.video.muni.cz
quark9.video.muni.cz
konos16-1.fav.zcu.cz
konos16-2.fav.zcu.cz
konos16.fav.zcu.cz
konos24-1.fav.zcu.cz
konos24-2.fav.zcu.cz
konos24.fav.zcu.cz
konos26-1.fav.zcu.cz
konos26-2.fav.zcu.cz
konos26.fav.zcu.cz
konos36-1.fav.zcu.cz
konos36-2.fav.zcu.cz
konos36.fav.zcu.cz
nympha10-1.zcu.cz
nympha10-2.zcu.cz
nympha10.zcu.cz
tarkil16-1.cesnet.cz
tarkil16-2.cesnet.cz
tarkil16.cesnet.cz
tarkil2-1.cesnet.cz
tarkil2-2.cesnet.cz
tarkil2.cesnet.cz
ajax.zcu.cz
eru1.ruk.cuni.cz
eru2.ruk.cuni.cz
hermes02-1.prf.jcu.cz
hermes02-2.prf.jcu.cz
hermes02.prf.jcu.cz
nympha12-1.zcu.cz
nympha12-2.zcu.cz
nympha12.zcu.cz
nympha13-1.zcu.cz
nympha13-2.zcu.cz
nympha13.zcu.cz
nympha15-1.zcu.cz
nympha15-2.zcu.cz
nympha15.zcu.cz
nympha16-1.zcu.cz
nympha16-2.zcu.cz
nympha16.zcu.cz
nympha17-1.zcu.cz
nympha17-2.zcu.cz
nympha17.zcu.cz
nympha19-1.zcu.cz
nympha19-2.zcu.cz
nympha19.zcu.cz
quark10-1.video.muni.cz
quark10-2.video.muni.cz
quark10.video.muni.cz
quark8-1.video.muni.cz
quark8-2.video.muni.cz
quark8.video.muni.cz
hermes11-1.prf.jcu.cz
hermes11-2.prf.jcu.cz
hermes11.prf.jcu.cz
orca4-1.ics.muni.cz
orca4-2.ics.muni.cz
orca4.ics.muni.cz
hermes01-1.prf.jcu.cz
hermes01-2.prf.jcu.cz
hermes01.prf.jcu.cz
quark16-1.video.muni.cz
quark16-2.video.muni.cz
quark16.video.muni.cz
nympha11-1.zcu.cz
nympha11-2.zcu.cz
nympha11.zcu.cz
nympha18-1.zcu.cz
nympha18-2.zcu.cz
nympha18.zcu.cz
tarkil3-1.cesnet.cz
tarkil3-2.cesnet.cz
tarkil3.cesnet.cz
tarkil28-1.cesnet.cz
tarkil28-2.cesnet.cz
tarkil28.cesnet.cz
manwe1.ics.muni.cz
manwe2.ics.muni.cz
manwe5.ics.muni.cz
manwe6.ics.muni.cz
manwe7.ics.muni.cz
perian55.ncbr.muni.cz
skirit80-1.ics.muni.cz
tarkil4-1.cesnet.cz
tarkil4-2.cesnet.cz
tarkil4.cesnet.cz
tarkil6-1.cesnet.cz
tarkil6-2.cesnet.cz
tarkil6.cesnet.cz
nympha14-1.zcu.cz
nympha14-2.zcu.cz
nympha14.zcu.cz
skirit83.ics.muni.cz
skirit83-1.ics.muni.cz
skirit83-2.ics.muni.cz
luna3.fzu.cz
apollo1.fzu.cz
apollo2.fzu.cz
apollo3.fzu.cz
perian56-1.ncbr.muni.cz
perian56-2.ncbr.muni.cz
perian56.ncbr.muni.cz
perian41-1.ncbr.muni.cz
perian41-2.ncbr.muni.cz
perian41.ncbr.muni.cz
perian42-1.ncbr.muni.cz
perian42-2.ncbr.muni.cz
perian42.ncbr.muni.cz
perian43-1.ncbr.muni.cz
perian43-2.ncbr.muni.cz
perian43.ncbr.muni.cz
perian44-1.ncbr.muni.cz
perian44-2.ncbr.muni.cz
perian44.ncbr.muni.cz
perian45-1.ncbr.muni.cz
perian45-2.ncbr.muni.cz
perian45.ncbr.muni.cz
perian46-1.ncbr.muni.cz
perian46-2.ncbr.muni.cz
perian46.ncbr.muni.cz
perian47-1.ncbr.muni.cz
perian47-2.ncbr.muni.cz
perian47.ncbr.muni.cz
perian48-1.ncbr.muni.cz
perian48-2.ncbr.muni.cz
perian48.ncbr.muni.cz
perian49-1.ncbr.muni.cz
perian49-2.ncbr.muni.cz
perian49.ncbr.muni.cz
perian50-1.ncbr.muni.cz
perian50-2.ncbr.muni.cz
perian50.ncbr.muni.cz
perian51-1.ncbr.muni.cz
perian51-2.ncbr.muni.cz
perian51.ncbr.muni.cz
perian52-1.ncbr.muni.cz
perian52-2.ncbr.muni.cz
perian52.ncbr.muni.cz
perian53-1.ncbr.muni.cz
perian53-2.ncbr.muni.cz
perian53.ncbr.muni.cz
perian54-1.ncbr.muni.cz
perian54-2.ncbr.muni.cz
perian54.ncbr.muni.cz
skirit80-2.ics.muni.cz
minos1.zcu.cz
minos1-1.zcu.cz
minos1-2.zcu.cz
minos2.zcu.cz
minos2-1.zcu.cz
minos2-2.zcu.cz
minos3.zcu.cz
minos3-1.zcu.cz
minos3-2.zcu.cz
minos4.zcu.cz
minos4-1.zcu.cz
minos4-2.zcu.cz
minos5.zcu.cz
minos5-1.zcu.cz
minos5-2.zcu.cz
minos6.zcu.cz
minos6-1.zcu.cz
minos6-2.zcu.cz
minos7.zcu.cz
minos7-1.zcu.cz
minos7-2.zcu.cz
minos8.zcu.cz
minos8-1.zcu.cz
minos8-2.zcu.cz
minos9.zcu.cz
minos9-1.zcu.cz
minos9-2.zcu.cz
minos10.zcu.cz
minos10-1.zcu.cz
minos10-2.zcu.cz
minos11.zcu.cz
minos11-1.zcu.cz
minos11-2.zcu.cz
minos12.zcu.cz
minos12-1.zcu.cz
minos12-2.zcu.cz
minos13.zcu.cz
minos13-1.zcu.cz
minos13-2.zcu.cz
minos14.zcu.cz
minos14-1.zcu.cz
minos14-2.zcu.cz
minos15.zcu.cz
minos15-1.zcu.cz
minos15-2.zcu.cz
minos16.zcu.cz
minos16-1.zcu.cz
minos16-2.zcu.cz
minos17.zcu.cz
minos17-1.zcu.cz
minos17-2.zcu.cz
minos18.zcu.cz
minos18-1.zcu.cz
minos18-2.zcu.cz
minos19.zcu.cz
minos19-1.zcu.cz
minos19-2.zcu.cz
minos20.zcu.cz
minos20-1.zcu.cz
minos20-2.zcu.cz
minos21.zcu.cz
minos21-1.zcu.cz
minos21-2.zcu.cz
minos22.zcu.cz
minos22-1.zcu.cz
minos22-2.zcu.cz
minos23.zcu.cz
minos23-1.zcu.cz
minos23-2.zcu.cz
minos24.zcu.cz
minos24-1.zcu.cz
minos24-2.zcu.cz
minos25.zcu.cz
minos25-1.zcu.cz
minos25-2.zcu.cz
minos26.zcu.cz
minos26-1.zcu.cz
minos26-2.zcu.cz
minos27.zcu.cz
minos27-1.zcu.cz
minos27-2.zcu.cz
minos28.zcu.cz
minos28-1.zcu.cz
minos28-2.zcu.cz
minos29.zcu.cz
minos29-1.zcu.cz
minos29-2.zcu.cz
minos30.zcu.cz
minos30-1.zcu.cz
minos30-2.zcu.cz
minos31.zcu.cz
minos31-1.zcu.cz
minos31-2.zcu.cz
minos32.zcu.cz
minos32-1.zcu.cz
minos32-2.zcu.cz
minos33.zcu.cz
minos33-1.zcu.cz
minos33-2.zcu.cz
minos34.zcu.cz
minos34-1.zcu.cz
minos34-2.zcu.cz
minos35.zcu.cz
minos35-1.zcu.cz
minos35-2.zcu.cz
minos36.zcu.cz
minos36-1.zcu.cz
minos36-2.zcu.cz
minos37.zcu.cz
minos37-1.zcu.cz
minos37-2.zcu.cz
minos38.zcu.cz
minos38-1.zcu.cz
minos38-2.zcu.cz
minos39.zcu.cz
minos39-1.zcu.cz
minos39-2.zcu.cz
minos40.zcu.cz
minos40-1.zcu.cz
minos40-2.zcu.cz
minos41.zcu.cz
minos41-1.zcu.cz
minos41-2.zcu.cz
minos42.zcu.cz
minos42-1.zcu.cz
minos42-2.zcu.cz
minos43.zcu.cz
minos43-1.zcu.cz
minos43-2.zcu.cz
minos44.zcu.cz
minos44-1.zcu.cz
minos44-2.zcu.cz
minos45.zcu.cz
minos45-1.zcu.cz
minos45-2.zcu.cz
minos46.zcu.cz
minos46-1.zcu.cz
minos46-2.zcu.cz
minos47.zcu.cz
minos47-1.zcu.cz
minos47-2.zcu.cz
minos48.zcu.cz
minos48-1.zcu.cz
minos48-2.zcu.cz
minos49.zcu.cz
minos49-1.zcu.cz
minos49-2.zcu.cz
skirit66-1.ics.muni.cz
skirit66-2.ics.muni.cz
luna1.fzu.cz
mandos1.ics.muni.cz
mandos2.ics.muni.cz
mandos3.ics.muni.cz
mandos4.ics.muni.cz
mandos5.ics.muni.cz
mandos6.ics.muni.cz
mandos7.ics.muni.cz
mandos8.ics.muni.cz
mandos9.ics.muni.cz
mandos10.ics.muni.cz
mandos11.ics.muni.cz
mandos12.ics.muni.cz
mandos13.ics.muni.cz
mandos14.ics.muni.cz
+0 −15
Original line number Original line Diff line number Diff line
#!/bin/bash
#Logovatko poctu prenesenych zprav na Warden server a vytizeni serveru


USER=root
PASS=
DB=warden
INT=1

QUERY="SELECT NOW(), COUNT( id ), COUNT(DISTINCT(note)) FROM events WHERE received > DATE_SUB(UTC_TIMESTAMP(), INTERVAL $INT MINUTE) AND service='test';"

M_OUT=`echo $QUERY | mysql -s -u$USER -p"$PASS" $DB`
U_OUT=`uptime | awk '{print $11}'`
RET="${M_OUT} ${U_OUT%?}"
echo $RET
−1.2 MiB

File deleted.

+0 −38
Original line number Original line Diff line number Diff line
#!/bin/bash

#IP serveru 
SERVER=""
PORT=""

#Cesta ke scriptum a zdrojakum, typicky AFS, napr. /afs/zcu.cz/users/v/vomacka/public/wardentest
BASE=""

HNAME=`hostname -f`

# STAGEIN
WDIR="/scratch/${PBS_O_LOGNAME}/wardentest.$$"
mkdir -p $WDIR || exit 1
cd $WDIR

tar xzf $BASE/warden-client-meta.tgz 
perl -pi -e "s#\[path\]#$WDIR#" performance-sender.pm
perl -pi -e "s#\[path\]#$WDIR#" etc/warden-client.conf
perl -pi -e "s#\[server\]#$SERVER#" etc/warden-client.conf
perl -pi -e "s#\[port\]#$PORT#" etc/warden-client.conf

openssl req -new -nodes -keyform PEM -outform PEM -config ./ca/openssl.cnf -keyout ./ca/server-key.pem -out ./ca/server.csr -subj "/CN=$HNAME" -days 365 
openssl ca -batch -keyform PEM -passin pass:test -name client_ca -config ./ca/openssl.cnf -out ./ca/server-cert.pem -infiles ./ca/server.csr

# JOB
for i in `seq 1 1000`; do 
./performance-sender.pm test 10 &> /dev/null
done

date

# STAGEOUT
#cp p1.log $BASE/output-p1.log.$PBS_JOBID.$HNAME
#cp p2.log $BASE/output-p2.log.$PBS_JOBID.$HNAME
cd /tmp
rm -rf $WDIR
+0 −28
Original line number Original line Diff line number Diff line
#!/bin/bash
#PBS -N wtw-lenny.sh
#PBS -q short
#PBS -l nodes=1:ppn=1:^cl_luna
#PBS -j oe
#PBS -m abe
#
# describtion from 'man qsub':
# -N ... declares a name for the job.  The name specified may be up to and including 15 characters in  length.   It
#        must consist of printable, non white space characters with the first character alphabetic.
# -q ... defines the destination of the job (queue)
# -l ... defines  the  resources that are required by the job
# -j oe ... standard error stream of the job will be merged with the standard output stream
# -m ace ...  mail is sent anytime

#in file name of which can be found in variable PBS_NODEFILE, is list of allocated machines
echo '***PBS_NODEFILE***START*******'
cat $PBS_NODEFILE
echo '***PBS_NODEFILE***END*********'

#Cesta ke scriptum a zdrojakum, typicky AFS, napr. /afs/zcu.cz/users/v/vomacka/public/wardentest
BASE=""
cd $BASE || exit 1

# spusti dany prikaz na vsech pridelenych strojich
pbsdsh -o -- bash ${BASE}/wardentest-lenny-meta.sh

+0 −52
Original line number Original line Diff line number Diff line
package DNSblacklist;
use strict;
use warnings;
use Data::Dumper;

my  %CONSTANTS =    (
                       target      => "127.0.0.2",
                       outputfile  => "tmp/blacklist.csv",
                       threshold   => 10,
                       excludedip  => [],
                       eventtype   => [],
                       maxage      => "1D",
                       ttl         => "3600",
                       zone        => "@",
                       dns         => "dns.example.com",
                       hostmaster  => "hostmaster\@example.com",
                       refresh     => "1800    ; refresh (30 minutes)",
                       retry       => "600     ; retry (10 minutes)",
                       expire      => "1209600 ; expire (2 weeks)",
                       minimum     => "86400   ; minimum (1 day)",
                     );

my %FORMAT   =      (   maxage     => qr/\d+[hdmHDM]/, );

sub run {
    my (undef, $modprefix, $cfg, $dbh, $db_engine) = @_;
    
    my $v = Constants::mergeConfigs($cfg, $modprefix, \%CONSTANTS, \%FORMAT);

    my $eventtype_query = DB::joinIN("type", \@{$v->{'eventtype'}});
    my $excluded_query  = DB::joinNotIN("source", \@{$v->{'excludedip'}});

    my $condition = substr($excluded_query . $eventtype_query, 0, -5);
    my @columns= ("source", "note");
    my @params = ($condition, DB::getOldDataDB($db_engine, "NEWER", $v->{'maxage'}));
    my $query = DB::getQueryCondThreshold($db_engine, "events", \@columns, \@params, $v->{'threshold'});

    my @rows = Utils::fetchall_array_hashref($dbh, $query);

    my ($sec, $min, $hr, $day, $mon, $year) = localtime;
    
    $v->{'serial'} = sprintf("%02d%02d%02d%02d%02d", $year - 100 , $mon + 1, $day,  $hr, $min); 
    $v->{'hostmaster'} =~ s/\@/\./;

    sub header { my $v = shift; return "\$ORIGIN .\n\$TTL $v->{'ttl'}\n$v->{'zone'}\t\t\t\t\t\tIN\tSOA\t$v->{'dns'}. $v->{'hostmaster'}. (\n\t\t\t\t\t\t\t\t$v->{'serial'} ; serial\n\t\t\t\t\t\t\t\t$v->{'refresh'}\n\t\t\t\t\t\t\t\t$v->{'retry'}\n\t\t\t\t\t\t\t\t$v->{'expire'}\n\t\t\t\t\t\t\t\t$v->{'minimum'}\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tNS\t$v->{'dns'}.\n"; };
 
    sub record { my ($r, $v) = @_; $r->{'note'} = "" if !defined $r->{'note'};  return ";" . "$r->{'source'}\n" . join(".", reverse( split(/\./, $r->{'source'}))) . "\t\tIN\t\tA\t$v->{'target'}\n\t\t\t\t\tIN\t\tTXT\t\"$r->{'note'}\"\n"; }; 

    my $ret = Utils::generateOutput($v->{'outputfile'}, \@rows, \&header, \&record, undef, $v);
    return $ret;
}
1;
+0 −36
Original line number Original line Diff line number Diff line
package IPblacklist;
use strict;
use warnings;
use Data::Dumper;

my %CONSTANTS =    (
                       outputfile  => "tmp/blacklist.csv",
                       threshold   => 200,
                       excludedip  => [],
                       eventtype   => [],
                       maxage      => "1D",
                    );

my %FORMAT   =      (  maxage     => qr/\d+[hdmHDM]/, );


sub run {
    my (undef, $modprefix, $cfg, $dbh, $db_engine) = @_;
    my $v = Constants::mergeConfigs($cfg, $modprefix, \%CONSTANTS, \%FORMAT);

    my $eventtype_query = DB::joinIN("type", \@{$v->{'eventtype'}});
    my $excluded_query  = DB::joinNotIN("source", \@{$v->{'excludedip'}});

    my $condition = substr($excluded_query . $eventtype_query, 0, -5);
    my @columns= ("source");
    my @params = ($condition, DB::getOldDataDB($db_engine, "NEWER", $v->{'maxage'}));
    my $query = DB::getQueryCondThreshold($db_engine, "events", \@columns, \@params, $v->{'threshold'});

    my @rows = Utils::fetchall_array_hashref($dbh, $query);

    sub record { my $r = shift; return "$r->{'source'},\n"; };
    
    my $ret = Utils::generateOutput($v->{'outputfile'}, \@rows, undef, \&record, undef, $v);
    return $ret;
}
1;
+0 −40
Original line number Original line Diff line number Diff line
package IPset;
use strict;
use warnings;
use Data::Dumper;

my %CONSTANTS =    (
                        enabled    =>  "no",
                        outputfile =>  "tmp/ipset.txt",
                        threshold  =>  250,
                        excludedip =>  [],
                        eventtype  =>  [],
                        setname  =>  "BLOCK",
                        maxage     =>  "1D",
                     );

my %FORMAT   =      (   maxage     => qr/\d+[hdmHDM]/, logging  => qr/enable|disable/,);

sub run {
    my (undef, $modprefix, $cfg, $dbh, $db_engine) = @_;
   
    my $v = Constants::mergeConfigs($cfg, $modprefix, \%CONSTANTS, \%FORMAT);
    
    my $eventtype_query = DB::joinIN("type", \@{$v->{'eventtype'}});
    my $excluded_query  = DB::joinNotIN("source", \@{$v->{'excludedip'}});

    my $condition = substr($excluded_query . $eventtype_query, 0, -5);
    my @columns= ("source");
    my @params = ($condition, DB::getOldDataDB($db_engine, "NEWER", $v->{'maxage'}));
    my $query = DB::getQueryCondThreshold($db_engine, "events", \@columns, \@params, $v->{'threshold'});

    my @rows = Utils::fetchall_array_hashref($dbh, $query);

    sub header { my $v = shift; return "create $v->{'setname'}_tmp hash:ip\n"; };
    sub record { my ($r, $v) = @_; return "add $v->{'setname'}_tmp $r->{'source'}\n" if ($r->{'source'}=~/\d+\.\d+\.\d+\.\d+/); };
    sub footer { my ($v) = @_; return "swap $v->{'setname'}_tmp $v->{'setname'}\ndestroy $v->{'setname'}_tmp\nquit\n"; };

    my $ret = Utils::generateOutput($v->{'outputfile'}, \@rows, \&header, \&record, \&footer, $v);
    return $ret;
}
1;
+0 −40
Original line number Original line Diff line number Diff line
package IPtables;
use strict;
use warnings;
use Data::Dumper;

my %CONSTANTS =    (
                        enabled    =>  "no",
                        outputfile =>  "tmp/iptables.txt",
                        threshold  =>  250,
                        excludedip =>  [],
                        eventtype  =>  [],
                        chainname  =>  "BLOCK",
                        destchain  =>  "DROP",
                        maxage     =>  "1D",
                     );

my %FORMAT   =      (   maxage     => qr/\d+[hdmHDM]/, logging  => qr/enable|disable/,);

sub run {
    my (undef, $modprefix, $cfg, $dbh, $db_engine) = @_;
   
    my $v = Constants::mergeConfigs($cfg, $modprefix, \%CONSTANTS, \%FORMAT);
    
    my $eventtype_query = DB::joinIN("type", \@{$v->{'eventtype'}});
    my $excluded_query  = DB::joinNotIN("source", \@{$v->{'excludedip'}});

    my $condition = substr($excluded_query . $eventtype_query, 0, -5);
    my @columns= ("source");
    my @params = ($condition, DB::getOldDataDB($db_engine, "NEWER", $v->{'maxage'}));
    my $query = DB::getQueryCondThreshold($db_engine, "events", \@columns, \@params, $v->{'threshold'});

    my @rows = Utils::fetchall_array_hashref($dbh, $query);

    sub header { my $v = shift; return "/sbin/iptables -F $v->{'chainname'}\n"; };
    sub record { my ($r, $v) = @_; return "/sbin/iptables -A $v->{'chainname'} -s $r->{'source'}/32 -j $v->{'destchain'}\n"; };

    my $ret = Utils::generateOutput($v->{'outputfile'}, \@rows, \&header, \&record, undef, $v);
    return $ret;
}
1;
+0 −74
Original line number Original line Diff line number Diff line
package MailReport;
use strict;
use warnings;

my %CONSTANTS =      (
                       tool        => "sendmail",
                       sender      => "",
                       recipients  => [],
                       subject     => "",
                       subnets     => ["147."],
                       signature   => "XXX",
                       threshold   => 0,
                       excludedsensor => [],
                       excludedip  => [],
                       eventtype   => [],
                       maxage      => "1D",
                       summary     => "yes",
                     );

my %FORMAT   =      (   maxage     => qr/\d+[hdmHDM]/, 
                        tool       => qr/(ssmtp|sendmail)/,
                    );

sub run {
    my (undef, $modprefix, $cfg, $dbh, $db_engine) = @_;

    my $v = Constants::mergeConfigs($cfg, $modprefix, \%CONSTANTS, \%FORMAT);

    my $eventtype_query = DB::joinIN("type", \@{$v->{'eventtype'}});
    my $excluded_query  = DB::joinNotIN("source", \@{$v->{'excludedip'}});
    my $excludedsensor_query  = DB::joinNotIN("service", \@{$v->{'excludedsensor'}});
    my $subnets_query  = DB::joinLIKE("source", \@{$v->{'subnets'}});

    my $condition = substr($excluded_query . $eventtype_query . $excludedsensor_query . $subnets_query, 0, -5);
    my @columns= ("source", "hostname", "service", "type", "detected", "target_proto", "target_port", "attack_scale");
    my @params = ($condition, DB::getOldDataDB($db_engine, "NEWER", $v->{'maxage'}));
    my $query = DB::getQueryCondThreshold($db_engine, "events", \@columns, \@params, $v->{'threshold'});

    my @rows = Utils::fetchall_array_hashref($dbh, $query);

    if($v->{'subject'} eq "") {
        my $hostname = `hostname -f`;
        $v->{'subject'} = "$modprefix (Warden-app) on $hostname";
    }
    
    $v->{'modprefix'} = $modprefix;
   
    sub header { 
        my $v = shift; 
        my $header; 

        $header = "$v->{'modprefix'} noticed following events during $v->{'maxage'} timeframe:\n\n";
        $header   .= sprintf("+-------------------------------+---------------------+------------+-----------------+-------+----------+--------+\n"); 
        $header   .= sprintf("|       Detector/Service        |       Detected      |    Type    |      Source     | Dport |   Proto  | Volume |\n"); 
        $header   .= sprintf("+-------------------------------+---------------------+------------+-----------------+-------+----------+--------+\n"); 

        return $header
    };

    sub record { my $r = shift; return sprintf("|%30s | %19s | %10s | %15s | %5s | %8s | %6s |\n", "$r->{'hostname'}/$r->{'service'}", $r->{'detected'}, $r->{'type'}, $r->{'source'}, $r->{'target_port'}, $r->{'target_proto'}, $r->{'attack_scale'}); };

    sub footer { 
        my $v = shift; 
        my $footer = sprintf("+-------------------------------+---------------------+------------+-----------------+-------+----------+--------+\n\n");
        $footer    .= $v->{'signature'};
   
        return $footer; 
    };

    Utils::generateEmails($v->{'tool'}, \@{$v->{'recipients'}}, $v->{'sender'}, $v->{'subject'}, \@rows, \&header, \&record, \&footer, $v, $v->{'summary'});

    return 1;
}
1;
+0 −116
Original line number Original line Diff line number Diff line
package Constants;
use strict;
use warnings;
use Data::Dumper;

use constant SCALAR => 'SCALAR';

our %DEFAULTS = 
(
    factory     =>  {
                        GENERAL_logfile         =>  "var/log/factory.log",
                        GENERAL_modpath         =>  "Modules",
                     },

    receiver    =>  {
                        GENERAL_method          =>  ( "stdout" ),
                        GENERAL_logfile         =>  "var/log/receiver.log",
                        GENERAL_wardenpath      =>  "/opt/warden/client",
                        GENERAL_requested_type  =>  "",
                        
                        FILE_directory          =>  "var/fileout/",
                        FILE_method             =>  "append",
                        FILE_appendfilename     =>  "received",
                        FILE_extension          =>  "csv",
                        
                        DB_dbengine               =>  "sqlite",
                    },


    db          =>  {
                        SQLITE_db   =>  "var/db.sqlite",
                        SQLITE_user =>  "",
                        SQLITE_pass =>  "",
                        
                        MYSQL_db    =>  "warden",
                        MYSQL_user  =>  "root",
                        MYSQL_pass  =>  "",
                        MYSQL_host  =>  "localhost",
                        MYSQL_port  =>  "3306",
                    },

    cleaner     =>  {
                        GENERAL_method  =>  ( "db" ),
                        GENERAL_maxage  =>  "11D",
                    },
);


sub getDefaultValue {
    my ($valuename, $section) = @_;
    
    $valuename =~ s/\./_/g;
    my @value = $DEFAULTS{$section}{$valuename};
    die "Value '$valuename' is not defined" if not @value;
    
    return (wantarray ? @value : $value[0]);
}

sub assignValue {
    my ($valuename, $cfg, $section, $nocheck) = @_;
    
    my @configvalue = $cfg->param($valuename);
    $valuename =~ s/\./_/g;

    my @value;

    if(!defined $nocheck) { 
        my @defaultvalue = getDefaultValue($valuename, $section);
        @value = (@configvalue ? @configvalue : @defaultvalue);
    } 
    else {
        @value = @configvalue;     
    }
    die "Value '$valuename' is not defined" if not defined $value[0];

    if(wantarray and $value[0] eq "") {
        return ();
    }
    else {
        return (wantarray ? @value : $value[0]);
    }
}


sub mergeConfigs {
    my ($config, $section, $constants, $format) = @_;
    my %ret;
 
    my $conf_hash = $config->get_block($section);

    foreach my $const_key ( keys %$constants )
    {
        if( exists $conf_hash->{$const_key} ) {
            if(ref($constants->{$const_key}) eq ref($conf_hash->{$const_key})) {
                $ret{$const_key} = $conf_hash->{$const_key};
            }
            elsif (ref($constants->{$const_key}) eq 'ARRAY') {
                $ret{$const_key} = (defined $conf_hash->{$const_key} ? [$conf_hash->{$const_key}] : []);
            }
            elsif (ref(\$constants->{$const_key}) eq 'SCALAR') {
                $ret{$const_key} = (defined $conf_hash->{$const_key} ? $conf_hash->{$const_key}->[0] : "");
            } 

            if(exists $format->{$const_key}) {
                if($ret{$const_key} !~ $format->{$const_key}) {
                    $ret{$const_key} = $constants->{$const_key};
                }
            }
        }
        else {
            $ret{$const_key} = $constants->{$const_key};
        }
    }

    return \%ret;
}
+0 −105
Original line number Original line Diff line number Diff line
package DB;
use strict;
use warnings;

use WardenApp::Constants;

use constant DB_ENGINE_MYSQL => 'mysql';
use constant DB_ENGINE_SQLITE => 'sqlite';
use constant DB_SECTION => 'db';

use DBI;

sub connectDB {
    my ($cfg, $db_engine) = @_;
    
    my $dbh;

     if(lc $db_engine eq DB_ENGINE_MYSQL) {
        
        my $db      = Constants::assignValue('MYSQL.db',  $cfg, DB_SECTION);
        my $host    = Constants::assignValue('MYSQL.host',  $cfg, DB_SECTION);
        my $user    = Constants::assignValue('MYSQL.user',  $cfg, DB_SECTION);
        my $pass    = Constants::assignValue('MYSQL.pass',  $cfg, DB_SECTION);
        my $port    = Constants::assignValue('MYSQL.port',  $cfg, DB_SECTION);

        $dbh = DBI->connect("DBI:mysql:host=" . $host . ";port=" . $port . ";database=" . $db,
                            $user,
                            $pass,
                            {RaiseError => 0,AutoCommit => 0}) || die "Database connection not made: $DBI::errstr";
    }
    elsif (lc $db_engine eq DB_ENGINE_SQLITE) {
        
        my $db      = Constants::assignValue('SQLITE.db',  $cfg, DB_SECTION);
        my $user    = Constants::assignValue('SQLITE.user',  $cfg, DB_SECTION);
        my $pass    = Constants::assignValue('SQLITE.pass',  $cfg, DB_SECTION);

        $dbh = DBI->connect("DBI:SQLite:" . $db,
                            $user,
                            $pass,
                            {RaiseError => 0,AutoCommit => 1}) || die "Database connection not made: $DBI::errstr";
    }

    return \$dbh;
}

sub getOldDataDB {

    my ($db_engine, $expr, $maxage) = @_;

    my ($num, $word) = $maxage =~ /(\d+)([dmhDMH])/;
    my ($word_long, $word_desc);

    $word_long = "HOUR" if $word =~ /[hH]/;
    $word_long = "DAY"  if $word =~ /[dD]/;
    $word_long = "MONTH" if $word =~ /[mM]/;

    my $c;
    $c = "<" if($expr eq "OLDER");
    $c = ">" if($expr eq "NEWER");


    if($db_engine eq DB_ENGINE_MYSQL) {
        return sprintf("detected %s DATE_SUB(NOW(), INTERVAL %d %s)", $c, $num, $word_long);
    }
    
    if($db_engine eq DB_ENGINE_SQLITE) {
        return sprintf("datetime(detected) %s datetime('now','-%d %s')", $c, $num, $word_long);
    }

    return "";
}

sub closeDB {
    my $dbh = shift;
    $$dbh->disconnect;
}

sub getQueryCondThreshold {
    my ($db_engine, $table, $columns, $params, $threshold) = @_;
    
    my $columns_q = join ", ", @$columns;
    my $params_q = join " AND ", grep { $_ } @$params;
    
    return sprintf("SELECT %s FROM %s WHERE %s GROUP BY source HAVING COUNT(id) > %s", $columns_q, $table, $params_q, $threshold);
}

sub joinIN {
    my ($column, $data) = @_;
    return (@$data ? sprintf("%s IN (%s) AND ", $column, join ",", map { "'$_'" } @$data)  : "");
}

sub joinNotIN {
    my ($column, $data) = @_;
    return (@$data ? sprintf("%s NOT IN (%s) AND ", $column, join ",", map { "'$_'" } @$data)  : "");
}

sub joinLIKE {
    my ($column, $data) = @_;
    my $ret = (@$data ? sprintf("%s",  join ",", map { "$column LIKE '$_%' OR " } @$data)  : "");
    
    return ($ret ne "" ? substr($ret, 0, -4) . " AND " : "");
}


1;
+0 −59
Original line number Original line Diff line number Diff line
package Factory;
use strict;
use warnings;

use Config::Simple;
use WardenApp::Constants;
use WardenApp::DB;
use WardenApp::Utils;
use Data::Dumper;

use constant TRUE   => 1;
use constant FALSE  => 0;
use constant ENABLED  => 'yes';

use constant DB_ENGINE_MYSQL  => 'mysql';
use constant DB_ENGINE_SQLITE => 'sqlite';

use constant FACTORY_SECTION  => 'factory';
use constant CFG_MODULE_DIR   => 'GENERAL.modpath';


sub isModEnabled {
    my ($modprefix, $cfg) = @_;

    my $enabled = Constants::assignValue($modprefix . ".enabled", $cfg, FACTORY_SECTION);
    if ($enabled eq ENABLED) {
        return TRUE;
    }
    else {
        return FALSE;
    }
}

sub runModule {
    my ($modulename, $cfg, $dbh, $db_engine) = @_;
 
    unless(isModEnabled($modulename, $cfg)) {
        print "Module '$modulename' disabled! See configuration file!\n";
        return 0;    
    }
 
    my $moddir  = Constants::assignValue(CFG_MODULE_DIR,  $cfg, FACTORY_SECTION);
    my $module  = Constants::assignValue($modulename . ".module",  $cfg, FACTORY_SECTION, "nocheck");  
    
    require "$moddir/$module.pm";
    
    print "Module '$modulename' started\n"; 
    my $ret = $module->run($modulename, $cfg, $dbh, $db_engine); 
    
    if($ret) { 
        print "Module '$modulename' finished\n"; 
        return 1;
    }
    else {
        print "Module '$modulename' finished with errors\n"; 
        return 0;
    }
}
1;
+0 −71
Original line number Original line Diff line number Diff line
package Receiver;
use strict;
use warnings;

use WardenApp::Constants;

use constant RECEIVER_SECTION  => 'receiver';
use constant SQL_INSERT_EVENT  => "INSERT INTO events VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";

sub openfile {
    my ($cfg) = @_;
    my ($filename, $openparam);

    my $method = Constants::assignValue('FILE.method', $cfg, RECEIVER_SECTION);

    if($method ne 'newfile' and $method ne 'append') {
        $method = Constants::getDefaultValue('FILE.method', RECEIVER_SECTION);
    }
    
    if($method eq 'newfile') {
        my ($sec, $min, $hr, $day, $mon, $year) = localtime;
        
        $openparam = ">";
        $filename = sprintf("%02d-%02d-%04d_%02d-%02d", $day, $mon + 1, 1900 + $year, $hr, $min);
    
    }
    elsif ($method eq 'append') {
        $openparam = ">>";
        $filename = Constants::assignValue('FILE.appendfilename', $cfg, RECEIVER_SECTION); 
    }


    my $directory = Constants::assignValue('FILE.directory', $cfg, RECEIVER_SECTION); 
    my $extension = Constants::assignValue('FILE.extension', $cfg, RECEIVER_SECTION);

    my $openstring = $openparam . $directory . "/" .  $filename . "." . $extension; 
    open FILE, $openstring or die $!;
    return \*FILE;

}

sub saveToDB {
    my ($dbh, $event, $db_engine) = @_;
    
    my $sth = $$dbh->prepare(SQL_INSERT_EVENT);
    #my $data = join(',', @$event);
    $sth->execute(@$event) || die $sth->errstr;

    print "Receiver-$db_engine:\tError \"$@\" while processing data\n" if $@;
}

sub saveToFile {
    my ($file, $event) = @_;
    my $data = join(';', @$event);

    print $file $data . "\n";
}

sub printToStdout {
    my $event = shift;   
    
    print "| " . join(' | ', @$event ) . " |" . "\n";
}

sub closeFile {
    my $file = shift;
    close $file;
}

1;
+0 −111

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −61

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −48

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −65

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −341

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −19
Original line number Original line Diff line number Diff line
#+--------------------------- minute [0-59;*/10 means every 10 minutes (0,10,20,30,40,50)]
#|       +------------------- hour [0-23]
#|       |   +--------------- day of month [1-31]
#|       |   | +------------- month [1-12]
#|       |   | | +----------- day of week [0-7; 0 or 7 is Sunday]
#|       |   | | |  +-------- user
#|       |   | | |  |     +-- command
#|       |   | | |  |     |

SCRIPT_PATH=/opt/warden-app/

*/5  *   * * *  root    cd $SCRIPT_PATH; ./warden-receiver.pl

21   *   * * *  root    cd $SCRIPT_PATH; ./warden-factory.pl MOD_IPTABLES_1

21   *   * * *  root    cd $SCRIPT_PATH; ./warden-factory.pl MOD_BLACKLISTIP_1

1    1   * * *  root    cd $SCRIPT_PATH; ./warden-cleaner.pl
Loading