#! /usr/bin/perl
###########
# dominfo
# Provides various pieces of information about a domain. Works on both cPanel and Plesk.
# WIKI
# http://git.toolbox.hostgator.com/dominfo/dominfo
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011 - HostGator.com, LLC
###########
#
# Provides general information about a domain.
#              

use strict;
use Getopt::Long qw (:config pass_through);
use DBI;
use File::Find;
use Term::ANSIColor;

my $isplesk;
my $iscpanel;
my $subs;
my $du;
my $scripts;
my $dbh;
my $help;

GetOptions ('subs' => \$subs, 'du' => \$du, 'scripts' => \$scripts, 'help' => \$help);

if ($help) {
	help();
}

if (eval {require XML::Simple;}) {
	require XML::Simple;
} else {
	print "[!] Failed to load the necessary modules for this script to function properly. Plese install XML::Simple via 'cpan install XML::Simple'\n";
	exit 1;
}

if ( -s "/etc/psa/.psa.shadow" ){
	$isplesk = 1;
	open(FILE, "</etc/psa/.psa.shadow") or die "Unable to open /etc/psa/.psa.shadow!\n";
	my $mysqlpass = do { local $/; <FILE> };
	close(FILE);
	chomp $mysqlpass;
	
	$dbh = DBI->connect("DBI:mysql:database=psa;host=localhost","admin","$mysqlpass") or die "couldnt connect";
} elsif ( -s "/usr/local/cpanel/cpanel"){
	$iscpanel = 1;
	if (eval {require cPanel::PublicAPI;}) {
		require cPanel::PublicAPI;
	} else {
		print "[!] Failed to load the necessary modules for this script to function properly. Please install cPanel::PublicAPI via 'perl <(GET toolbox.hostgator.com/fixes/fix-cpanelapi)'\n";
		exit 1;
	}
} else {
        print "[!] Neither cPanel nor Plesk detected.\n";
        exit 1;
}

if ($#ARGV != 0) {
	help();
}

sub help {

	print "dominfo version 1.0\n";
	print "Provides various bits of information for a domain.\n\n";
	print "Usage: dominfo <domain>\n\n";
	print "Optional switches:\n";
	print "          --subs     - Process any subdomains that belong to the domain.\n";
	print "          --du       - Perform disk usage calculations for the document root.\n";
	print "          --scripts  - Perform a 'common scripts' check within the document root.\n";

	exit 1;
}

my @ipc = grep (/inet addr:/, `ifconfig`);
my @ips;
foreach my $t (@ipc) {
	my $ip = (split(/:/, $t))[1];
	$ip = (split(/ /, $ip))[0];
	if ($ip !~ m/^127\.|^10\./){
		push @ips, $ip;
	}
}

main();

sub main {

	my $domain = lc ($ARGV[0]);

	if ($iscpanel) {
		process_cpanel($domain);
	} else {
		process_plesk($domain);
	}
}

