Skip to content
This repository has been archived by the owner on Nov 3, 2021. It is now read-only.

Commit

Permalink
add plugin system to the rest api, alter blockIP to use plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffbryner committed Feb 10, 2015
1 parent 2d00426 commit c73d820
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 139 deletions.
30 changes: 25 additions & 5 deletions meteor/app/client/blockIP.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ <h4>Block IP</h4>
<form id="blockIPform" class="form-horizontal" style="margin: 0px 5%;">
<!-- IP addr -->
<div class="form-group">
<label class="control-label" for="ipaddr">IP address or subnet (IPv6 supported, use addr/X for subnets)</label>
<label class="control-label" for="ipaddress">IP address or subnet (IPv6 supported, use addr/X for subnets)</label>
<div class="controls">
<input id="ipaddr" name="ipaddr" class="form-control" type="text" required>
<input id="ipaddress" name="ipaddress" class="form-control" type="text" required>
</div>
</div>
<!-- Duration -->
Expand All @@ -105,12 +105,32 @@ <h4>Block IP</h4>
</div>

<div class="form-group">
<label class="control-label" for="bugid">Reference ID</label>
<label class="control-label" for="referenceid">Reference ID</label>
<div class="controls">
<input id="bugid" name="bugid" class="form-control" type="text" placeholder="optional" maxlength="7" >
<input id="referenceid" name="referenceid" class="form-control" type="text" placeholder="optional" maxlength="7" >
</div>
</div>


<!--plugins-->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Plugins:</h3>
</div>
<div class="panel-body">
{{#each pluginsForEndPoint "blockip"}}

<div class="form-group">
<div class="col-xs-8 checkbox">
<label>
<input type="checkbox" name="{{name}}">{{name}}: ( {{description}} )
</label>
</div>
</div>
{{/each}}
</div>
</div>


<!-- Button -->
<div class="form-group">
<label class="control-label" for="submit"></label>
Expand Down
39 changes: 8 additions & 31 deletions meteor/app/client/blockIP.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,55 +11,32 @@ Anthony Verez averez@mozilla.com

if (Meteor.isClient) {

blockIP=function(){
var reporter = '';
try {
reporter = Meteor.user().profile.email;
}
catch(err) {
reporter = 'test';
}
var cidr = 32;
var ipaddr = $('#ipaddr')[0].value.split('/');
var address = ipaddr[0];
if (ipaddr.length == 2) {
cidr=parseInt(ipaddr[1]) || 32;
}
var actionobj = {
address: address,
cidr: cidr,
duration: $('#duration')[0].value,
comment: $('#comment')[0].value,
reporter: reporter,
bugid: parseInt($('#bugid')[0].value)
};
Meteor.call('blockip', actionobj);

};


Template.blockIPform.rendered = function() {
$('#ipaddr')[0].value = Session.get('blockIPipaddress');
$('#ipaddress')[0].value = Session.get('blockIPipaddress');
};

Template.blockIPform.events({
"submit form": function(event, template) {
event.preventDefault();
blockIP();
formobj=formToObject("#blockIPform :input");
formobj.push({userid:Meteor.user().profile.email});
Meteor.call('blockip', formobj);
Router.go('/attackers');
}
});

Template.blockIPModal.rendered = function(){
Deps.autorun(function() {
$('#ipaddr')[0].value = Session.get('blockIPipaddress');
$('#ipaddress')[0].value = Session.get('blockIPipaddress');
}); //end deps.autorun
};

Template.blockIPModal.events({
"submit form": function(event, template) {
event.preventDefault();
blockIP();
formobj=formToObject("#blockIPform :input");
formobj.push({userid:Meteor.user().profile.email});
Meteor.call('blockip', formobj);
$('#modalBlockIPWindow').modal('hide')
}
});
Expand Down
41 changes: 40 additions & 1 deletion meteor/app/client/mozdef.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,19 @@ if (Meteor.isClient) {
Session.set('alertsrecordlimit',100);
Session.set('attackerlimit','10');
getAllPlugins();
//console.log(pluginsForEndPoint("test"));
});

//find plugins registered for a
//specific endpoint
pluginsForEndPoint=function(endpoint){
matches=[]
matches=_.filter(Session.get('plugins'),
function(e){
return _.indexOf(e.registration,endpoint) >-1 ;
});
return matches;
};

getAllPlugins=function(){
Meteor.apply('getplugins',[],
Expand All @@ -35,7 +47,7 @@ if (Meteor.isClient) {
}
Session.set('plugins',plugins);
})
}
};

