DHCP Test – Perl

Ok, this one is actually a really useful script I wrote when I was testing a DHCP server for work. It will run on Linux and repeatedly mac spoof and request a new IP.

CODE:

#!/usr/bin/perl
 
use Getopt::Std;
use Getopt::Long;
 
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
 
sub printIntro {
	print "DHCP Testing tool.\n";
	print "\tIf at any time you require help using this application, use the switch -h\n";
}
 
sub printHelp {
	print "\n\nUsage Options:\n";
	print "\t-i   :   Use the specified interface (defaults to eth0)\n";
	print "\t-h   :   Displays this help file\n";
	print "\t *** PLEASE NOTE THIS SCRIPT REQUIRES ROOT PRIVILIGES ***\n";
}
 
sub generateByte {
	my $byte = sprintf "%x", int(rand(255));
	if(length($byte) == 1) {
		$byte .= '0';
	}
	return $byte
}
 
sub generateMAC {
	my $mac = "000B0A" . generateByte() . generateByte() . generateByte();
	return $mac;
}
 
sub dropNIC {
	if(system('ifconfig ' . $opt_i . ' down')) { 
		print "Cannot drop interface $opt_i\n";
		die;
	}
}
 
sub raiseNIC {
	if(system('ifconfig ' . $opt_i . ' up')) {
		print "Cannot raise interface $opt_i\n";
		die;
	}
}
 
sub refreshNIC {
	if(system('dhclient ' . $opt_i)) {
		print "Cannot refresh network address\n";
		die;
	}
}
 
sub shiftMAC {
	if(system('ifconfig ' . $opt_i . ' hw ether ' . generateMAC())) {
		print "Cannot set new MAC address\n";
		die;
	}
}
 
sub getMAC {
	my $rec = `ifconfig ` . $opt_i . ` | grep "HWaddr"`;
	my ($iface, $link, $type, $label, $mac) = split(/\s+/, $rec);
	return $mac;
}
 
sub getIP {
	my $ip = ((`/sbin/ifconfig eth0`)[1] =~ /inet addr:(\S+)/);
	return $1;
}
 
sub getTime {
	($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
	my $theTime = "$hour:$minute:$second";
	return $theTime;
}
 
sub getDate {
	($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
	$year = 1900 + $yearOffset;
	my $theDate = "$weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
	return $theDate;
}
 
getopts('i:c:h');
 
printIntro();
if($opt_h) {
	printHelp();
	die;
}
 
if(!$opt_i) {
	$opt_i = 'eth0';
}
 
open(MYFILE, '>>DHCP.csv');
print MYFILE "DATE,TIME,IP,MAC\n";
 
while(1) {
	dropNIC();
	shiftMAC();
	raiseNIC();
	refreshNIC();
	print MYFILE '"' . getDate() . '",' . getTime() . "," . getIP() . "," . getMAC . "\n";
}
 
close(MYFILE);