#!/usr/bin/perl
#Copyright (c) 2006, Midwest Connections Inc.
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without 
#modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#		this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#		this list of conditions and the following disclaimer in the documentation
#		and/or other materials provided with the distribution.
#    * Neither the name of the Midwest Connections Inc. nor the names of its
#		contributors may be used to endorse or promote products derived from
#		this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#written by Zane C. Bowers <zanecb@midwest-connections.com>



use strict;
use warnings;
use Net::LDAP;
use Getopt::Std;
use Config::Tiny;
use Term::ReadKey;
use Term::ANSIColor;


#zLDAPhash is property of Zane C. Bowers <vvelox@vvelox.net>
#Copyright (c) 2006, Zane C. Bowers
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without 
#modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#		this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#		this list of conditions and the following disclaimer in the documentation
#		and/or other materials provided with the distribution.
#    * Neither the name of the Zane C. Bowers nor the names of its contributors
#		may be used to endorse or promote products derived from this software
#		without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
sub  zLDAPhash {
	my $mesg = $_[0]; #the object returned from a LDAP search

	#used for holding the data, before returning it
	my %data;

	#builds it
	my $entryinter=0;
	my $max = $mesg->count;
	for ( $entryinter = 0 ; $entryinter < $max ; $entryinter++ ){
        my $entry = $mesg->entry ( $entryinter );
        $data{$entry->dn}={ldap=>{dn=>$entry->dn},internal=>{changed=>0}};
        #builds a hash of attributes
#       my $attrinter=0;
        foreach my $attr ( $entry->attributes ) {
#       while (defined($entry->attributes($attrinter))) {
#               my $attr=$entry->attributes($attrinter);
                $data{$entry->dn}{ldap}{$attr}=[];

                #builds the array of values for the attribute
                my $valueinter=0;
                my @attributes=$entry->get_value($attr);
                while (defined($attributes[$valueinter])){
                        $data{$entry->dn}{ldap}{$attr}[$valueinter]=$attributes[$valueinter];
                        $valueinter++;
                };

#               $attrinter++;
        };
	};

	return %data;
};
	
sub main::HELP_MESSAGE {

	print "\nmwcLDAadd ";
	print " -c " ; print color 'underline' ; print 'customer ID' ; print color 'reset';
	print " -u " ; print color 'underline' ; print 'username' ; print color 'reset';
	print " -p " ; print color 'underline' ; print 'password' ; print color 'reset';
	print " [ -m " ; print color 'underline' ; print 'mac# list' ; print color 'reset'; print " ]";
	print "\n	[ -i " ; print color 'underline' ; print 'ip#' ; print color 'reset'; print " ]";
	print " [ -s ] [ -C "; print color 'underline' ; print 'config file' ; print color 'reset'; print " ]";
	print " [ -e " ; print color 'underline' ; print 'entry' ; print color 'reset'; print " ]\n";
	print "	[ -T (0|1) ]";
	print " [ -t " ; print color 'underline' ; print 'towers list' ; print color 'reset'; print " ] ";
	print " [ -M (0|1) ]\n" ; 

	exit 1;
};

sub main::VERSION_MESSAGE {
    print "mwcLDAadd v. 1.0.4\n";
}

#used for checking if a entry exists
sub LdapEntryExists{
	my $dn=$_[0];
	my $binder=$_[1];
	my $password=$_[2];
	my $server=$_[3];
	my $port=$_[4];

	#connect to the LDAP server
	my %ldapconnection=mwcqbinder($binder, $password, $server, $port, "1");

	#search the LDAP server and return only one entry.
	my $mesg = $ldapconnection{ldap}->search(base=>$dn,filter=>'(objectclass=*)',scope=>'base');

#uncomment to get...
#Can't locate object method "count" via package "Net::LDAP::Unbind" at ./mwcLDA.pl line 76, <STDIN> line 1.
#
#it should just work...
#	$mesg = $ldapconnection{ldap}->unbind;
	
	my %hash=zLDAPhash($mesg);
	my @keys=keys(%hash);
	if (!defined($keys[0])){
		return 0;
	};

	return 1;
};