sub process_cpanel {

	my $domain = shift;
	my $docroot = cpanel_docroot($domain);
	
	if (!$docroot) {
		print "[!] '".colorify($domain, "red")."' does not appear to be setup on the server.\n";
		exit 1;
	}

	my $user = (split('/', $docroot))[2];

	if (-s "/var/cpanel/users/$user") {
		print "\n[*] Domain name: ".colorify($domain, "green")."\n";
		print "[+] cPanel username: ".colorify($user, "green")."\n";

		my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $homedir, $shell) = getpwnam ($user);

		my $primary;
		my $ip;
		my @subdomains = getsubs_cpanel($domain, $user);

		open (UFILE, "/var/cpanel/users/$user");
		foreach my $line (<UFILE>) {
			chomp $line;
			if ($line =~ m/^DNS=/) {
				$primary = $line;
				$primary =~ s/DNS=//g;
			}
			if ($line =~ m/^IP=/) {
				$ip = $line;
				$ip =~ s/IP=//g;
			}
		}
		close(UFILE);

		print "\n".colorify("Domain", "green")." Information:\n\n";
		if ($domain eq $primary || $domain eq "www.$primary") {
			print "\t".colorify($domain, "green")." is the ".colorify("primary", "red")." domain of the account.\n";
		} else {
			print "\t".colorify($domain, "yellow")." is an ".colorify("addon/subdomain/parked", "green")." domain.\n";
		}

		print "\tThe IP address this domain is setup on is: ".colorify($ip, "green")."\n";
		if (cpanel_isdedi($ip)) {
			print "\tThis IP is a ".colorify("dedicated", "red")." address on the server.\n";
		} else {
			print "\tThis IP is ".colorify("not", "red")." a dedicated address on the server.\n";
		}
		print "\tThere are ".colorify(scalar(@subdomains), "green")." subdomain(s) setup under '$domain'.\n";
		print "\tThe document root is: ".colorify($docroot, "green")."\n\n";

		if (-s "$homedir/etc/$domain/passwd") {
			open (EFILE, "$homedir/etc/$domain/passwd");
			1 while <EFILE>;
			my $lcount = $.;
			close (EFILE);
			print colorify("Email", "green"). " Accounts: $lcount\n\n";
		}
		
		findssl_cpanel($domain);

		if (-d "$docroot") {
			if ($du) {
				print "[+] Disk usage information:\n\n";
				print "\tCalculating size of the document root ... ";
				my $du = `du -sh \"$docroot\"`;
				chomp $du;
				$du =~ s/\s$docroot//g;
				print "$du\n";

				if (-d "$homedir/mail/$domain/") {
					print "\tCalculating size of the maildir ... ";
					my $du = `du -sh \"$homedir/mail/$domain/\"`;
					chomp $du;
					$du =~ s/\s$homedir\/mail\/$domain\///g;
					print "$du\n";
				}
			}

			if ($scripts) {
				my @output;
				my $dbcheck = 0;
				if (-e "/root/bin/dbchecker") {
					print "\n[+] Common scripts installed in the document root:\n\n";
					$dbcheck = 1;
					@output = `dbchecker --dir $docroot`;
				} elsif (-e "/root/bin/dbcheck") {
					print "\n[+] Common scripts installed in the document root:\n\n";
					$dbcheck = 1;
					@output = `dbcheck --dir $docroot`;
				} else {
					print "[!] DBChecker not found on server. Skipping common script checks...\n";
				}
			
				if (scalar(@output) < 3 and $dbcheck) {
					print "\t".colorify("None", "red")."\n";
				} else {
					foreach my $line (@output) {
						if (($line =~ m/\[!\]/) or ($line =~ m/\[\+\]/)) {
							$line =~ s/^\[!\]//g;
							$line =~ s/^\[\+\]//g;
							print "\t$line";
						}
					}
				}
			}
		}

		if (-e "/root/bin/dnschecker") {
			print "\n";
			my @output = `dnschecker --domain $domain`;
			foreach (@output) {
				if ((m/^\[!\]/) or (m/^\[\+\]/)) {
					print $_;
				} elsif (m/^\[\*\]/) {
					if (m/$domain/){
						print $_;
					}
				}
			}
			print "\n";
		} else {
			print "[!] Dnschecker not found on server. Skipping resolution checks...\n\n";
		}

		if ($subs) {
			foreach (@subdomains) {
				process_cpanel ($_);
			}
                }
	} else {
		print "\tcPanel username: ".colorify("NONE", "red")."\n";
	}
}

