Archive for the 'Code' Category

Script to automatically detect and ban malicious IPs that try to brute force SSH accounts

Thursday, May 29th, 2008

We’ve noticed that most of our servers have been under heavy attack from random IP addresses to break via SSH.

With the help of the last post on how to ban an IP, and the following python script, you’ll be able to have a cronjob that runs once or twice a day and automagically bans all the offending ips from ever trying to brute force their way in ever again.

touch and make executable a file called “detect_ssh_hostiles”

touch detect_ssh_hostiles
chmod +x detect_ssh_hostiles

Then copy the following code inside:

# Usage:
# python detect_ssh_hostiles [auth.log file path]
#
# Requirement: There should be “ban_ip” and “unban_ip” command availability on the path
#
# Note: you gotta have read permissions on the auth.log file and sudo
#       permissions for the script to ban the ips.

#If an IP meets this number of failed login attemmpts it will be banned
BAN_THRESHOLD = 7
SUSPECTS = {}

#Put here IP addresses you trust, could be making genuine login errors
SAFE_IPS = ['81.73.111.49','101.73.111.160','72.31.171.235','72.36.23.234','82.36.180.210','202.132.82.16']

import os
import sys
import re

BANNED = {}
def loadBanned():
  ”’
  This function will load all the banned IPS into the BANNED Dict.
  It will also count how many times (by mistake) the same IP has
  been banned, and it will unban it, so that it will appear only once.
  ”’
  global BANNED
  command = ’sudo iptables –list –numeric’
  try:
    p = os.popen(command,’rb’)
  except Exception,e:
    print e
    sys.exit(1)

  line = ‘-’

  while line != ”:
    line = p.readline().strip()

    if line.startswith(”DROP”):
      parts = line.split()
      ip = parts[3]

      #add hit or register banned ip
      if BANNED.has_key(ip):
        BANNED[ip]+=1
      else:
        BANNED[ip]=1

  #Make sure banned IPs are banned only once
  for ip in BANNED:
    if BANNED[ip] > 1:
      print “IP %s has been banned %d times” % (ip, BANNED[ip])
      n=BANNED[ip]-1
      while n > 0:
        os.system(”unban_ip %s” % ip)
        print (”unban_ip %s” % ip)
        n=n-1

  p.close()

# —- here we go —-
loadBanned()

#read auth log
logfile = ‘/var/log/auth.log’

if len(sys.argv)==2:
  logfile = sys.argv[1]

command = ‘grep “Failed password for ” %s’ % logfile
#print command

try:
  p = os.popen(command,’rb’)
except Exception,e:
  print e
  sys.exit(1)

line = “123″

while line != ”:
  line = p.readline()

  #Sample line:
  # May 25 03:29:49 main sshd[6933]: Failed password for root from 202.118.236.132 port 54863 ssh2
  pattern = “(.*)(from\s)(\d+\.\d+\.\d+\.\d+)(.*)”
  matchObject = re.match(pattern, line)

  suspect = None
  if matchObject is not None:
    suspect = matchObject.groups()[2]

    #skip safe IPs
    if suspect in SAFE_IPS:
      continue

    if SUSPECTS.has_key(suspect):
      #add a hit
      SUSPECTS[suspect] += 1
    else:
      #add first hit
      SUSPECTS[suspect] = 1

p.close() #close the pipe

print “==”*30

import time
t = time.localtime()
#(2008, 6, 6, 9, 35, 21, 4, 158, 1)

timestr = “%d-%d-%d@%d:%d:%d” % (t[0],t[1],t[2],t[3],t[4],t[5])
print timestr
print “–”*30
if len(SUSPECTS) > 0:
  for suspect in SUSPECTS:
    if SUSPECTS[suspect] >= BAN_THRESHOLD and not BANNED.has_key(suspect):
      print “Banning %s with %d attempts” % (suspect,SUSPECTS[suspect])
      BANNED[suspect]=1
      os.system(”ban_ip %s” % suspect)
    elif BANNED.has_key(suspect):
      print “Ip %s has already been banned” % (suspect)
    else:
      print “Suspect candidate? %s with %d attempts” % (suspect,SUSPECTS[suspect])
else:
  print “Found no suspects to ban”

print “==”*30

Then add this as a cronjob of your root user, and it will automatically ban all those IPs that have tried to break in. See the script for configuration. You can always make some IPs immune to banning by adding them on the SAFE_IPS list.

How to ban/unban ips in linux

Thursday, May 29th, 2008

In case you’re not an iptables guru, you might want to create a couple scripts and put em somewhere on your $PATH. I’ve created two scripts called ban_ip and unban_ip.