#quickly binds to a LDAP server and returns it.
sub mwcqbinder{
	my $binder=$_[0];
	my $password=$_[1];
	my $server=$_[2];
	my $port=$_[3];
	my $errorMethode=$_[4];#0 continue and return error
						   #1 exit with error and be verbose
						   #2 exit with error and be quiet

	#sets the port if it is not defined
	if (!defined($port)){
		$port="389";
	};
	
	#sets the $errorMethode if it is not defined
	if (!defined($errorMethode)){
		$errorMethode="1";
	};
	
	my %ldapconnection=();
	
	#connect to the ldap server
	$ldapconnection{ldap} = Net::LDAP->new( $server ) or $ldapconnection{status}=0;
	#checks if the status is equal to 0.
	if (defined($ldapconnection{status}) && $ldapconnection{status} == 0){
		if ($errorMethode == 0){
			$ldapconnection{LONGerror}="Could not contact the server.";
			return 1;
		};
		if ($errorMethode == 1){
			print "Could not contact the server.\n".
				"server: ".$server."\nport: ".$port."\n";			
			exit 1;
		};
		if ($errorMethode == 2){		
			exit 1;
		};
	};

	$ldapconnection{bindMesg} = $ldapconnection{ldap}->bind( $binder, password=>$password, version=>3 );
	if ($ldapconnection{bindMesg}->code) { #check for a failed bind
		if ($errorMethode == 0){
			$ldapconnection{status}=0;
			$ldapconnection{LONGerror}="Could not bind to the server.";
			return %ldapconnection;
		};
		if ($errorMethode == 1){
			print "Could not bind to the server.\nserver: ".$server."\nport: ".$port.
			"\nbinder: ".$binder."\n";
			exit 1;
		};
		if ($errorMethode == 2){
			exit 1;
		};
	}
	
	$ldapconnection{status}=1;
	return %ldapconnection
};

#get the list of options it was ran with and do help check
$Getopt::Std::STANDARD_HELP_VERSION = 1;
my %opts=();
getopts("C:c:u:p:i:m:se:a:d:T:t:M", \%opts);
#C = config
#c = customer ID
#u = user to add
#p = user password
#i = IP#
#	This should be left blank if a initial one is not to be set.
#m = MAC#
#	This should be left blank if a initial one is not to be set.
#M = default MAC allow
#
#e = entry
#	This is a entry in the ini file to look at.
#s = static
#	This entry will be marked as static. This does require a IP# and MAC#.
#t = towers allowed or disallowed
#T = default

#the hash used for holding the config file
my %config;

#gets the config file to use
if(defined($opts{C})){
	$config{file}=$opts{C};
}else{;
	$config{file}=$ENV{HOME}."/.mwcLDArc"
};

#checks if a customer ID was specified and if it is make sure it is numeric
if (defined($opts{c})){
	my $CIDtest=$opts{c};
	$CIDtest=~s/[0123456789]//g;
	if (! $CIDtest eq "" ){
		print "The customer ID# is not completely numeric.\n";
		exit 1	
	};
	$config{customerID}=$opts{c};
};