sub process_plesk {

	my $domain = shift;
	my $docroot = plesk_docroot($domain);
	
	if (!$docroot) {
		print "[!] '".colorify($domain, "red")."' does not appear to be setup on the server.\n";
		exit 1;
	}
	
	my $querystring = qq^select sys_users.login from sys_users inner join hosting on hosting.sys_user_id=sys_users.id where hosting.www_root = '$docroot' limit 1;^;
	my $query = $dbh->prepare($querystring);
	$query->execute();

	my $user = $query->fetchrow_array;

	if ($user) {
		print "\n[*] Domain name: ".colorify($domain, "green")."\n";
		print "[+] Plesk username: ".colorify($user, "green")."\n";

		my $primq = qq^select domains.name from hosting inner join sys_users on hosting.sys_user_id=sys_users.id inner join domains on domains.id=hosting.dom_id where sys_users.login = '$user' and domains.webspace_id=0 limit 1;^;
		my $query = $dbh->prepare($primq);
		$query->execute();
		my $primary = $query->fetchrow_array;

		my $ipq = qq^select val from dns_recs where host = '$domain.'and type = 'A' limit 1;^;
		my $query = $dbh->prepare($ipq);
		$query->execute();
		my $ip = $query->fetchrow_array;

		my @subdomains = getsubs_plesk($domain, $user);

		print "\n".colorify("Domain", "green")." Information:\n\n";
		if ($domain eq $primary || $domain eq "www.$primary") {
			print "\t".colorify($domain, "green")." is the ".colorify("primary", "red")." domain of the account.\n";
		} else {
			print "\t".colorify($domain, "yellow")." is an ".colorify("addon/subdomain/parked", "green")." domain.\n";
		}

		print "\tThe IP address of the account is: ".colorify($ip, "green")."\n";
		if (plesk_isdedi($ip)) {
			print "\tThis IP is a ".colorify("dedicated", "red")." address on the server.\n";
		} else {
			print "\tThis IP is ".colorify("not", "red")." a dedicated address on the server.\n";
		}
		print "\tThere are ".colorify(scalar(@subdomains), "green")." subdomain(s) setup under '$domain'.\n";
		print "\tThe document root is: ".colorify($docroot, "green")."\n\n";

		my $emailq = qq^SELECT mail.mail_name FROM mail INNER JOIN domains ON domains.id=mail.dom_id WHERE domains.name='$domain';^;
		my $query = $dbh->prepare($emailq);
		$query->execute();
		my $lcount = $query->rows;
    
		if ($lcount) {
			print colorify("Email", "green"). " Accounts: $lcount\n\n";
		}
        
		findssl_plesk($domain);

		if (-d "$docroot") {
			if ($du) {
				print "[+] Disk usage information:\n\n";
				print "\tCalculating size of the document root ... ";
				my $du = `du -sh $docroot`;
				chomp $du;
				$du =~ s/\s$docroot//g;
				print "$du\n";
	    		
				if (-d "/var/qmail/mailnames/$domain/") {
					print "\tCalculating size of the maildir ... ";
					my $du = `du -sh \"/var/qmail/mailnames/$domain/\"`;
					chomp $du;
					$du =~ s/\/var\/qmail\/mailnames\/$domain\///g;
					print "$du\n";
				}
			}
            
			if ($scripts) {
				my @output;
				my $dbcheck = 0;
				if (-e "/root/bin/dbchecker") {
					print "\n[+] Common scripts installed in the document root:\n\n";
					$dbcheck = 1;
					@output = `dbchecker --dir $docroot`;
				} elsif (-e "/root/bin/dbcheck") {
					print "\n[+] Common scripts installed in the document root:\n\n";
					$dbcheck = 1;
					@output = `dbcheck --dir $docroot`;
				} else {
					print "[!] ".colorify("DBChecker", "red")." not found on server. Skipping common script checks...\n";
				}

				if (scalar(@output) < 3 and $dbcheck) {
					print "\t".colorify("None", "red")."\n";
				} else {
					foreach my $line (@output) {
						if (($line =~ m/\[!\]/) or ($line =~ m/\[\+\]/)) {
							$line =~ s/^\[!\]//g;
							$line =~ s/^\[\+\]//g;
							print "\t$line";
						}
					}
				}
			}
		}

		if (-e "/root/bin/dnschecker") {
			print "\n";
			my @output = `dnschecker --domain $domain`;
			foreach (@output) {
				if ((m/^\[!\]/) or (m/^\[\+\]/)) {
					print $_;
				} elsif (m/^\[\*\]/) {
					if (m/$domain/){
						print $_;
					}
				}
			}
			print "\n";
		} else {
			print "[!] ".colorify("Dnschecker", "red")." not found on server. Skipping resolution checks...\n";
		}

		if ($subs) {
			foreach (@subdomains) {
				process_plesk ($_);
			}
		}
	} else {
		print "\tPlesk username: ".colorify("NONE", "red")."\n";
	}
}

