Tuesday, May 7, 2013

Python CIDR Subnet Calculator, 'IP to long', and IP range to CIDR

This collection of scripts is useful for converting and working with IP address data in an application. They were scattered around before now. I did not write these and I don't remember where I found them. Enjoy.

Source code at the bottom of the post.

Python CIDR Subnet Calculator

$ ./subnet.py

Input an IP address in CIDR notation and the script will calculate the subnet mask, the network address and the broadcast address. 

IP address to long integer

When working with IP addresses in (MySQL) databases, it is best to store each IPv4 address as its 'long integer' value. For example:

$ ./ip2long.sh

$ ./ip2long.sh

Note how the integer and IP address incremented by one. All IP addresses have an integer equivalent. 

Long integer to IP address

This converts the input of a long integer into the IPv4 address.
$ ./long2ip.sh 3232235877

IP Range to CIDR notation

This little gem (perl?) is good when you need the CIDR notation from a range of IP addresses. For example:
$ ./range2cidr.pl
And for those who will be using this to configure routers, Cisco gear, etc. Take the output of the range2cidr script and use the subnet.py script:

$ ./subnet.py
$ ./subnet.py

Wunderbar! Ok, source code:

Python CIDR Subnet Calculator 

#!/usr/bin/env python
# python subnet.py

import sys

# Get address string and CIDR string from command line
(addrString, cidrString) = sys.argv[1].split('/')

# Split address into octets and turn CIDR into int
addr = addrString.split('.')
cidr = int(cidrString)

# Initialize the netmask and calculate based on CIDR mask
mask = [0, 0, 0, 0]
for i in range(cidr):
    mask[i/8] = mask[i/8] + (1 << (7 - i % 8))

# Initialize net and binary and netmask with addr to get network
net = []
for i in range(4):
    net.append(int(addr[i]) & mask[i])

# Duplicate net into broad array, gather host bits, and generate broadcast
broad = list(net)
brange = 32 - cidr
for i in range(brange):
    broad[3 - i/8] = broad[3 - i/8] + (1 << (i % 8))

# Print information, mapping integer lists to strings for easy printing
print "Address: " , addrString
print "Netmask: " , ".".join(map(str, mask))
print "Network: " , ".".join(map(str, net))
print "Broadcast: " , ".".join(map(str, broad))

IP address to long integer 


INET_ATON() { #{{{
    local IFS=. ip num e
    for e in 3 2 1
        (( num += ip[3-e] * 256 ** e ))
    (( num += ip[3] ))
    echo $num
} #}}}

echo `INET_ATON $1`

Long integer to IP address


INET_NTOA() { #{{{
    local IFS=. num quad ip e
    for e in 3 2 1
        (( quad = 256 ** e))
        (( ip[3-e] = num / quad ))
        (( num = num % quad ))
    echo "${ip[*]}"
} #}}}

echo `INET_NTOA $1`

IP range to CIDR notation routes

Note the dependency on Perl CPAN module Net::CIDR 
To install on Ubuntu: sudo cpan to open CPAN, followed by install Net::CIDR

#!/usr/bin/perl -w
# range2cidr.pl
# sudo cpan > install Net::CIDR

use Net::CIDR;
use Net::CIDR ':all';

