Inspirated

 
 

July 1, 2013

Blocking traffic flows selectively with a timeout from Bro IDS

Filed under: Blog — krkhan @ 2:55 am

I needed to block some flows on OpenWRT from the Bro IDS. One option was to install the recent module for expiring iptables rules which sounded like an overkill. After some tinkering around I landed on using bash and at to expire the firewall rules after timeouts (luckily the at daemon was available on OpenWRT which made my job easier).

There are three parts to the process:

The bash script

First, a script which:

  1. Constructs and adds the iptables rule to the FORWARD chain.
  2. Constructs the corresponding deletion rule.
  3. Creates a temporary bash script, writes the rule to it, makes the new script self-deleting.
  4. Schedules a launch of the temporary script with at command.

Here’s the script:

#!/bin/sh
 
if [ $# -le 5 ] ; then
  echo "usage: $0 proto src sport dst dport timeout"
  exit 1
fi
 
proto=$1
src=$2
sport=$3
dest=$4
dport=$5
timeout=$6
 
echo "  proto: $1"
echo "    src: $2"
echo "  sport: $3"
echo "   dest: $4"
echo "  dport: $5"
echo "timeout: $6"
 
rule=""
 
if [ "$proto" != "any" ]; then
  rule="$rule --protocol $proto"
fi
 
if [ "$src" != "0.0.0.0" ]; then
  rule="$rule --source $src"
fi
 
if [ "$sport" != "0" ]; then
  rule="$rule --sport $sport"
fi
 
if [ "$dest" != "0.0.0.0" ]; then
  rule="$rule --destination $dest"
fi
 
if [ "$dport" != "0" ]; then
  rule="$rule --dport $dport"
fi
 
rule="$rule -j DROP"
 
echo "rule: $rule"
 
addcmd="iptables -I FORWARD $rule"
delcmd="iptables -D FORWARD $rule"
 
delscript=`mktemp`
echo "delscript: $delscript"
 
echo "#!/bin/sh" >>$delscript
echo $delcmd >>$delscript
echo "rm \"${delscript}\"" >>$delscript
chmod 755 $delscript
 
echo "adding iptable rule:"
echo $addcmd
`$addcmd`
 
atcmd="at -M -f $delscript now + $timeout min"
echo "creating at job for deletion:"
echo $atcmd
`$atcmd`

Given below is an example run. First, let’s print the default FORWARD chain:

# iptables -nL FORWARD
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             10.42.0.0/24         state RELATED,ESTABLISHED
ACCEPT     all  --  10.42.0.0/24         anywhere            
ACCEPT     all  --  anywhere             anywhere            
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Block a flow for 2 minutes:

# sh blockflow.sh tcp 50.50.50.50 50 60.60.60.60 60 2
  proto: tcp
    src: 50.50.50.50
  sport: 50
   dest: 60.60.60.60
  dport: 60
timeout: 2
rule:  --protocol tcp --source 50.50.50.50 --sport 50 --destination 60.60.60.60 --dport 60 -j DROP
delscript: /tmp/tmp.SAREJvtsK0
adding iptable rule:
iptables -I FORWARD --protocol tcp --source 50.50.50.50 --sport 50 --destination 60.60.60.60 --dport 60 -j DROP
creating at job for deletion:
at -M -f /tmp/tmp.SAREJvtsK0 now + 2 min
job 79 at Sun Jun 30 14:37:00 2013

Let’s check if the new rule was added:

# iptables -nL FORWARD
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
DROP       tcp  --  50.50.50.50          60.60.60.60          tcp spt:50 dpt:60
ACCEPT     all  --  anywhere             10.42.0.0/24         state RELATED,ESTABLISHED
ACCEPT     all  --  10.42.0.0/24         anywhere            
ACCEPT     all  --  anywhere             anywhere            
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

After 2 minutes, the temporary bash script shall remove the rule and then delete itself. To confirm:

# iptables -nL FORWARD
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             10.42.0.0/24         state RELATED,ESTABLISHED
ACCEPT     all  --  10.42.0.0/24         anywhere            
ACCEPT     all  --  anywhere             anywhere            
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

The Bro module

A simple module which export one function, i.e., BlockFlow::block which takes a conn_id and a count and calls the bash script with appropriate parameters:

module BlockFlow;
 
export {
  global block: function(id: conn_id, t: count);
}
 
function block(id: conn_id, t: count)
{
  print fmt("blocking %s:%d -> %s:%d for %d minutes", id$orig_h, id$orig_p, id$resp_h, id$resp_p, t);
 
  local protocol = get_port_transport_proto(id$resp_p);
  print fmt("protocol is: %s", protocol);
 
  local cmd: string = fmt("sh blockflow.sh %s %s %d %s %d %d", protocol
                                                             , id$orig_h, id$orig_p
                                                             , id$resp_h, id$resp_p, t);
  print fmt("executing: %s", cmd);
  system(cmd);
}

Bro module usage

And finally, using the module from a Bro script:

@load ./blockflow
 
event bro_init()
  {
    local id: conn_id;
    id$orig_h = 10.10.10.10;
    id$orig_p = 10/tcp;
    id$resp_h = 20.20.20.20;
    id$resp_p = 20/tcp;
    BlockFlow::block(id, 2);
  }

And the flow will be blocked for 2 minutes. Unfortunately, due to the way at command works the granularity of timeouts is limited to minutes. If you really want to block flows for only a few seconds a quick solution would be to use sleep in place of at before expiring the rule.

Tags: , , , , , , ,

December 10, 2012

Bro IDS on OpenWRT

Filed under: Blog — krkhan @ 12:59 pm

While I was at SysNet, we had been working on a project we called “Shrimp” — Software-defined Home Router Intelligent Monitoring Point. The goal of the project was to provide a framework for easy programmatic access to network monitoring on low-cost, commodity, home router devices. One of the requirements was to have an IDS on the home routers for which we chose Bro — the leading framework for semantic analysis of network traffic.

The OpenWRT OS was chosen as the target platform. Its SDK contained a cross-compile toolchain for CMake projects. However, during the compilation Bro tried to run the binpac and bifcl executables for processing intermediate files. The executables refused to run on the build platform if the target platform architecture was different (mostly the case, e.g., we were building on x86-64 and target was arm).

The (not-so-pretty ™) workaround we used was to build Bro twice. Once for the host, and once for the target. The CMake files were then patched to first generate binpac and bifcl binaries if they weren’t provided and then use the provided binaries if they were defined at make time. The first compile generated the binaries on x86-64 and the second compile (for arm) used the earlier binaries to process the bif files.

The Makefile and patches are available in this tarball: openwrt-bro.tar.gz, while the compiled ipk package is also available for installation. Here is a test execution of Bro on OpenWRT:

# bro –v
bro version 2.0
# cat test.bro
event bro_init()
{
	print "Hello World!";
}

event new_connection(c: connection)
{
	print "New connection created";
}
# bro test.bro
Hello World!
# bro -i br-lan test.bro
Hello World!
New connection created
New connection created
# ls
conn.log           notice_policy.log  reporter.log       weird.log
dns.log            packet_filter.log  test.bro

A heap of thanks to Zaafar for dealing with my messy code and providing the links to hosted files :) !

