#!/usr/bin/perl -w


my $cacertusername='pg@futureware.at';
my $cacertpassword='';


#Load a list of names and email addresses from the file list.txt :
&getListe("list.txt");

#Load the users from the Active Directory on Server SERVER:
#&getActiveDirectory("SERVER","company.com");


&sendEmails('sender@company.com',"PKI Department");












my %generatedCerts;

sub readfile($)
{
  if(open IN,"<$_[0]")
  {
    my $old=$/;
    undef $/;
    my $content=<IN>;
    $/=$old;
    close IN;
    return($content);
  }
  return "";
}

sub writefile($$)
{
  if(open OUT,">$_[0]")
  {
    print OUT $_[1];
    close OUT;
  }
}


sub getCert($$$)
{
  my ($firstname,$lastname,$email)=@_;

  use LWP::UserAgent;
  use HTTP::Request::Common;
  
  $fn=$email; $fn=~s/\@/_/g; $fn=~s/\s+//g;
  system "openssl genrsa -out $fn.key 2048"; 
  system "openssl req -new -key $fn.key -out $fn.csr -subj /CN=$email";
  my $csr=readfile("$fn.csr");
#  $csr=~s/\n/%0a/sg; 
#  $csr=~s/ /%20/g;
  print "$csr\n";

  my $userAgent = LWP::UserAgent->new(agent => 'perl post');
  my %test=(
  username => $cacertusername,
  password => $cacertpassword,
  "email[0]" => $email,
  name => "$firstname $lastname",
  codesign => "0",
  optionalCSR => $csr );

  my $response = $userAgent->post('https://www.cacert.org/api/ccsr.php',\%test);

  print $response->error_as_HTML unless $response->is_success;

  my $res=$response->as_string;

  if($res=~m/(-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s)
  {
    open OUT,">$fn.crt";
    print OUT $1;
    close OUT;

    system "openssl pkcs12 -export -out $fn.pfx -inkey $fn.key -in $fn.crt -passout pass:whatever";

    system "openssl x509 -in $fn.crt -text -noout |grep Subject";
    $generatedCerts{"$fn.pfx"}=$email;
  }
  else
  {
    print "Could not enrol a certificate for $firstname $lastname ($email)\n";
  }


}


sub getListe()
{
  if(open LISTE,"<$_[0]")
  {
    while(<LISTE>)
    {
      my @list=split ",",$_;
      print "Generating a certificate for $list[0] $list[1] with email $list[2]\n";
  
      getCert($list[0],$list[1],$list[2]);
    }
    close LISTE;
  }
}

sub getActiveDirectory($$)
{
  require Win32API::Net;
#  use Win32API::Net qw(UserEnum);
  my @list=();
  UserEnum($_[0],\@list);
  foreach (@list)
  {
    if(m/(\w+)\.(\w+)/)
    {
      getCert($1,$2,"$1.$2\@$_[1]");
    }
  }
}

sub sendEmails()
{
  foreach(keys %generatedCerts)
  {
    print "Sending $_ via email to $generatedCerts{$_}\n";
  }

}