sub findssl_plesk {

	my $domain = shift;
	my @ssls;

	my $sslq = qq^select cert_file FROM certificates INNER JOIN domains on domains.cert_rep_id=certificates.id WHERE domains.name='$domain' OR domains.name='www.$domain';^;
	my $query = $dbh->prepare($sslq);
	$query->execute();
	while (my $row = $query->fetchrow_array){
		push @ssls, "/usr/local/psa/var/certificates/".$row;
	}

	if (scalar(@ssls) > 1){
		print "[+] Found multiple CRT files for $domain on the server. Please be sure to pick the valid one from the following CRTs...:\n";
	} elsif (scalar(@ssls) == 1) {
		print "[+] Found one CRT for $domain on the server.\n";
	} else {
		print "[!] No SSLs found for $domain.\n";
	}

	foreach my $ssl (@ssls) {
		print "$ssl: \n";
		my $validity = valid_crt($ssl);
		if ($validity == 0) { print "\t".colorify($ssl, "green")." - Valid SSL Certificate\n\n"; }
		elsif ($validity == 1) { print "\t".colorify($ssl, "orange")." - Self-signed or Not valid yet.\n\n"; }
		elsif ($validity == 2) { print "\t".colorify($ssl, "red")." - Expired SSL.\n\n"; }
		else { print "\t".colorify($ssl, "red")." - ERROR parsing info.\n\n"; }
	}
}

sub findssl_cpanel {

	my $domain = shift;
	
	my @dirs = ("/etc/ssl/certs/", "/usr/share/ssl/certs/");
	my @ssls;

	File::Find::find(
		{ wanted => 
			sub {
				if($_ =~ /^$domain\.crt$/i or $_ =~ /^www\.$domain\.crt$/i) {
					push @ssls, $File::Find::name;
				}
			}
		}, @dirs
	);

	if (scalar(@ssls) > 1){
		print "[+] Found multiple SSL certificates for ".colorify($domain,"green")." on the server. Please be sure to pick the valid one from the following CRTs...:\n";
	} elsif (scalar(@ssls) == 1) {
		print "[+] Found one SSL certificate for ".colorify($domain,"green")." on the server.\n";
	} else {
		print "[!] No SSL certificate found for ".colorify($domain,"red").".\n";
	}

	foreach my $ssl (@ssls) {
		print "$ssl: \n";
		my $validity = valid_crt($ssl);
		if ($validity == 0) { print "\t".colorify($ssl, "green")." - Valid SSL Certificate\n\n"; }
		elsif ($validity == 1) { print "\t".colorify($ssl, "yellow")." - Self-signed or Not valid yet.\n\n"; }
		elsif ($validity == 2) { print "\t".colorify($ssl, "red")." - Expired SSL.\n\n"; }
		else { print "\t".colorify($ssl, "red")." - ERROR parsing info.\n\n"; }


		open (my $httpconf, "<", "/usr/local/apache/conf/httpd.conf");
		my $grep = (grep(/$ssl/, <$httpconf>))[0];
		if ($grep) {
			print "[+] SSL certificate: $ssl appears to be installed and configured on Apache.\n";
		} else {
			print "[!] SSL certificate: $ssl does not seem to be installed on the server.\n";
		}
	}
}

#Output: 0 = OK - Appears to be valid.
#        1 = Not valid yet (i.e. today is before the start date)
#        2 = Expired       (i.e. today is after the end data)
#        3 = Error