Tags: , , , , , , , ,

November 14, 2012

Workflow sharing with Synergy

Filed under: Blog — krkhan @ 4:33 am

It has been a while since I’ve posted around here and the reasons have been entirely mundane — got a job, moved to a different country and lost track of everything open-source during the transition.

However, open-source is out there and every once a while you’re bound to stumble across gems that make life easier (and fun) no matter which line of work you are in and that’s exactly what happened to me today. Let me admit first, I have a fetish for multiple screens. If it was up to me I would have a circle of screens and sit inside them all day long, just to make revolving chairs lot more exciting. Take that, 3D!

Anyways, the issue with multiple screens is not only having enough video outputs on your graphic card(s), but also the sharing of resources. I want three different machines with different processors, hard-disks, heck even different operating systems to share their I/O devices. One option would be the KVM switches, but that would restrict me to only one “active” machine at a time, plus the switching button is too much of a hindrance in the work flow. Aristotle famously claimed that the whole is greater than the sum of its parts, then cometh Synergy:

Synergy in action
(Click on the thumbnail for larger version.)

Three different machines sharing the keyboard, mouse and clipboard across five different screens and it even works across different platforms! Granted, there are some issues with the configuration which you have to take care about (especially on Windows 7+ platforms with UAC) but once it gets going it becomes one of those cute plus practical toys that make you wonder how you ever lived without them.