#checks if a username was defined
if (defined($opts{u})){
	#exits if ()[]*'\" found in a username
	my $usertest=$opts{u};
	$usertest=~s/[\(\)\[\]\*\\\'\"]//g; #' this is here to handle a highlighting bug in Eclipse
	if ($usertest ne $opts{u}){
		print '()[]*\'\" are not allowed in usernames.'."\n";
		exit 1;
	};
	$config{username}=$opts{u};
};


#checks if a password is defined for the user
if (defined($opts{p})){
	$config{userpassword}=$opts{p};
};


#get and checks for a IP# contains the proper characters
if (defined($opts{i})){
	my $IPtest=$opts{i};
	$IPtest=~s/[0123456789\.]//g;
	if (! $IPtest eq "" ){
		print "The IP# contains illegal characters.\n";
		exit 1	
	};
	
	$config{ip}=$opts{i};
};
	

#get and checks the MAC and makes sure it contains the proper characters
if (defined($opts{m})){
	my $IPtest=$opts{m};
	$IPtest=~s/[0123456789:abcdefABCDEF,\!]//g;
	if (! $IPtest eq "" ){
		print "The MAC# contains illegal characters.\n";
		exit 1	
	};
	
	my @macs=split(/,/,$opts{m});

	$config{macsAllowed}="";
	$config{macsDisallowed}="";

	#splits them into allowed and disallowed
	#any thing begining with ! is disallowed
	#any thing else is allowed
	my $count=0;
	my $DAcount=0;
	my $Acount=0;
	while (defined($macs[$count])){
		my $macTest=$macs[$count];	
		$macTest=~s/^!//;
		if($macTest ne $macs[$count]){
			if ($DAcount >= 1){
				$config{macsDisallowed}=$config{macsDisallowed}.",".$macTest;
			}else{
				$config{macsDisallowed}=$macTest;
			};
			$DAcount++;
		}else{
			if ($Acount >= 1){
				$config{macsAllowed}=$config{macsAllowed}.",".$macTest;
			}else{
				$config{macsAllowed}=$macTest;
			};
			$Acount++;
		};
		$count++;
	};
}else{
	$config{macsAllowed}="";
	$config{macsDisallowed}="";
};

#if the -M switch is used, 
if (defined($opts{M})){
	my $Mtest=$opts{M};
	$Mtest=~s/[01]//g;
	if (! $Mtest eq "" ){
		print "The MAC allow default is set to something other than 0 or 1\n";
		exit 1	
	};
	$config{Mdefault}=$opts{M};
}else{
	$config{Mdefault}="1";
};

#get the default tower allow
if (defined($opts{T})){
	my $Ttest=$opts{T};
	$Ttest=~s/[01]//g;
	if (! $Ttest eq "" ){
		print "The tower default is set to something other than 0 or 1\n";
		exit 1	
	};
	
	$config{Tdefault}=$opts{T};
}else{
	$config{Tdefault}="1";
};

#gets the allowed and disallped towers
if (defined($opts{t})){
	my @towers=split(/,/,$opts{t});

	$config{towersAllowed}="";
	$config{towersDisallowed}="";

	#splits them into allowed and disallowed
	#any thing begining with ! is disallowed
	#any thing else is allowed
	my $count=0;
	my $DAcount=0;
	my $Acount=0;
	while (defined($towers[$count])){
		my $towerTest=$towers[$count];	
		$towerTest=~s/^!//;
		if($towerTest ne $towers[$count]){
			if ($DAcount >= 1){
				$config{towersDisallowed}=$config{towersDisallowed}.",".$towerTest;
			}else{
				$config{towersDisallowed}=$towerTest;
			};
			$DAcount++;
		}else{
			if ($Acount >= 1){
				$config{towersAllowed}=$config{towersAllowed}.",".$towerTest;
			}else{
				$config{towersAllowed}=$towerTest;
			};
			$Acount++;
		};
		$count++;
	};
}else{
	$config{towersAllowed}="";
	$config{towersDisallowed}="";
};


#checks for which entry to use in the config file.
#_ means Config::Tiny will check the root of the config file.
if (defined($opts{e})){
	$config{entry}=$opts{e};
}else{
	$config{entry}="_";
};

#checks if it is static or not.
#If $config{static} is defined it is treated as true regardless of the value.
#It needs to have MAC# and IP#.
if (defined($opts{s})){
	$config{static}="true";
	
	if (!defined($config{ip}) || !defined($config{mac})){
		print "MAC# or IP# not defined for static entry.\n";
		exit 1;
	};
};	

#makes sure everything required is present
if (!defined($config{userpassword}) || !defined($config{username}) || !defined($config{customerID})){
	print "Not enought fields specfieid.\nUsername, customer ID, and/or password need specified.\n";
	exit 1;
};
	

#loads INI file.
my $rc=Config::Tiny->new();
$rc=Config::Tiny->read($config{file});

#INI info
#LDAPserver = the IP# of the LDAP server
#LDAPuser = the user to connect as
#baseDN = the base DN containing the DHCP users
#LDAPpassword = the password for connecting to LDAP... if thise is left blank, it will be asked for.

#reels the INI vars into $config
my @INIvars=("LDAPserver","LDAPuser","baseDN","LDAPpassword","LDAPport");
my @INIvars_migrate=@INIvars;#we need to add ENVpass to the list, but it is not required
push(@INIvars_migrate,"ENVpassword");
my $count=0;
while (defined($INIvars_migrate[$count])){
	if (defined($rc->{_}->{$INIvars_migrate[$count]})){
		$config{$INIvars_migrate[$count]}=$rc->{_}->{$INIvars_migrate[$count]};
	};
	$count++;
};

#reels entry specific vars in
if ($config{entry} ne "_"){
	$count=0;
	while (defined($INIvars[$count])){
		if (defined($rc->{$config{entry}}->{$INIvars[$count]})){
			$config{$INIvars[$count]}=$rc->{$config{entry}}->{$INIvars[$count]};
		};
		$count++;
	};
};

if (!defined($config{LDAPserver})){
	print "No LDAP server defined in $config{file} or select a different entry.\n";
	exit 1;
};

if (!defined($config{LDAPuser})){
	print "No LDAP bind defined in $config{file} or select a different entry.\n";
	exit 1;
};

#gets the password from the enviroment if needed.
if (defined($config{ENVpassword})){
	$config{LDAPpassword}=$ENV{LDAPpassword};
}else{
	if (!defined($config{LDAPpassword})){
		ReadMode('noecho');
		print $config{LDAPuser}."\nLDAP password:";
		$config{LDAPpassword}=ReadLine(0);
		print "\n";
	};
};

if (!defined($config{LDAPport})){
	$config{LDAPport}="389";
};

chomp($config{LDAPpassword});

#exits if the action is add and the user does exist
$config{DHCPuserDN}="uid=".$config{username}.",".$config{baseDN};
if  (LdapEntryExists($config{DHCPuserDN},$config{LDAPuser},$config{LDAPpassword},
	$config{LDAPserver},$config{LDAPport})){
	
	print "\nUser '".$config{username}."' all ready exists.\n";
	exit 1;
};


my $newEntry = Net::LDAP::Entry->new;

#builds the entry
$newEntry->dn($config{DHCPuserDN});
$newEntry->add(objectClass=>['simpleSecurityObject','mwcDHCP','top'],
	uid=>$config{username},
	userPassword=>$config{userpassword},
	customerIDnumber=>$config{customerID},
	mwcDHCPtowerDefaultAllow=>$config{Tdefault},
	mwcDHCPmacDefaultAllow=>$config{Mdefault}
);

#adds the allowed list to it if needed
if (!$config{macsAllowed} eq ""){
	$newEntry->add(mwcDHCPmacsAllowed=>$config{macsAllowed});
};

#adds the disallowed mac list if needed
if (!$config{macsDisallowed} eq ""){
	$newEntry->add(mwcDHCPmacsDisallowed=>$config{macsDisallowed});
};
		
#adds the allowed tower list to it if needed
if (!$config{towersAllowed} eq ""){
	$newEntry->add(mwcDHCPtowersAllowed=>$config{towersAllowed});
};
	
#adds the disallowed tower list if needed
if (!$config{towersDisallowed} eq ""){
	$newEntry->add(mwcDHCPtowersDisallowed=>$config{towersDisallowed});
};
	
#tells it that this will be added.
$newEntry->changetype('add');

#binds to the server
my %ldapconnection=mwcqbinder($config{LDAPuser}, $config{LDAPpassword}, $config{LDAPserver}, $config{LDAPport}, "1");
	
#adds the new entry
my $result=$newEntry->update($ldapconnection{ldap});
	
#checks for an error and prints it if there is one
if (!${$result}{errorMessage} eq ""){
	print "\nLDAP error.\n	".${$result}{errorMessage}."\n";
	exit 1;
}else{
	print "Successfully added...\nusername: ".$config{username}."\npassword: ".$config{userpassword}.
			"\nCID: ".$config{customerID}."\n";
};

exit 0;

#-----------------------------------------------------------
# POD documentation section
#-----------------------------------------------------------

=head1 NAME

mwcLDAadd - add a  DHCP users in a LDAP ldap.

=head1 SYNOPSIS

mwcLDA B<-c> customerID# B<-u> username B<-p> password [B<-m> MAC# list]
[B<-i> ip#] [B<-s>] [B<-C> config file] [B<-e> entry] [B<-T> (0|1)] [B<-t> tower list]
[B<-M> (0|1)]

=head1 OPTIONS

=item -c customerID#

This is the customer ID# that a entry is for.

=item -u username

This is the username that will be used for when some one tries to log into the account.

=item -p password

This is the password for the user.

=item -m MAC# list

This is a comma seperated list of MAC#s.

=item -i IP#

The IP# for a static entry.

=item -s

Tells it to make this a static entry.

=item -C config file

This is the config the options will be read from. See the config file section for more information.

=item -e entry

this is the entry to use in the config file. If it not specified, it will check the root.

=item -T (0/1)

0 means it will be disallowed by default. 1 means will be allowed by default. If set to disallow
it will disallow any attempts to log on to any towers that is not in the list. If set to allow
it will do the oppasite.

=item -t tower list

This is a comma seperated list of towers that a account can log on to.

=item -M (0/1)

0 means it will be disallowed by default. 1 means will be allowed by default. If set to disallow,
any clients that try to log on with a MAC# not listed in the list will be disallowed. If set to
allow, it will do the oppasite.

=head1 CONFIG FILE

The config file is a .ini file. The default config file is F<~/.mwcLDArc>. The entry over rides
any thing found in the root for the .ini file.

=item LDAPserver

This is the IP# of the server that will be connected to.

=item baseDN

This is the DN that the users will be put into.

=item LDAPuser

This is the bind that will be made to the LDAP server.

=item LDAPpassword

This is the password that will be used for connecting to the LDAP server. This this is left out,
it will prompt for a password.

=item LDAPport

This is the port that will be used for connecting 

=item ENVpassword

If this is defined, it will check for the presence of a LDAPpassword enviromental variable.

=item Example:
	
	LDAPserver=192.168.50.99
	;a freaking comment
	basedn=ou=users,ou=dhcp,ou=network,dc=fu,dc=bar
	
	[americanus]
	LDAPuser=cn=bufo americanus,ou=employees,dc=fu,dc=bar
	
	[alvarius]
	LDAPuser=cn=bufo alvarius,ou=employees,dc=fu,dc=bar
	LDAPpassword=somethingannoyinglyeasytofreakingremember

=head1 LDAP notes

See http://cpan.org/authors/id/M/MW/MWCZANECB/ for the required schema
and more info on it.

=head1 TODO

=item Implement the static IP setting. Currently the -i switch is unused.

=item Implement a set option for -a.

=item Add more toad references.

=item Fix some of the funky POD formating.

=item Allow SASL and SSL.

=head1 AUTHOR

Copyright (c) 2006, Midwest Connections Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
    * Neither the name of the Midwest Connections Inc. nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

written by Zane C. Bowers <zanecb@midwest-connections.com>

=head1 SCRIPT CATEGORIES

Unix/System_administration

=head1 OSNAMES

any

=head1 README

mwcLDA is adding DHCP users in a LDAP directory. This is for use with mwcDHCPauth.

=head1 CHANGE LOG

=head 2006-10-24

=item version 1.0.5

Added in enviromental based password.

=head2 2006-10-23

=item cleanup

Cleaned up the POD and help a bit.

=head2 2006-10-16

=item POD

Removed the LDAP schema from the POD.

=head2 2006-10-02

Copied from mwcLDA and removed the uneeded parts.

=head2 2006-09-13

Fixed a few config file reading issues. Bumped the version to 1.0.3.

=cut

#-----------------------------------------------------------
# End of POD documentation
#-----------------------------------------------------------
