Monday, November 24, 2008

Event driven programming with Perl

By using hash table and function pointers you can implement an event dispatcher in Perl. With this programming style you can reduce conditions statements like if-else and switch.

#!/usr/bin/perl -w
use strict;

die "Syntax: test.pl action data\n" unless @ARGV > 1;

my %handlers;

$handlers{"up"} = \&OnUpper;
$handlers{"lo"} = \&OnLower;

die "Invalid ation!\n" unless exists $handlers{$ARGV[0]};

# The dispatcher
$handlers{$ARGV[0]}->($ARGV[1]);

sub OnUpper
{
  my $param = shift;
  print(uc "$param\n");
}

sub OnLower
{
  my $param = shift;
  print(lc "$param\n");
}

Saturday, November 22, 2008

Configure IPFW

IPFirewall is the default firewall for Mac OSX and FreeBSD. Use the ipfw command tool to define firewall rules for your computer.

This shell script creates my firewall rules when I am using insecure networks in my professional work. The script configuring firewall logging and create rules to block traffic on network all interfaces except loopback interface and outbound traffic for HTTP, HTTPS, SSH, SMTP, NTP and DNS. 

#!/bin/sh

sudo ipfw -q flush

if [ "$1" = "on" ]; then
  sudo sysctl -w net.inet.ip.fw.verbose=2 > /dev/null
  sudo ipfw -q add allow ip from me to any via lo0

  sudo ipfw -q add allow tcp from me to any 80 keep-state out
  sudo ipfw -q add allow tcp from me to any 443 keep-state out
  sudo ipfw -q add allow tcp from me to any 22 keep-state out
  sudo ipfw -q add allow tcp from me to any 993 keep-state out
  sudo ipfw -q add allow tcp from me to any 25 keep-state out

  sudo ipfw -q add allow udp from me to any 123 keep-state out
  sudo ipfw -q add allow udp from me to any 53 keep-state out
  sudo ipfw -q add deny log all from any to any
  echo "Firewall is activated"
else
  sudo sysctl -w net.inet.ip.fw.verbose=0 > /dev/null
  echo "Firewall is disabled"
fi