#!/home/product/code/webui-perl/bin/perl

=head1 NAME

ssldump - Simple script to output info about SSL certificates

=head1 SYNOPSIS

    ssldump

=head1 DESCRIPTION

This script is a companion to the NG SSL Certificate loadinator that
shows information about certificates loaded into /tmp/sslcert/*.

It's for support and developer information only and should not be
used for any UI or other purpose.

Note that the output is abbreviated to make it easy for humans to
read.  If you use this information for any real purpose, you're
insane.

=cut

use strict;

if( @ARGV ) {
	system("perldoc", $0);
	exit;
}

my $ssldir = "/tmp/sslcert";
my $maxlen = 60;
my $modmaxlen = 20;
my %files = ();

# Sort in the order:
# certs before keys
# subjects
# issuers
# filenames
sub sortfile {
	my ($a, $b) = @_;
	if( $files{$a}->[0] && !$files{$b}->[0] ) {
		return -1;
	} elsif( !$files{$a}->[0] && $files{$b}->[0] ) {
		return +1;
	} elsif( $files{$a} ) {
		if( $files{$a}->[0] eq $files{$b}->[0] ) {
			if( $files{$a}->[1] eq $files{$b}->[1] ) {
				return $a cmp $b;
			} else {
				return $files{$a}->[1] cmp $files{$b}->[1];
			}
		} else {
			return $files{$a}->[1] cmp $files{$b}->[1];
		}
	} else {
		return $a cmp $b;
	}
}

# Read all the cert and key files.  Ignore directories.
opendir DIR, $ssldir;
while( my $ent = readdir(DIR) ) {
	my $p = "$ssldir/$ent";
	if( ! -d $p && $ent !~ /^\./ ) {
		my $subj = `openssl x509 -noout -subject -in "$p" 2>/dev/null`;
		chomp($subj);
		$subj =~ s/^subject=\s*//;
		$subj = "..." . substr($subj, (3-$maxlen), ($maxlen-3)) if( length($subj) > $maxlen );
		my $issu = `openssl x509 -noout -issuer -in "$p" 2>/dev/null`;
		chomp($issu);
		$issu =~ s/^issuer=\s*//;
		$issu = "..." . substr($issu, (3-$maxlen), ($maxlen-3)) if( length($issu) > $maxlen );
		my $modu = `openssl x509 -noout -modulus -in "$p" 2>/dev/null`;
		$modu = `openssl rsa -noout -modulus -in "$p" 2>/dev/null` if !$modu;
		$modu =~ /Modulus\s*=\s*(.{0,$modmaxlen})/;
		$modu = $1;
		$files{$ent} = [ $subj, $issu, $modu ];
	}
}
closedir DIR;

# Print subject/issuer info about certs
print "Certificates:\n";
foreach my $f (sort( { sortfile($a, $b); } keys(%files))) {
	if( $files{$f}->[0] ) {
		print "    $f:\n";
		print "        Subj: " . $files{$f}->[0] . "\n";
		print "        Issu: " . $files{$f}->[1] . "\n";
	}
}

# Print key filenames
print "\nKeys: \n";
foreach my $f (sort( { sortfile($a, $b); } keys(%files))) {
	if( !$files{$f}->[0] ) {
		print "    $f\n";
	}
}

# Print modulus of each cert and key (so you can manually match them)
print "\nModului:\n";
foreach my $f (sort( { sortfile($a, $b); } keys(%files))) {
	print "    " . $files{$f}->[2] . " $f\n";
}