Tags: , , , ,

March 18, 2012

slicehosts: Extract host-based traffic out of pcap dumps

Filed under: Blog — krkhan @ 2:56 pm

During the course of my work on botnet security we have had to deal with mammoth traffic traces captured at a local ISP. While analyzing the traffic we needed to extract traffic for some certain hosts out of large pcap files. An obvious solution would be to run tshark once for each host, filtering the traffic for that particular IP and writing it to a separate pcap file. However with the number of hosts approaching thousands and the pcap traces approaching terabytes in size tshark didn’t really fit the bill.

Initially I thought of writing a splitter in Python but my colleague’s aversion for using Python on large network traces coupled with lack of maintenance of libpcap bindings resulted in me going for C/libpcap directly. The new C-based slicer is available at our GitHub respository. It needs glib to compile though, as I needed a hash table implementation for maintaining the list of hosts that need to be sliced. The Makefile in the repository should take care of compiling with the appropriate flags.

Onto the performance, the speed of slicing is only throttled by libpcap‘s own read/write throughput as most of the remaining work is done in constant time. It took only 71 minutes (or 1.1 hours) to slice 1019 hosts out of a 180 GB pcap file on 2.5 GHz CPU. In simpler words, it’s lightning fast.

Right now the script does its job well enough. If someone needs to package it I’ll prefer removing the glib dependency in favor of perhaps glibc‘s own hash table implementation (search.h). In any case, I hope it proves helpful for other people playing with large pcap files.

Tags: , , , , , , , , ,

December 11, 2011

Fix disappearing Compiz skydome at login

Filed under: Blog — krkhan @ 1:49 pm

For a little while now I noticed that my Compiz skydome was disappearing whenever I logged in. I could bring it back by disabling and re-enabling the Cube plugin but from a cold-boot I was always greeted to an abysmal looking cube:

Compiz blank skydome
(Click on the thumbnail for larger version.)

A little bit of forensics revealed that the issue lied with the loading order of Compiz plugins. At the moment Compiz does not try to resolve any plugin dependencies at startup, so while the skydome relied on the PNG plugin the latter wasn’t pre-loaded — resulting in a blank background.

The solution was to change the following line in config:

[core]
s0_active_plugins = core;composite;opengl;copytex;decor;vpswitch;mousepoll;firepaint;gnomecompat;resize;compiztoolbox;wobbly;cube;screensaver;shift;scale;regex;imgpng;splash;place;move;obs;animation;rotate;expo;workarounds;freewins;ezoom;session;staticswitcher;

To:

[core]
s0_active_plugins = core;composite;opengl;copytex;decor;vpswitch;mousepoll;firepaint;gnomecompat;imgpng;resize;compiztoolbox;wobbly;cube;screensaver;shift;scale;regex;splash;place;move;obs;animation;rotate;expo;workarounds;freewins;ezoom;session;staticswitcher;

imgpng had to be loaded before cube, giving me back the pretty backdrop for all things 3D:

Compiz PNG skydome
(Click on the thumbnail for larger version.)