if (@ARGV == 0) {
  die "Usage Example: $0 \n";

print join("\n", Net::CIDR::range2cidr("$ARGV[0]")) . "\n";

Tuesday, November 13, 2012

(Simple, pretty crappy) Banner Grabbing with Linux

HTTP Server Banner Grab

Using netcat (nc) to interact with an HTTP server. The output can be 'teeed' and 'grepped'

$ nc www.computerbiology.com 80
GET / HTTP/1.1
Host: computerbiology.com
User-Agent: commandline :-D
Referrer: google.com

[Enter key 2x]  and you get a response like this:

HTTP/1.1 301 Moved Permanently
Date: Tue, 07 May 2013 23:29:42 GMT
Server: Apache
X-Pingback: http://www.computerbiology.com/xmlrpc.php
Location: http://www.computerbiology.com/
Content-Length: 0
Content-Type: text/html; charset=UTF-8


Telnet Server

A simple netcat one liner can be used by itself or in scripts to perform banner grabbing.

Telnet banner grab and output to file:
nc -v host.com 23 | tee output.txt | sleep 3

This command opens a verbose netcat connection, tee grabs the stdout and sends the output to a file, and sleep for a few seconds to ensure connection was made and entire banner captured.

Note: output.txt can be changed to a $var for bash scripting to reduce disk I/O

Tuesday, January 10, 2012

Change playback speed/framerate of AVI file

I found a useful command while making time lapse videos with a digital camera.

I set the camera to take a picture once every 30 sec. It converts those pictures into an avi file.

The problem was the hour I spent testing the time lapse only produced 120 'frames' - the avi was playing back at 30 frames per second.. end result being a 4 second video that flashed by the screen.

My first attempts to slow this video down resulted in a 4 second video with a slower frame rate but it truncated the movie and most of the 'frames' were missing.

mencoder -speed .25 -ovc copy movie_in.avi -o movie_out.avi

The end result of this command is a longer video file, because the speed was slowed down, this way each picture 'frame' is on the screen longer. The -speed option is expressed in a percentage of the original speed.

Adjust the .25 to 1 and you have the output .avi the same speed as the original..if you set -speed to 3 the framerate is faster.


Thursday, October 20, 2011

Clean r57 PHP Shell

The r57 shell (and others) at http://www.xfocus.net.ru/soft/r57.txt has a backdoor.

Clean copy can be found here: 



See original source for base 64 encoded variables, containing javascript back doors. These have been cleaned up in the pastebin above..

Computer Biology

Saturday, September 17, 2011

Tor Proxy and Proxychains = Anonymous Internet Operations

The Tor network is an onion routing project that allows users to send traffic through the network, thus making your Internet traffic appear to come from the Tor exit node, not your real IP.

This article will show you how to use torproxy to tunnel to a Tor exit node, bypassing the rest of the s-l-o-w Tor network, and then use proxychains so that your applications can use this tunnel, and your public IP will appear to be that of the Tor exit node. 

First we need to get the required applications installed.


I will be using Ubuntu 11.04. You will also need to install:
tortunnel (contains torproxy, requires boost libraries)
Boost C++ Libraries

From terminal:
sudo apt-get install proxychains privoxy libboost-all-dev

See notes below if you cant get Boost libraries installed.

Next, download and save tortunnel:

Back to terminal, then extract and install...

tar -xf tortunnel-0.2.tar.gz
 cd tortunnel-0.2

./configure; make;

Watch the install screen and make sure it all goes well. To confirm torproxy is working type: 


You should get a response:

Usage: ./torproxy <ExitNodeIP>


Now that everything is installed, we need to configure privoxy and proxychains so that they work with torproxy.

Configure proxychains.

sudo gedit /etc/proxychains.conf 

Comment out the last line with a # and add the line below:

# defaults set to "tor"
#socks4 9050
socks5 5060

Configure privoxy

sudo gedit /etc/privoxy/config

Find the line that says "forward-socks5" and change it to look like this (including the period):

#      To chain Privoxy and Tor, both running on the same system,
#      you would use something like:
        forward-socks5   /      .

Configure torproxy

To connect to an exit node we first need to find exit node IP.
From the tortunnel website they provide a directory of Tor routers. Look in the directory for a router that has the properties:  "Fast" "Exit" and "Valid"

A directory of Tor routers is located here:

Once you find an exit node IP, run torproxy using that IP, and put an & at the end of the command to start it as a backround job.
./torproxy <ExitNodeIP> &

You should see a result like this: 
torproxy 0.2 by Moxie Marlinspike.
Retrieving directory listing...
Connecting to exit node:
SSL Connection to node complete.  Setting up circuit.
Connected to Exit Node.  SOCKS proxy ready on 5060.

Use tunnel

Once  you see the line "Connected to Exit Node. SOCKS proxy ready on 5060" we can start pushing traffic through that socket.

We configured proxychains to forward traffic to port 5060. To use command line tools use the following syntax:

proxychains telnet google.com 80

proxychains ssh user@example.com

proxychains nmap

Or you can configure Firefox to run through the Tor exit proxy. Click
Edit > Preferences > Network > Settings

Set proxy to "Manual proxy configuration" and specify 5060 as Firefox's SOCKS proxy - this will push all firefox traffic trough the Tor exit node. Confirm this by checking whatismyip.com - it should be the same IP as the exit node you chose.

You may need to download the Boost C++ libraries directly from their website or SourceForge and install it manually. The release package will have detailed install instructions.

Computer Biology

Tuesday, July 5, 2011

Word Frequency Analysis

Simple Bash script used to determine the frequency of words in a text file called "mydatafile".

cat mydatafile \
        | tr '[:punct:]'  ' ' \
        | tr '[:digit:]'  ' ' \
        | tr ' ' '\012' \
        | sort \
        | uniq -c \
        | sort -n \
        | tail -700

Line by line walk through of the above script:

First, cat the text file to the standard output and pipe into a few tr commands.
The first tr removes any punctuation and output piped into a second tr which removes the numbers and the output is piped into a third tr command that places every word (group of letters separated by a ' ' ) on a new line.

The output is run through a sort command, arranging the words in a sorted list and the output is piped into a uniq -c command that counts the unique words outputting two columns; the count and the word, which is piped into a sort -n to sort the list ascending order of words.

The last line cuts the list to only display the top 700 most frequent words.

Tuesday, March 8, 2011

Low Orbit Ion Cannon (LOIC) Analysis

The Primordial Weapon of Cyberwar

The LOIC is a readily available, open-source application used in DDoS attacks; most notably used in the 'Anonymous' attacks against Visa, MasterCard and WordPress. Read more about LOIC attacks here.
"It's true that most of the operations performed under the Anonymous branding have been relatively unsophisticated, albeit effective: the attacks made on MasterCard and others were distributed denial-of-service attacks using a modified version of the Low Orbit Ion Cannon (LOIC) load-testing tool. The modified LOIC enables the creation of large botnets that each user opts into: the software can be configured to take its instructions from connections to Internet relay chat (IRC) chat servers, allowing attack organizers to remotely control hundreds of slave machines and hence control large-scale attacks that can readily knock websites offline."

Once a willing participant hands control over to the IRC channel, LOIC blasts away at a web server, using a loop of HTTP GET requests, TCP connections, and or UDP connections. One person using this application is not enough to bring down a web server, as the server should handle these requests; its when thousands of people use the tool to overwhelm the server that the DoS actually occurs. 

See the links section at the end of this post if you want to read more about the attacks and the 'group' labeled Anonymous.

A screen shot of the original LOIC v. written by Praetox - Note, this early version does not have the remote IRC control feature.

v. - The remote control over IRC feature allows individuals to participate and use their home bandwidth in an attack with no prior 'hacking' knowledge.

The Source

There are two different LOIC's that are popularly downloaded. There are many variants in the wild but all are based on the original code in C#. LOIC has been ported to other languages including Java and JavaScript.

LOIC v.1.0.4
Developed by abatishchev - http://sourceforge.net/projects/loic/

LOIC v.1.1.3
Developed by NewEraCracker - https://github.com/NewEraCracker/LOIC/

Each version has two main modules that do most of the 'work' in the aplication.


As the names imply, these are the two different methods LOIC uses to flood the web server with traffic.

Looking at the source, we can actually see what is happening and the difference between the two popular versions.  

LOIC v.1.0.4 (SourceForge.com)

byte[] buf = System.Text.Encoding.ASCII.GetBytes(String.Format("GET {0} HTTP/1.0{1}{1}{1}", Subsite, Environment.NewLine));
socket.Send(buf, SocketFlags.None);
These lines, neatly wrapped in a While loop, create a variable called buf and send that variable through a socket.

The buf variable is simply the text sent to a web server to make a legitimate request for a document on that server. When placed in the loop this seemingly innocent request starts to get not-so-innocent. One person using this is a load-testing tool but a few hundred people can cause some damage if they all point at one server.

byte[] buf = System.Text.Encoding.ASCII.GetBytes(Data);

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
while (IsFlooding)


socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

while (IsFlooding)

socket.SendTo(buf, SocketFlags.None, RHost);

The first flooding method besides HTTP requests, is the TCP connection, sending random message/data through a TCP connection, again not-so-innocently placed inside a while loop. The other flooding option is creating a UDP connection. The screen shots show a text input field where a user can specify the text they wish to send through the socket. 

LOIC v.1.1.3 (GitHub.com)

byte[] buf = System.Text.Encoding.ASCII.GetBytes(String.Format("GET {0}{1} HTTP/1.1{4}Accept: */*{4}User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0){4}{3}Host: {2}{4}{4}{4}", Subsite, ( AllowRandom ? new Functions().RandomString() : null ), Host, (AllowGzip ? "Accept-Encoding: gzip, deflate"+Environment.NewLine : null), Environment.NewLine));

IPEndPoint RHost = new IPEndPoint(System.Net.IPAddress.Parse(IP), Port);

The updated version performs the same HTTP GET request but this time is spoofs browser headers (Mozilla/4.0(Compatible; MSIE 7.0 Windows NT 6.0), sends a random string as part of the request, allows GZip compression, and as usual you need to end the request with a few Enter keystrokes (Environment.NewLine) just like when you telnet into a web server to make the request manually.

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);


socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


while (IsFlooding)

buf = System.Text.Encoding.ASCII.GetBytes(String.Concat(Data, (AllowRandom ? new Functions().RandomString() : null) ));

socket.SendTo(buf, SocketFlags.None, RHost);
The XXPFlooder is practically the same, except this version concatenates the user input text message with a random string and sends that through either a TCP or UDP connection.

Defend your network from a LOIC attack

Proxies and Tor can't be used in this type of attack because the DoS traffic will overwhelm the proxy or Tor network. This attack exposes the client IP address, as if they were making thousands of legitimate requests. If you are attacked with a DDoS, log every connection attempt that you possibly can.

Defense against this type of DDoS attack include:

- Limit the number of requests per IP address per second.

- Use firewalls that support layer 7 HTTP inspection.

- Ingress Filtering


LOIC on GitHub - pageview traffic from Dec 2010 to present (Mar 2011) Yes, thats 35K page views in Dec 2010. Operation Avenge Assange was launched in Dec 2010, targeting PayPal, Visa, MasterCard and the Swedish Prosecution Authority. The traffic appears to have fallen off since then.

Have a look at download statistics for LOIC hosted on SourceForge. Top downloading country: the United States, top OS: Windows. Its staggering that this is an opt-in, point-and-click attack and the source seems to be concentrated in the United States.




- LOIC DDoS Analysis, Wireshark and Snort

- Operation Payback used LOIC

- DACS Paper on LOIC & Anonymous

- WordPress attacked by LOIC

- More about LOIC

Computer Biology