//helper functions for UI templates
//and other client javascript routines
Expand Down Expand Up @@ -64,6 +76,29 @@ if (Meteor.isClient) {
console.log(logthis);
}
};

formToObject=function(selector){
//send a selctor like "#formID :input"
//get back an object you can JSON.stringify
//as an array of key:value pairs
//for each named item in a form
var inputs = $(selector);
var formobj = $.map(inputs, function(n, i)
{
var o = {};
switch($(n).attr("type")){
case "radio":
case "checkbox":
o[n.name] = $(n).prop('checked');
break;
default:
o[n.name] = $(n).val();
break;
}
return o;
});
return formobj;
};

Template.hello.greeting = function () {
if (typeof console !== 'undefined')
Expand Down Expand Up @@ -163,6 +198,10 @@ if (Meteor.isClient) {

});
});

UI.registerHelper('pluginsForEndPoint',function(endpoint){
return pluginsForEndPoint(endpoint);
});


//auto run to handle session variable changes
Expand Down
8 changes: 4 additions & 4 deletions meteor/app/server/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ if (Meteor.isServer) {
}
}

function blockIP(actionobj) {
var blockIPRequest = HTTP.post(mozdef.rootAPI + '/blockip', {data: actionobj});
function blockIP(formobj) {
var blockIPRequest = HTTP.post(mozdef.rootAPI + '/blockip', {data: formobj});

if (blockIPRequest.statusCode==200) {
console.log(actionobj.address+"/"+actionobj.cidr+" blocked for "+actionobj.duration);
console.log(JSON.stringify(formobj) + ' successfully sent to ' + mozdef.rootAPI);
} else {
console.log("Could not block "+actionobj.address+"/"+actionobj.cidr+" for "+actionobj.duration);
console.log("Could not send to "+ mozdef.rootAPI + '/blockip ' + JSON.stringify(formobj) );
}
}

Expand Down
99 changes: 1 addition & 98 deletions rest/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import bottle
import json
import MySQLdb
import netaddr
import os
import pyes
Expand Down Expand Up @@ -116,11 +115,6 @@ def index():
@post('/blockip/', methods=['POST'])
@enable_cors
def index():
if options.enableBlockIP:
try:
request.body = banhammer(request.json)
except Exception as e:
sys.stderr.write('Error parsing json sent to POST /banhammer\n')
sendMessgeToPlugins(request, response, 'blockip')
return response

Expand Down Expand Up @@ -257,7 +251,7 @@ def registerPlugins():
if 'message' in dir(module):
mclass = module.message()
mreg = mclass.registration

mclass.restoptions = options

if 'priority' in dir(mclass):
mpriority = mclass.priority
Expand Down Expand Up @@ -404,59 +398,6 @@ def kibanaDashboards():
sys.stderr.write('Elastic Search server could not be reached, check network connectivity\n')


def banhammer(action):
try:
mysqlconn = MySQLdb.connect(
host=options.banhammerdbhost,
user=options.banhammerdbuser,
passwd=options.banhammerdbpasswd,
db=options.banhammerdbdb)
dbcursor = mysqlconn.cursor()
# Look if attacker already in the DB, if yes get id
dbcursor.execute("""SELECT id FROM blacklist_offender
WHERE address = "%s" AND cidr = %d""" % (action['address'], int(action['cidr'])))
qresult = dbcursor.fetchone()
if not qresult:
# insert new attacker in banhammer DB
created_date = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
dbcursor.execute("""
INSERT INTO blacklist_offender(address, cidr)
VALUES ("%s", %d)
""" % (action['address'], action['cidr']))
# get the ID of this query
dbcursor.execute("""SELECT id FROM blacklist_offender
WHERE address = "%s" AND cidr = %d""" % (action['address'], int(action['cidr'])))
qresult = dbcursor.fetchone()
(attacker_id,) = qresult
# Compute start and end dates
start_date = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
end_date = datetime.utcnow() + timedelta(hours=1)
if action['duration'] == '12hr':
end_date = datetime.utcnow() + timedelta(hours=12)
elif action['duration'] == '1d':
end_date = datetime.utcnow() + timedelta(days=1)
elif action['duration'] == '1w':
end_date = datetime.utcnow() + timedelta(days=7)
elif action['duration'] == '30d':
end_date = datetime.utcnow() + timedelta(days=30)

if action['bugid']:
# Insert in DB
dbcursor.execute("""
INSERT INTO blacklist_blacklist(offender_id, start_date, end_date, comment, reporter, bug_number)
VALUES (%d, "%s", "%s", "%s", "%s", %d)
""" % (attacker_id, start_date, end_date, action['comment'], action['reporter'], int(action['bugid'])))
else:
dbcursor.execute("""
INSERT INTO blacklist_blacklist(offender_id, start_date, end_date, comment, reporter)
VALUES (%d, "%s", "%s", "%s", "%s")
""" % (attacker_id, start_date, end_date, action['comment'], action['reporter']))
mysqlconn.commit()
sys.stderr.write('%s/%d: banhammered\n' % (action['address'], action['cidr']))
except Exception as e:
sys.stderr.write('Error while banhammering %s/%d: %s\n' % (action['address'], action['cidr'], e))


def getWhois(ipaddress):
try:
whois = IPWhois(netaddr.IPNetwork(ipaddress)[0]).lookup()
Expand Down Expand Up @@ -488,20 +429,6 @@ def getIPCIF(ipaddress):
except Exception as e:
sys.stderr.write('Error looking up CIF results for {0}: {1}\n'.format(ipaddress, e))


def checkBlockIPService():
if options.enableBlockIP:
try:
mysqlconn = MySQLdb.connect(
host=options.banhammerdbhost,
user=options.banhammerdbuser,
passwd=options.banhammerdbpasswd,
db=options.banhammerdbdb)
dbcursor = mysqlconn.cursor()
except Exception as e:
sys.stderr.write('Failed to connect to the Banhammer DB\n')


def verisSummary(verisRegex=None):
try:
# aggregate the veris tags from the incidents collection and return as json
Expand Down Expand Up @@ -546,26 +473,6 @@ def initConfig():
'http://localhost:9090',
options.configfile)

# options for your custom/internal ip blocking service
# mozilla's is called banhammer
# and uses an intermediary mysql DB
# here we set credentials
options.enableBlockIP = getConfig('enableBlockIP',
False,
options.configfile)
options.banhammerdbhost = getConfig('banhammerdbhost',
'localhost',
options.configfile)
options.banhammerdbuser = getConfig('banhammerdbuser',
'auser',
options.configfile)
options.banhammerdbpasswd = getConfig('banhammerdbpasswd',
'',
options.configfile)
options.banhammerdbdb = getConfig('banhammerdbdb',
'banhammer',
options.configfile)

# options for your CIF service
options.cifapikey = getConfig('cifapikey', '', options.configfile)
options.cifhosturl = getConfig('cifhosturl',
Expand All @@ -575,10 +482,6 @@ def initConfig():
options.mongohost = getConfig('mongohost', 'localhost', options.configfile)
options.mongoport = getConfig('mongoport', 3001, options.configfile)

# check any service you'd like at startup rather than waiting
# for a client request.
checkBlockIPService()


if __name__ == "__main__":
parser = OptionParser()
Expand Down

0 comments on commit c73d820

Please sign in to comment.