#!/usr/bin/env perl
# ipchecker - looks for expired SSL's and free IP's.
# jlavoy - 04.17.2012
# Please report bugs to bugs.hostgator.com
# (C) 2012 HostGator.com, LLC
use strict;
use Date::Parse;
use Text::Table;

my $timenow = time();

open(my $DAT, "<", "/etc/reservedips");
	my @reservedips = <$DAT>;
close($DAT);

my %ips;
my %usedips;
open($DAT, '-|', "/sbin/ifconfig");
	while(<$DAT>) {
		if ( /inet\saddr:([0-9\.]+)/ ) {
			if (( $1 !~ /^10\./ ) && ( $1 !~ /^127\./ ) && ( ! grep(/^$1$/, @reservedips)) ) {
				$ips{$1} = 0;
				$usedips{$1} = 0;
			}
		}
	}
close($DAT);

open($DAT, "<", "/etc/trueuserdomains");
	while(<$DAT>) {
		if ( /^([0-9a-zA-Z\.\-]+):\s+([a-zA-Z0-9]+)$/ ) {
			my $user = $2;
			open(my $DAT2, "<", "/var/cpanel/users/$user") or next;
				while(<$DAT2>) {
					if ( /^IP=([0-9\.]+)$/ ) {
						my $assignedip = $1;
						if ( grep(/^$assignedip$/, keys %ips) ) {
							delete($ips{$assignedip});
						}
					}
				}
			close($DAT2);
		}
	}
close($DAT);

my $total = keys %ips;
print "[*] System has $total free IP addresses:\n";
foreach my $ip ( keys %ips ) {
	print "\t- $ip\n";
}
print "\n";

my %domains;
my %expirations;

my @files = </usr/share/ssl/certs/*.crt>;
foreach my $file (@files) {
	$file =~ s/\s+//g;
	$file =~ s/\*/\\\*/g;
	open($DAT, "-|", "/usr/bin/openssl x509 -text -noout -in $file") or print "wat\n";
		while(<$DAT>) {
			if ( /^\s+Not\sAfter\s:\s([0-9a-zA-Z\:\s]+)$/ ) {
				my $expiration = $1;
				my $epoch = str2time($expiration);
				if ( $epoch < $timenow ) {
					my @parts = split(/\//, $file);
					my $domain = pop(@parts);
					$domain =~ s/\.crt//g;
					chomp(my $owner = `/scripts/whoowns $domain`);
					open(my $DAT2, "<", "/var/cpanel/userdata/$owner/${domain}_SSL") or next;
						while(<$DAT2>) {
							if ( /^ip:\s([0-9\.]+)$/ ) {
								if ( grep(/^$1$/, keys %usedips) ) {
									$domains{$domain} = $1;
									$expirations{$domain} = $epoch;
								}
							}
						}
					close($DAT2);
				}
			}
		}
	close($DAT);
}

my $totaldomains = keys %domains;
if ( $totaldomains > 0 ) {
	my $tb = Text::Table->new("\t", "Domain", "\t", "IP", "\t", "Expiration");
	print "[!] Expired SSL's found -\n";
	$tb->load(["\t", "------------------------", "\t", "------------------------", "\t", "------------------------"]);
	foreach my $domain ( keys %domains ) {
		$tb->load(["\t", "$domain", "\t", "$domains{$domain}", "\t", scalar localtime($expirations{$domain})]);
	}
	print $tb;
} else {
	print "[*] No expired SSL's Found.\n";
}
print "\n";
