#!/usr/bin/perl
# Copyright (C) beplacid.net
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.


use strict;

# ifconfig eth2 hw ether be:ef:be:ef:be:ef
my $NAME = "macspoof.pl";
my $VERSION = "0.2 (Alpha)";

# Check we're root
if($ENV{'USER'} ne 'root') { print "You must be root!\n"; exit(1); }

# valid hex chars used to create our random mac address
my @CHARS = ('A','B','C','D','E','F',0,1,2,3,4,5,6,7,8,9);

# BEGIN FUNCTIONS

# return a random hexadecimal character
sub random_hex_char {
	return @CHARS[int(rand() * scalar(@CHARS))];
}

# creates a random MAC address
sub generate_mac {
	my $i = 0;
	my $MAC = "";
	while($i < 6){
		$MAC .= random_hex_char();
		$MAC .= random_hex_char();
		$MAC .= ":" unless $i == 5;
		$i++;
	}
	return $MAC;
}

# sets the mac address of an inteface.
# expects a scalar interface identifier and the mac address
sub set_iface_mac {
	my ($iface,$mac) = @_;
	print "Setting the MAC address of '$iface' to '$mac'\n";
	system("ifconfig '$iface' hw ether '$mac'");
	if($? != 0) {
		# execution failed
		print "Error setting MAC address for '$iface'!\n";
		exit(1);
	}
}

# parse the arguments provided to the script
sub parse_args {
	if(scalar(@ARGV) != 1){ print_usage(); exit 1; }
	elsif(@ARGV[0] eq '-h'){ print_usage(); exit 0; }
}

sub print_usage {
	print "Usage: $NAME interface
Reassigns the MAC (hardware) address of the given interface.\n";
}

sub main {
	parse_args();
	my $MAC = generate_mac();
	set_iface_mac($ARGV[0],$MAC);
}

main();