sub valid_crt {

	my $crt = shift;
	my @sslmembers;            
	my $return;

	my $start_date;
	my $start_year;
	my $start_month;
	my $start_day;
	my $end_date;
	my $end_year;
	my $end_month;
	my $end_day;
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	my $now = sprintf("%04d%02d%02d", $year+1900, $mon+1, $mday);
	my %months = ("Jan", 1, "Feb", 2, "Mar", 3, "Apr", 4, "May", 5, "Jun", 6, "Jul", 7, "Aug", 8, "Sep", 9, "Oct", 10, "Nov", 11, "Dec", 12);

	if (lookup_cert_info($crt, \@sslmembers)) {
		return 3;
	}

	my $start = $sslmembers[1];
	$start =~ s/Not Before: //;
	($start_month, $start_day, undef, $start_year, undef) = split (/\s+/, $start);
	$start_date = sprintf("%04d%02d%02d", $start_year, $months{$start_month}, $start_day);

	my $end = $sslmembers[2];
	$end =~ s/Not After : //;
	($end_month, $end_day, undef, $end_year, undef) = split(/\s+/, $end);
	$end_date = sprintf("%04d%02d%02d", $end_year, $months{$end_month}, $end_day);

	if (length($sslmembers[1])) { print "\t$sslmembers[1]\n"; }
	if (length($sslmembers[2])) { print "\t$sslmembers[2]\n"; }
	if (length($sslmembers[3])) { print "\t$sslmembers[3]\n"; }

	if ($sslmembers[0] =~ /Self Signed/) {
		return 1;
	}

	if ($now < $start_date) {
		return 1;
	}
	if ($now > $end_date) {
		return 2;
	}
	return 0;
}

sub lookup_cert_info {

	my $crt = shift;
	my $out = shift;

	my @sslinfo = `openssl x509 -text -in \"$crt\"`;
	my $sslissuer = (grep(/\s*Issuer:/, @sslinfo))[0];
	$sslissuer =~ s/Issuer://g;
	$sslissuer = trimspace($sslissuer);
	my $sslsubject = (grep(/\s*Subject:/, @sslinfo))[0];
	$sslsubject =~ s/Subject://g;
	$sslsubject = trimspace($sslsubject);
	my $sslstart = (grep(/\s*Not Before:/, @sslinfo))[0];
	$sslstart = trimspace($sslstart);
	my $sslend = (grep(/\s*Not After/, @sslinfo))[0];
	$sslend = trimspace($sslend);
	my $dns = (grep(/\s*DNS:/, @sslinfo))[0];
	$dns = trimspace($dns);

	if (length($sslsubject) == 0 or length($sslstart) == 0 or length($sslend) == 0) {
		print "\tFailed to parse SSL info from $crt. Is it a valid certificate?\n";
		return 1;
	}

	if ($sslissuer eq $sslsubject) {
		$sslissuer = "Self Signed";
	}

	push (@{$out}, $sslissuer);
	push (@{$out}, $sslstart);
	push (@{$out}, $sslend);
	push (@{$out}, $dns);
	return 0;
}

sub trimspace {

	my $string = shift;
	chomp $string;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;

	return $string;
}

sub getsubs_plesk {

	my $domain = shift;
	my $user   = shift;
	my @subs;

	my $primq = qq^select name from domains WHERE name LIKE '%$domain';^;
	my $query = $dbh->prepare($primq);
	$query->execute();
	while (my $row = $query->fetchrow_array) {
		if (!($row eq $domain)){
			push @subs, $row;
		}
	}
	return @subs;
}