Tags: , , , , , ,

November 16, 2011

Useless domains, Dynamic DNS and Netgear

Filed under: Blog — krkhan @ 8:06 pm

A few weeks back I was renewing this blog’s domain name when I was given a coupon code which would grant me a 20%+ discount for orders >75 USD. Now my order was only touching 70, so grabbing a calculator and dutifully acting like a white-collar citizen made me realize that if I ordered another domain my total order would actually cost me lesser than what I already had. Classic case of “more is less” — I ended up with another domain and a total lack of ideas about what to do with it.

Until, I remembered about this picture from 2 years ago:

The Three Musketeers
“Say hello to my little friend!”
(Click on the thumbnail for larger version.)

The ineffectual Eee PC finally found some practical use. Using Dynamic DNS to point expirated.com towards it, I configured lighttpd to serve the website. As for the content I wrote a few Python scripts to monitor the status of the Tor relay and internet connection at my home. Still not terribly useful, but at least the plots for latter give me a nice idea about how my internet is doing when I’m not at home.

The internet router (Netgear DG834) did not support SSH/SCP so I used Python’s telnetlib module to log in to the router and bring back the modem stats. The results are then fed to a maze of regexes, generating values which are finally plotted via matplotlib.

How I wish I had better things to do with a domain name.

Tags: , , , , , ,

October 15, 2011

Google Summer of Code 2011 Memorabilia

Filed under: Blog — krkhan @ 2:14 am

I love code, I love cotton … :

GSoC 2011 Memorabilia
(Click on the thumbnail for larger version.)

… as much as I loved them last year:

GSoC 2010 & 2011 Memorabilia
(Click on the thumbnail for larger version.)

Tags: , , , , , ,

October 8, 2011

BBC World Have Your Say: The death of Steve Jobs

Filed under: Blog — krkhan @ 2:15 am

I recall three distinct things about my visit to BBC’s Islamabad Studios today. Kamil’s very friendly support (he kept reassuring me that everyone gets nervous for their first live appearance on television), a minor car accident right beneath the balcony I was standing in and prevalent general confusion about what to do with my hands when I’m on air (I wasn’t sure if they were on screen so couldn’t decide whether to stuff them in my pockets or not). In any case, it was ultra fun:

Tags: , , , , , , , ,

October 4, 2011

Summing up Google Summer of Code 2011

Filed under: Blog — krkhan @ 12:32 pm

Due to a number of commitments which I had pinned back during the summer for GSoC I was unable to attend much to the Internet over the past few weeks. Now that I’m back a summary of this year’s coding festival is in order:

The Program

This year I was working with Electronic Frontier Foundation/The Tor Project for improving the Anonymizing Relay Monitor (arm). The original proposal can be downloaded from this link are accessed via a browser at Google Docs. However, do note that not all of the goals from the proposal were met. Some were modified, some were removed altogether while some new ones were added — the details of which I’ll be explaining in the following sections.

Overall the program has been an extraordinarily enjoyable and learning experience for me. My involvement with Ubuntu last year had already taught me how invaluable it is to merge with your mentoring organizing’s developer community. This year most of my collaboration took place in #tor-dev on OFTC. Many times when I was stuck or heading towards an improper direction with my code the core Tor developers helped me and provided advice for design decisions as well as general guidance about the way things work in Tor. It wasn’t only a privilege to be helped by such rockstars, but was also vital as I can see in hindsight how disastrous it would have been if I had attempted to work through the program entirely on my own.

A huge thanks goes to my mentor Damian. Most of the credit for making this program an enjoyable and stimulating experience for me goes directly to him. He has one of the best combinations of code-people skills among people I’ve known. I would’ve loved meeting him and the Tor community in PETS ’11 but couldn’t travel due to some paperwork fiasco which was entirely a result of my slothful attitude towards anything involving government offices. Nevertheless, I do hope to meet the guys next year in PETS ’12.

The Code