Create a file called ban_ip

touch ban_ip
chmod +x ban_ip

Edit it and copy the following code inside:

#!/bin/bash
sudo iptables -A INPUT -s $1 -j DROP
echo IP Address $1 has been banned
echo

To ban an IP, you must invoke

ban_ip <someIpAddressHere>

e.g.

ban_ip 211.32.44.111

And the IP will be banned.

Do the same now for the unban_ip script

touch unban_ip
chmod +x unban_ip

Open your fav. text editor and copy the following code inside:

#!/bin/bash
iptables -D INPUT -s $1 -j DROP
echo Unbanned ip $1
echo

Save it, and use it.

To unban an IP, you must invoke

unban_ip <someIpAddressHere>

e.g.

unban_ip 211.32.44.111

Requirements
Have sudo access, have iptables installed.

Function callbacks in C

Friday, May 2nd, 2008

Ever since I started programming in Javascript, and doing asynchronous function calls, I’ve found myself to be addicted to passing functions as parameters.

I do it a lot in python and php, it’s very easy to do this on all these dynamic typed languages.

I never had this concept of passing functions as parameters, or pointers to functions as parameters when I was a kid in school and we were doing stuff in C or Pascal, I’d deal with it with ifs and switches.

So, this afternoon I decided to read a little bit and give it a try in C.

Here’s some code for future reference If I ever need it, it’s pretty easy.

#include 
void this() { printf(”This\n”); }
void that() { printf(”That\n”); }

int sum(int x, int y) {	return x+y; }

int mul(int x, int y) { return x*y; }

//Function that takes a callback that uses no parameters
void callanother(void (*callback)()) {
  (*callback)();
}

//Function that takes a callback that
//takes 2 int parameters and returns int
int callComplexCallback(int (*callback)(),int a, int b) {
  return (*callback)(a,b);
}

int main (int argc, char** argv) {
  callanother(this);
  callanother(that);

  printf(”\n”);

  int w = 20;
  int h = 30;

  printf(”%d\n”,callComplexCallback(sum,w,h));
  printf(”%d\n”,callComplexCallback(mul,w,h));

  //this also works
  printf(”%d\n”,callComplexCallback((*sum),w,h));
  printf(”%d\n”,callComplexCallback((*mul),w,h));

  return 0;
}

The output is this:

~$ ./a.out
This
That

50
600
50
600

The whole trick is how you define the function that will take the other function as a parameter.

If you have a function:

void whatever();

The function that’s supposed to use “whatever()” like-functions should look:

void useWhateverLikeFunctions(void (*f)()) {
  ...
  (*f)();
}

If you have a callback function that needs parameters, then you define the caller as:

void callerFunction(void (*f),int paramA, int* paramB, char paramC) {
  ...
  (*f)(paramA,paramB,paramC);
}

Then you’d use the function

void someCallback(int a, int* b, char c);

...
callerFunction(someCallback,a,b,c);
...

I know this is the oldest thing in the world to C programmers, but it never crossed my mind before, so here it is for my own personal reference, I hope it serves others.

emacs doesn’t work after Leopard upgrade?

Friday, May 2nd, 2008

After updating from Tiger to Leopard I started getting this error whener I tried to execute emacs:


Fatal malloc_jumpstart() error

The solution was basically to reinstall it with dumpemacs


sudo mv /usr/bin/emacs-i386 /usr/bin/emacs-i386.backup
sudo /usr/libexec/dumpemacs -d
emacs --version
emacs

Via Apple Support Discussions

Blooploader 0.6 is Hardy compatible

Saturday, April 26th, 2008


Blooploader 0.6 running on Hardy. Currently available only via subversion.

For our Linux users, you can safely update to Ubuntu Hardy if the one thing holding your breath was compatibility with the Blooploader.

Currently we run the Blooploader in Linux from source, you just need to have installed, Qt4, sip4, and PyQt4 on your machine. If you are an Ubuntu user this translates to:

  1. Checking out the source from our subversion repository
  2. sudo apt-get install python-sip4 python-qt4 python-qt-4-common
  3. ./run

For those of you that want to try the Blooploader in Ubuntu, and you have no clue on how to use the command line, we promise we’ll have a new .deb installer for our next release now that Hardy has enabled binary packages on their repository for all our dependencies.

The Pirate Bay, err, The Liberty Bay

Saturday, April 26th, 2008


A Screenshot of today’s ThePirateBay.org homepage.
“Hint Hint?” These guys certainly like to piss people off to get media attention and more traffic for that high priced CPM they must have.

read more | digg story