sub getsubs_cpanel {

	my $domain = shift;
	my $user   = shift;
	my @subs;

	if ( !-s "/root/.accesshash" ) {
		$ENV{'REMOTE_USER'} = 'root';
		system('/usr/local/cpanel/bin/realmkaccesshash');
	}

	my $apic = cPanel::PublicAPI->new();
	my $response = $apic->cpanel_api2_request('whostmgr', { 'module' => 'SubDomain', 'func' => 'listsubdomains', 'user' => $user, }, { 'regex' => $domain }, 'xml');
	my $output = XML::Simple::XMLin($response);

	if (ref($output->{'data'}) eq 'ARRAY'){
		foreach my $obj (@{$output->{'data'}}){
			my $tempu = $obj->{'domain'};
			if (!addonsub($tempu) and !($domain eq $tempu)){
				push (@subs, $tempu);
			}
		}
	} elsif(!($output->{'data'}->{'domain'} eq "")) {
		if (!addonsub($output->{'data'}->{'domain'}) and !($domain eq $output->{'data'}->{'domain'})){
			push (@subs, $output->{'data'}->{'domain'});
		}
	}

	return @subs;
}

sub addonsub {
	#checks to see if the subdomain passed is just the subdomain added by cpanel
	my $ldom = shift;
	# ignore wildcard domains
	if ($ldom =~ m/^\*/){
		return 1;
	}

	open (my $httpconf, "<", "/usr/local/apache/conf/httpd.conf");
	my $grep = (grep(/\bwww\.$ldom\b/, <$httpconf>))[0];
	close ($httpconf);

	$grep =~ s|serveralias||i;
	$grep =~ s|www.$ldom$||i;
	$grep =~ s/^\s+//;
	$grep =~ s/\s+$//;
	
	if (length($grep) > 0){
		return 1;
	} else {
		return 0;
	}
}

sub cpanel_isdedi {

	my $ip = shift;

	if ($ip =~ m/^10\./ || $ip =~ m/^127\./) {
		return 0;
	}

	my $ipcheck1;
	if (-e "/etc/reservedips") {
		open(my $reserves, "<", "/etc/reservedips");
		$ipcheck1 = (grep(/$ip/, <$reserves>))[0];
		close($reserves);
	}

	my $ipcheck2 = `/scripts/isdedicatedip $ip`;
	chomp $ipcheck2;

	if ($ipcheck1) {
		return 0;
	} elsif ($ipcheck2 =~ m/NOT/) {
		return 0;
	} else {
		return 1;
	}
}

sub plesk_isdedi {

	my $ip = shift;

	if ($ip =~ m/^10\./ || $ip =~ m/^127\./) {
		return 0;
	}

	my $ipq = qq^select type FROM ip_pool INNER JOIN IP_Addresses on IP_Addresses.id=ip_pool.ip_address_id WHERE ip_address='$ip' LIMIT 1;^;
	my $query = $dbh->prepare($ipq);
	$query->execute();

	my $type = $query->fetchrow_array;

	if ($type =~ m/shared/) {
		return 0;
	} else {
		return 1;
	}
}

sub cpanel_docroot {

	my $domain = shift;
	my $docroot;
	
	open (my $httpconf, "<", "/usr/local/apache/conf/httpd.conf") or die ("Unable to open httpd.conf\n");

	my $grep;
	while (<$httpconf>) {
		if (/\s$domain\s/i) {
			while (<$httpconf>){
				$grep = $_;
				last if (/documentroot/i);
			}
		}
	}
	close ($httpconf);

	if ($grep) {
		$grep =~ s|documentroot||gi;
		$grep =~ s/^\s+//;
		$grep =~ s/\s+$//;
		$docroot = $grep;
	} else {
		$docroot = "NONE";	
	}

	return $docroot;
}

sub plesk_docroot {

	my $domain = shift;

	my $querystring = qq^select hosting.www_root from hosting inner join domains on domains.id=hosting.dom_id where domains.name = '$domain' limit 1;^;
	my $query = $dbh->prepare($querystring);
	$query->execute();
	my @row = $query->fetchrow_array;

	my $docroot;
	if (scalar(@row)) {
		$docroot = $row[0];
	}

	if ($docroot) {
		return $docroot;
	} else {
		return "NONE";
	}
}

sub colorify {
        my $string = shift;
	my $color = shift;
	return color("$color").$string.color("reset");
}