In order to not sound repetitious, I’ll provide a quick summary of the milestones while linking to the posts which explain them in detail:

Menus for arm CLI

My first task was to add dropdown menus for the curses interface to arm. Even though the menus were replaced by Damian’s rewrite, they went a long way in helping me assimilate myself with the arm codebase:

Drop-down menus for arm
(Click on the thumbnail for larger version.)

Graphs and logs for arm GUI

GTK+ was chosen as the toolkit for developing the arm GUI prototype. While GTK+ has its own disadvantages when compared to Qt (platform portability — or the lack thereof — being the foremost), it fared well in light-weight Unix environment such as Live CDs (e.g., Tails). Bandwidth graphs and logs for various arm events were added to the prototype:

CLI bandwidth stats for arm

Down arrow

GUI bandwidth stats for arm
(Click on the thumbnails for larger version.)

Connections and general stats for arm GUI

Moving on with the GUI, next up was to improve its conformity with the rest of the user’s desktop:

Graphs panel for garm 0.1
(Click on the thumbnail for larger version.)

And then re-use arm’s CLI connection resolvers in order to display stats about Tor circuits and control connections:

Connections panel for garm 0.1
(Click on the thumbnail for larger version.)

A small addition was migration of the “sticky” panel from CLI which was moved under a “General” tab and provided miscellaneous info about Tor and arm:

General panel for garm 0.1
(Click on the thumbnail for larger version.)

Configuration panel for GUI

Another important panel in the arm CLI was its configuration interface which provided a nice and documented approach to altering Tor’s settings. It was migrated to GUI with nice dialogs for validating user input:

Configuration panel for garm
(Click on the thumbnail for larger version.)

Along with the configuration panel a few patches to Tor and Vidalia were developed which would allow arm to be notified of changes made by an external program via a CONF_CHANGED event. The support for CONF_CHANGED still isn’t solid in all Tor controllers yet which I plan on addressing in coming months.

Exit node selector for arm CLI & GUI

A popular feature request among Tor users was to be able to select the country for their exit nodes. While I initially planned on providing them more fine-grained control over their circuits (such as path length), Tor developers advised against it and hence the selection was limited to the exit-node’s locale:

Exit node selector for garm
Exit node selector for arm
(Click on the thumbnails for larger version.)

The Nutshell

“It goes on forever — and — oh my God — it’s full of stars!”

It’s just that awesome, seriously. Stars from the FLOSS strata gather around and help inexperienced and aspiring developers all over the globe for two months in order to bring more code and — more importantly — more people to the open-source world. The experience with GSoC not only helps me in general open-source development, but also proves to be priceless at my workplace for my research in software defined networks. If you’re even remotely interested in open-source do keep an eye on the program’s website for future updates.

Tags: , , , , , , , , , ,

September 4, 2011

Summer of Code Progress: Exit node selection

Filed under: Blog — krkhan @ 1:49 pm
Summer of Code Archive Inspirated Code
Original Proposal Google Docs
PDF
Repository Tor Project Git
Mentor Blog arm Development Log

The final weeks of GSoC 2011 were spent by me working on exit node selection for Tor users. The GUI controller can now be used to define a list of countries, after which only those exit nodes shall be used which lie in one of the specified territories:

Exit node selector for garm
(Click on the thumbnail for larger version.)

For the CLI, Damian decided that the general use case for exit node selection is specification of a single country so pressing ‘E’ in the connections panel brings up a list from which one can be chosen:

Exit node selector for arm
(Click on the thumbnail for larger version.)

Please note that the exit node restriction works only for circuits built after the selection. Therefore it might be a good idea to send a NEWNYM to Tor after specifying the countries — which you’ll have to do manually for the time being until I add the feature to (g)arm controllers.

In my next post I’ll cover a summary of my involvement with GSoC this year, that is, after I finish with the regular chores of code submission etc.

Tags: , , , , , , , , ,
Next Page »