#! /usr/bin/perl 

use strict;

use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use Template;
use JSON;
use Data::Dumper;
use File::Temp qw/tempfile/;

my $cgi = CGI->new();
my $tt = Template->new(
	INCLUDE_PATH => "/home/avi/wordpress_html/fingerprint/templates/",
	INTERPOLATE => 1,
);

print "Content-type: text/html\n\n";

if(!$cgi->param('cert')){
	$tt->process('main');
	exit;
}

my $cert = $cgi->param('cert');
my @c;
my $fingerprint;
my $fingerprint_type;
my $type;

if($cert =~ m/\s*-+BEGIN CERTIFICATE-+/){
	$type = 'x509 TLS';
	my $in_certificate = undef;
	my $cer = '';
	foreach my $line (split(m/\n/, $cert)){
		if($line =~ m/^\s*(-----BEGIN CERTIFICATE-----)\s*$/){
			push(@c, $1);
			$in_certificate = 1;
		}elsif($in_certificate > 0 and $line =~ m/^\s*(-----END CERTIFICATE-----)\s*$/){
			push(@c, $1);
			$in_certificate = 0;
		}elsif( $in_certificate and ($line =~ m#^\s*([\w=\+/]+)\s*#)){
			push(@c, $1);
		}
	}
	my $cert = join("\n", @c, "");
	$fingerprint = qx/echo '$cert' | openssl x509  -noout -fingerprint 2>&1/;
	if($fingerprint =~ m/(\S+) Fingerprint=(\S+)/){
		$fingerprint_type = $1;
		$fingerprint = $2;
	}
}elsif($cert =~ m/ds:X509Certificate/){
	$cert =~ s/\s+//;
	$cert =~ join('', split(m/\n+/, $cert));
	$cert =~ s#</ds:.+##;

}elsif($cert =~ m/^\s*(ssh-rsa\s+AA\S+)($|\s)/){
	$type = 'RSA SSH';
	$fingerprint = qx/echo '$1' | ssh-keygen -lf -/;
	if($fingerprint =~ m/^\d+ ([^:]+):(\S+)/){
		$fingerprint_type = $1;
		$fingerprint = $2;
	}
}

chomp($fingerprint);

$tt->process('main', {fingerprint => $fingerprint, cert => $cert, type => $type, fingerprint_type => $fingerprint_type});
