#!/usr/bin/perl -w
#
# Request host certificate from CERN CA and store it.
#
# 2020-11-20 v.0.9.4 daniel.juarez.gonzalez@cern.ch
#                    - no need for header on cert verify
# 2018-06-06 v.0.9.2 Jaroslaw.Polok@cern.ch
#                    - add --hostname option
# 2018-04-11 v.0.9.1 Jaroslaw.Polok@cern.ch
#                    - fix alternate config file option
# 2017-04-26 v.0.9 Jaroslaw.Polok@cern.ch
#                    - add SAN: DNS:hostname to cert req 
#                      (to make it work with Chrome 58)
# 2016-04-07 v.0.8.1 Jaroslaw.Polok@cern.ch
#                    - print ActivityID/RequestId in case of error.
# 2015-09-01 v.0.8 Jaroslaw.Polok@cern.ch
#                    - perform krb5 auth for all operations
# 2015-08-24 v.0.7.2 Jaroslaw.Polok@cern.ch
#                    - fix subject for Grid certs.
# 2015-02-27 v.0.7.1 Jaroslaw.Polok@cern.ch
#                    - fix handling of CA SOAP 'Denied by Policy Module' message
# 2015-02-17 v.0.7 Jaroslaw.Polok@cern.ch
#		     - rewritten for new SOAP CA interface
#                    - validity checked using OCSP
# 2015-02-06 v.0.6 Jaroslaw.Polok@cern.ch
#                    - adding CERN Grid CA
# 2015-02-05 v.0.5 Jaroslaw.Polok@cern.ch
#                    - usekrb5cfg option
#                    - fetch and store CRL
#                    - verify cert against CRL
# 2015-01-20 v.0.4   Jaroslaw.Polok@cern.ch
#                    - use temp. files
# 2015-01-15 v.0.3.1 Jaroslaw.Polok@cern.ch
#                    - status check
# 2014-12-11 v.0.3   Jaroslaw.Polok@cern.ch 
#                    - autorenewexec (optional) 
# 2014-12-03 v.0.2.1 Jaroslaw.Polok@cern.ch
#                    - autorenewal config file option
#                    - autorenewal cron job
# 2014-12-02 v.0.2   Jaroslaw.Polok@cern.ch
#		     - minor fixes, use cerndc with GSSAPI
# 2014-11-27 v.0.1   Jaroslaw.Polok@cern.ch
#                    - initial version
#

use strict;
use XML::Simple;
use WWW::Curl::Easy qw(/^CURLOPT_/ /^CURLINFO_/);
use Getopt::Long;
use Pod::Usage;
use Authen::Krb5;
use Data::Dumper;
use File::Temp;
use File::Copy qw(move);
use Date::Manip qw(ParseDate UnixDate);
use Config::Simple;

use constant {
GET_CERT_USER_AGENT => 'cern-get-certificate/0.9.2',
CA_SRV => 'https://ca.cern.ch/ca-services',
CA_AER => 'autoenrollment/Autoenrollment.asmx?op=',
CA_GETCERT => 'NewHostCertificate',
CA_AE_CHECK => 'GetHostCertificatesAutoenrollmentSettings',
CA_AE_DISABLE => 'DisableHostCertificatesAutoenrollment',
CA_AE_ENABLE =>  'EnableHostCertificatesAutoenrollment',
CA_CERT_TYPE => [
	'CernHostCertificate',
	'GridHostCertificate',
	],
CERT_REQ_SUBJECT => [
	'/CN=',
	'/DC=ch/DC=cern/OU=computers/CN=',
	],
# we should extract it from certificate, but .. URI will not change
CA_OCSP => 'ocsp.cern.ch',
CA_OCSP_ISSCERT => [
	'CERN_Certification_Authority.pem',
	'CERN_Grid_Certification_Authority.pem',	
	],
SUFF => [
	'',
	'.grid',
	],
CERT_CONFIG => '/etc/sysconfig/cern-get-certificate',
CERT_MINDAYS => 7,
CERT_OWNERUID => 0,
CERT_OWNERGID => 0,
CERT_CERN => 1,
CERT_GRID => 0,
CERT_PRIVPATH => '/etc/pki/tls/private/',
CERT_PUBPATH => '/etc/pki/tls/certs/',
CERT_CABUNDLE =>'/etc/pki/tls/certs/CERN-bundle.pem',
KRB5_DEF_KEYTAB => '/etc/krb5.keytab',
KRB5_CCACHE_NAME => 'MEMORY:cgcccache.'.$$,
KRB5_CCACHE_NAME2 => 'MEMORY:cgcccache2.'.$$,
OPENSSL  => 'LC_ALL=C /usr/bin/openssl',
CHCON => '/usr/bin/chcon',
CHECKIT => 0,
ENABLE => 1,
DISABLE => 2,
TMPSUFF => "._tmp_",
KRB5CFGTMP => '/tmp/cgk.krb5.conf',
KRB5REALM => 'CERN.CH',
CURL_CAPATH => '/etc/pki/tls/certs/',
CURL_CERTINFO => (0x400000 + 32), #undef? (CURLINFO_CERTINFO)
CURL_GSSNEGOTIATE => (1 << 2), #undef? (CURLOPT_GSSNEGOTIATE)
};


################################################################################
################################################################################

sub curlout_write_callback {
    my ($chunk,$variable)=@_; 
    push @{$variable}, $chunk;
    return length($chunk); 
}

sub errorout {
    my ($msg,$code)=@_;
    $code=0 if (!defined($code));
    if ($code > 0) {
       print "Error: ".$msg."\n";
    } else {
       print "".$msg."\n";
    }
    exit($code);
}

sub msg {
    my ($msg,$eol)= @_;
    $eol=1 if (!defined($eol));
    print "".$msg."";
    print "\n" if ($eol == 1);
}

sub myexec {
    my ($argstr,$verbose)=@_;
    msg("executing $argstr") if ($verbose);
    if(system($argstr)!=0) {
     if ($? == -1) { errorout("failed to execute.",1); }
     if ($? & 127) { errorout("child exit code: ".($? & 127),1); }
    }
    return 1;
}

sub fixselinux { 
    # would be nicer with some SE linux perl module...
    my($certfile)=@_;
    system(CHCON." system_u:object_r:cert_t:s0 $certfile") 
		if (-x CHCON && -f $certfile);
}

sub is_int {
    my ($val,$key,$cfgfile)=@_;
    errorout("error in config file $cfgfile: $key value ($val) is NOT an integer.",1) 
	if ($val !~ /^\d+$/); 

}

sub is_file {
    my ($val,$key,$cfgfile)=@_;
    if (defined($val) &&  !-r $val) {
      errorout("error in config file $cfgfile: $key file/path ($val) NOT readable.",1);
    } 
	
}
        
################################################################################
################################################################################

sub krb5cfgfile {
   my($kdc,$realm,$verbose,$debug)= @_;
   my($tfh,$tfname) = undef;

   ($tfh,$tfname)=File::Temp::tempfile("cgc.krb5.conf.XXXXXX",TMPDIR=>1,UNLINK=>1) or errorout("cannot create temporary krb5 config file: $tfname",1);
   printf $tfh "[libdefaults]\ndefault_realm=".$realm."\ndns_lookup_kdc=false\nforwardable=true\nproxiable=true\n" or errorout("cannot write temp. krb5 config file: $tfname",1);
   printf $tfh "[realms]\n".$realm."={\nkdc=".$kdc."\nadmin_server=".$kdc."\n}\n" or errorout("cannot write temp. krb5 config file: $tfname",1);
   $tfh->flush();
   msg("created temporary krb5 config file: $tfname") if ($verbose);
   return $tfname;
}


sub krb5init {
   my($verbose,$debug)= @_;
   Authen::Krb5::init_context() or 
	errorout(Authen::Krb5::error()." while initializing context.",1);
   Authen::Krb5::init_ets() or 
	errorout(Authen::Krb5::error()." while initializing error tables.",1);
}

sub krb5ccache {
   my($ccachefile,$verbose,$debug)= @_;
   if (defined($ccachefile)) {
      msg("resolving credentials cache ($ccachefile).") if ($debug);
      return Authen::Krb5::cc_resolve($ccachefile) ||
	errorout(Authen::Krb5::error()." while resolving ccache ($ccachefile)",1);
   }
   msg("resolving default credentials cache.") if ($debug);
   return Authen::Krb5::cc_default() || 
	errorout(Authen::Krb5::error()." while resolving default ccache",1);   
}


sub krb5ktauth {
   my($hostname,$keytabfile,$ccachefile,$verbose,$debug)= @_;
   my($principal,$krb5keytab,$krb5ktentry,$krb5ktcursor,$krb5princ,
      $krb5ccache,$krb5tgt) = undef;
   	
   msg("using default keytab file name.") 
        		if (!defined($keytabfile) && $debug);

   # this returns undef ... while shouldn't ..
   #$keytabfile=Authen::Krb5::kt_default_name() if (!defined($keytabfile));
   $keytabfile=KRB5_DEF_KEYTAB if (!defined($keytabfile));

   msg("using keytab file name: $keytabfile") if ($debug);

   msg("keytab file not readable.") if ($verbose && !-r $keytabfile);
   return (undef) if (!-r $keytabfile);

   $krb5ccache= krb5ccache($ccachefile,$verbose,$debug);
   
   msg("resolving keytab file $keytabfile") if ($debug);
   $krb5keytab= Authen::Krb5::kt_resolve($keytabfile) or 
     errorout(Authen::Krb5::error()." while resolving keytab ($keytabfile).",1);
   
   if(!defined($principal)) {
      msg("scanning keytab file for principal name ($hostname)") if ($debug);
      $krb5ktcursor= $krb5keytab->start_seq_get();
      while($krb5ktentry= $krb5keytab->next_entry($krb5ktcursor)) {
	# only hostname.domain.name principals, eliminate hostname$ MS stuff
         if ($krb5ktentry->principal->data =~ /^(.*)\.(.*)$/ && 
             $krb5ktentry->principal->data =~ /^\Q$hostname/) {           
            $principal=$krb5ktentry->principal->data;
	        $principal="host/".$principal;
            msg("found principal name: $principal") if ($debug);            
            last;
         }
      }
    $krb5keytab->end_seq_get($krb5ktcursor);	 

    msg("principal name not found.") if ($verbose && !defined($principal)); 
    return (undef) if (!defined($principal));
   }

   $krb5princ = Authen::Krb5::parse_name($principal) or 
	errorout(Authen::Krb5::error()." while parsing client principal.",1);
   $krb5ccache->initialize($krb5princ) or 
	errorout(Authen::Krb5::error()." while initalizing ccache.",1);
   msg("authen. as: ".$principal." using keytab file: ".$keytabfile.".") 
	if ($debug);
   $krb5tgt=Authen::Krb5::get_init_creds_keytab($krb5princ,$krb5keytab);   
   return (undef) if (!$krb5tgt);

   Authen::Krb5::Ccache::store_cred($krb5ccache,$krb5tgt) or 
	errorout(Authen::Krb5::error()." while storing TGT in ccache.",1);

   return ($principal);
}


################################################################################
## instead of openssl binary we could use perl modules here, but why pulling 
## in a dozen ?...
################################################################################


sub verifycert {
   my($certfile,$cafile,$ocsp,$verbose,$debug)=@_;
   my($tmpfile,$cmdline,@data)=undef;   

   $tmpfile = File::Temp->new(TEMPLATE => "cgcXXXXXX", UNLINK => 1, TMPDIR=>1);

   $cmdline=OPENSSL." ocsp -no_nonce -issuer ".$cafile." -cert ".
                    $certfile." -url http://".$ocsp."/ocsp/ > $tmpfile 2>&1";

   myexec($cmdline,$verbose);
   
   open(FH, '<', $tmpfile) or 
		errorout("Error opening tempfile for reading.",1);
   @data=<FH>;
   close FH;
   
   printf Dumper($data[1]) if ($debug);

   errorout("Unexpected content of tempfile.",1) 
	if (@data && $#data < 2);
   
   return 0 if ($data[1] !~ /^$certfile: good$/);   

   return 1;
}

sub checkcertdays {
   my($certfile,$verbose,$debug)=@_;
   my($tmpfile,$cmdline,@data,$enddate,$nowdate)=undef;

   $tmpfile = File::Temp->new(TEMPLATE => "cgcXXXXXX", UNLINK => 1, TMPDIR=>1);

   $cmdline=OPENSSL." x509 -inform PEM -noout -enddate -in $certfile > $tmpfile";

   myexec($cmdline,$verbose);

   open(FH, '<', $tmpfile) or 
		errorout("Error opening tempfile for reading.",1);
   @data=<FH>;
   close FH;

   printf Dumper(@data) if ($debug);

   errorout("Unexpected content of tempfile.",1) 
	if (@data && $#data ne 0);

   errorout("malformed content of tempfile.",1) 
	if ($data[0] !~ /^notAfter=(.*\d\d\d\d).*/);

   $enddate=UnixDate(ParseDate($1),'%s');
   $nowdate=time;

   return int(($enddate - $nowdate)/86400);
}

sub makecertreq {
   my ($hostname,$keyfile,$certreqfile,$cuid,$cgid,$tmpsuff,$which,$verbose,$debug)=@_;
   my @data = undef;
   my $tmpfile = File::Temp->new(TEMPLATE => "cgcXXXXXX", UNLINK => 1, TMPDIR=>1);

   # request with a defined SAN too: to calm down Chrome 58 ...
   printf $tmpfile "[req]\ndistinguished_name=req_distinguished_name\n";
   printf $tmpfile "[req_distinguished_name]\n";
   printf $tmpfile "[san]\nsubjectAltName=DNS:$hostname\n";
    
   my $cmdline=OPENSSL." req -new -subj \"".CERT_REQ_SUBJECT->[$which]."$hostname\" -nodes -sha512 ".
                       " -reqexts san -config ".$tmpfile.
                       " -newkey rsa:2048 -keyout ".$keyfile.$tmpsuff." -out ".$certreqfile.$tmpsuff;

   $cmdline.=" -verbose" if (defined($debug));
   $cmdline.=" > /dev/null 2>&1" if (!defined($verbose) || !defined($debug));
   myexec($cmdline,$verbose); 

   msg("reading certificate data from: $certreqfile.$tmpsuff") if ($verbose);   
   open(FH, '<', $certreqfile."".$tmpsuff) or 
		errorout("Error opening ".$certreqfile.$tmpsuff." for reading.",1);
   @data=<FH>;
   close FH;
   chmod(0600,$certreqfile."".$tmpsuff);
   chown($cuid,$cgid,$certreqfile."".$tmpsuff);
   chmod(0600,$keyfile."".$tmpsuff);
   chown($cuid,$cgid,$keyfile."".$tmpsuff);

   errorout($certreqfile.$tmpsuff." does not contain CSR.",1) 
		if ($data[0] !~ /BEGIN CERTIFICATE REQUEST/ || 
		    $data[-1] !~/END CERTIFICATE REQUEST/);   
   return join('',@data);
}

sub writecert {
    my ($certdata,$certfile,$cuid,$cgid,$tmpsuff,$verbose,$debug)=@_;
    my $cmdline=OPENSSL." x509 -inform PEM -in ".$certfile.".pem".$tmpsuff.
                        " -outform DER -out ".$certfile.".crt".$tmpsuff;
	
    msg("writing certificate data to: ".$certfile.".pem".$tmpsuff) if ($verbose);   

    open(my $FH, '>', $certfile.".pem".$tmpsuff) or 
		errorout("Error opening ".$certfile.".pem".$tmpsuff." for writing.",1);
    print $FH $certdata;
    close $FH;
    chmod(0644,$certfile.".pem".$tmpsuff);
    chown($cuid,$cgid,$certfile.".pem".$tmpsuff);
    msg("writing certificate data to: ".$certfile.".crt".$tmpsuff) if ($verbose);
    myexec($cmdline,$verbose);  
    chmod(0644,$certfile.".crt".$tmpsuff);
    chown($cuid,$cgid,$certfile.".crt".$tmpsuff);

}

sub autoenroll {
   my($what,$which,$verbose,$debug)=@_;
   my($soapurl,$soaphdr,$soapmth,$soaparg) = undef;

   if ($what == ENABLE) {
	$soapurl= CA_SRV."/".CA_AER."".CA_AE_ENABLE;   
	$soaphdr= CA_SRV."/".CA_AE_ENABLE;
	$soapmth= CA_AE_ENABLE;
        $soaparg= "<requestor>root</requestor>";
   } elsif ($what == DISABLE) {
	$soapurl= CA_SRV."/".CA_AER."".CA_AE_DISABLE;
	$soaphdr= CA_SRV."/".CA_AE_DISABLE;
	$soapmth= CA_AE_DISABLE;
        $soaparg= "<requestor>root</requestor>";
   } else {
	$soapurl= CA_SRV."/".CA_AER."".CA_AE_CHECK;
	$soaphdr= CA_SRV."/".CA_AE_CHECK;
	$soapmth= CA_AE_CHECK;
        $soaparg= "";

   }

   my $outdata=curlsoapreq(
    $soapurl,
    $soaphdr,	
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
		    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
	    <'.$soapmth.' xmlns="'.CA_SRV.'">
            <autoenrollmentHostCertificateTemplate>'.CA_CERT_TYPE->[$which].'</autoenrollmentHostCertificateTemplate>
            '.$soaparg.'
	    </'.$soapmth.'>
        </soap:Body>
     </soap:Envelope>',
     $verbose,
     $debug);

    print Dumper($outdata) if ($debug);

    my $odb=$outdata->{'soap:Body'}->{$soapmth.'Response'}->{ $soapmth.'Result'}; 

    if ($verbose) {
     print("curl RCV data:\n");
     print("Success:    ".$odb->{'Success'}."\n") if ($odb->{'Success'});
     print("Message:    ".$odb->{'Message'}."\n") if ($odb->{'Message'});
     print("Enabled:    ".$odb->{'Result'}->{'Enabled'}."\n") if ($odb->{'Result'}->{'Enabled'});
     print("DomainCtrl: ".$odb->{'Result'}->{'DomainController'}."\n") if ($odb->{'Result'}->{'DomainController'});
     print("ActivityID: ".$odb->{'ActivityID'}."\n") if ($odb->{'ActivityID'});
   }	     	
   
    errorout("cannot receive/parse server data:".$odb->{'Message'},1) 
		if ($odb->{'Success'} !~ /^true$/ || !defined($odb->{'Result'}->{'DomainController'})); 

    if($what == CHECKIT) {
      return (undef) if ($odb->{'Result'}->{'Enabled'} !~/^true$/);
    } 
 
    return ($odb->{'Result'}->{'DomainController'});
}

sub reqcert {
   my ($certreq,$which,$initial,$verbose,$debug)=@_;
   
   my $outdata=curlsoapreq(
   CA_SRV."/".CA_AER."".CA_GETCERT,
   CA_SRV."/".CA_GETCERT,
   # XML::Simple is not really meant for .. go for manual concat ..
   '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
		    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
	    <'.CA_GETCERT.' xmlns="'.CA_SRV.'"> 
            <autoenrollmentHostCertificateTemplate>'.CA_CERT_TYPE->[$which].'</autoenrollmentHostCertificateTemplate>
 	       <base64CertificateRequest>'.
                 $certreq.
              '</base64CertificateRequest>
            </'.CA_GETCERT.'>
        </soap:Body>
     </soap:Envelope>',
     $verbose,
     $debug);

   print Dumper($outdata) if ($debug);

   my $outdatabody=$outdata->{'soap:Body'}->{CA_GETCERT.'Response'}->{CA_GETCERT.'Result'};

   if ($verbose) {
    print("curl RCV data:\n");
    print("Success:     ".$outdatabody->{'Success'}."\n") if ($outdatabody->{'Success'});
    print("Message:     ".$outdatabody->{'Message'}."\n") if ($outdatabody->{'Message'});
    print("ActivityID:  ".$outdatabody->{'ActivityID'}."\n") if($outdatabody->{'ActivityID'});
    print("RequestId:   ".$outdatabody->{'RequestId'}."\n" ) if($outdatabody->{'RequestId'});
    print("Certificate: ".$outdatabody->{'Certificate'}."\n" ) if($outdatabody->{'Certificate'});
   }

   # we have no way of knowing if KDC already knows that we are authorized, 
   # so will retry few times ... ugly hack ..

   my $tmpout1="????";
   my $tmpout2="????";

   $tmpout1=$outdatabody->{'RequestId'} if (defined($outdatabody->{'RequestId'}));
   $tmpout2=$outdatabody->{'ActivityID'} if (defined($outdatabody->{'ActivityID'}));


   if ($initial) {
      return 'NOTYET'." [RequestId: ".$tmpout1.",ActivityID: ".$tmpout2."]" 
		if (defined($outdatabody->{'Message'}) && $outdatabody->{'Message'} =~ /^Permission denied: not authorized.$/);
      return 'NOTYET'." [RequestId: ".$tmpout1.",ActivityID: ".$tmpout2."]" 
		if (defined($outdatabody->{'Message'}) && $outdatabody->{'Message'} =~ /^Denied by Policy Module$/);
   }

   errorout("cannot receive/parse server data:".$outdatabody->{'Message'}." [RequestId: ".$tmpout1.",ActivityID: ".$tmpout2."]",1) 
		if ($outdatabody->{'Success'} !~ /^true$/); 
   #
   # XML::Lite returns HASH for empty elements ? ...
   #
   errorout("incomplete data received.",1) 
		if (ref($outdatabody->{'Certificate'}) eq "HASH");

   return ($outdatabody->{'Certificate'});    	
}

sub curlsoapreq {
   my ($soapurl,$soapaction,$soapbody,$verbose,$debug)=@_;
   my $curl=WWW::Curl::Easy->new();
   my $xml=XML::Simple->new();
   my @soapoutdata = ();
   my @soapheaders=( 
	"Content-Type: text/xml; charset=utf-8;",
	"SOAPAction: $soapaction" 
	);

   $curl->setopt(CURLOPT_SSL_VERIFYPEER, 1); # CHANGE TO 1 FOR PROD !
   $curl->setopt(CURLOPT_SSL_VERIFYHOST, 2); # CHANGE TO 2 FOR PROD !
   $curl->setopt(CURLOPT_USERAGENT,GET_CERT_USER_AGENT);
   $curl->setopt(CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt(CURLOPT_CONNECTTIMEOUT,10);
   $curl->setopt(CURLOPT_HTTPAUTH, CURL_GSSNEGOTIATE);
   $curl->setopt(CURLOPT_UNRESTRICTED_AUTH, 1); # we do not really send any password, BTW.
   $curl->setopt(CURLOPT_USERPWD,":");
   $curl->setopt(CURLOPT_WRITEFUNCTION, \&curlout_write_callback); 
   $curl->setopt(CURLOPT_FILE,\@soapoutdata);
   $curl->setopt(CURLOPT_TIMEOUT,60);
   $curl->setopt(CURLOPT_HEADER,0);
   $curl->setopt(CURLINFO_HEADER_OUT,1);
   $curl->setopt(CURLOPT_POSTFIELDS,$soapbody);
   $curl->setopt(CURLOPT_HTTPHEADER,\@soapheaders);
   $curl->setopt(CURLOPT_POST,1);
   $curl->setopt(CURLOPT_VERBOSE,1) if ($debug);
   # not everybody has certs imported in NSS db
   # and we do not include CERN certs in ca-bundle.crt ... 
   $curl->setopt(CURLOPT_CAPATH,CURL_CAPATH);
   $curl->setopt(CURLOPT_URL,$soapurl);

   msg("curl POST url:\n".$soapurl) if ($verbose);
   msg("curl POST header:\n".join('\n',@soapheaders)) if (defined($debug)); 
   msg("curl POST body:\n".$soapbody) if (defined($debug));
 
   
   errorout("http error: (".$curl->errbuf().
	" [http err:".$curl->getinfo(CURLINFO_HTTP_CODE)."])",1) 
             		if ($curl->perform() != 0);

   if ($curl->getinfo(CURLINFO_HTTP_CODE)!= 200) {
     msg("Error: server error: ".$curl->getinfo(CURLINFO_HTTP_CODE));
     msg("Error: server output:\n".join("",@soapoutdata)."\n") if ($verbose);
     exit(1);
   }  

   return ($xml->XMLin(join("",@soapoutdata)));
}

################################################################################
################################################################################

sub managefiles {
 my($csrfile,$keyfile,$certfile,$tmpsuff,$verbose,$debug)=@_;

 if (-r $csrfile.$tmpsuff) {
   msg("removing ".$csrfile.$tmpsuff) if ($verbose);
   unlink($csrfile."".$tmpsuff);
 }
 
 if (-r $keyfile."".$tmpsuff) {
   msg("moving ".$keyfile."".$tmpsuff." to ".$keyfile) if ($verbose);
   move($keyfile."".$tmpsuff,$keyfile);
   fixselinux($keyfile);
 }

 if (-r $certfile.".pem".$tmpsuff) {
   msg("moving ".$certfile.".pem".$tmpsuff." to ".$certfile.".pem") if ($verbose);
   move($certfile.".pem".$tmpsuff,$certfile.".pem");
   fixselinux($certfile.".pem");
 }

 if (-r $certfile.".crt".$tmpsuff) {
   msg("moving ".$certfile.".crt".$tmpsuff." to ".$certfile.".crt") if ($verbose);
   move($certfile.".crt".$tmpsuff,$certfile.".crt");
   fixselinux($certfile.".crt");
 }
 
}

#
# main() ;-)
# 
      

my($debug,$verbose,$force,$help,$principal,$principalnosrv,$hostname,
   $certreq,$keyfile,$certfile,$csrfile,$certreqdata,$certdata,
   $enableauto,$disableauto,$renew,$cron,$status,$usekrb5cfg,$cern,$grid,
   %confvals)=undef;

my $cfgfile=CERT_CONFIG;
my $privpath=CERT_PRIVPATH;
my $pubpath=CERT_PUBPATH;
my $mindays=CERT_MINDAYS;
my $certuid=CERT_OWNERUID;
my $certgid=CERT_OWNERGID;
my $keytab=KRB5_DEF_KEYTAB;
my $autorenew=1;
my $initial=0;

my $autorenewexec=undef;
my $which=0; # cern

my %opts=(
	"debug"		=> \$debug,
	"verbose"	=> \$verbose,
	"help"		=> \$help,
	"force"		=> \$force,
	"autoenroll"	=> \$enableauto,
	"noautoenroll"	=> \$disableauto,
	"renew"		 => \$renew,
	"config=s"	 => \$cfgfile,
	"cron"		 => \$cron,
	"status"	 => \$status,
	"usekrb5cfg" => \$usekrb5cfg,
	"cern"		 => \$cern,
	"grid"		 => \$grid,
    "hostname=s" => \$hostname,
	);

errorout("Invalid options specified.",1) if (GetOptions(%opts) ne 1);

pod2usage(-verbose=> 2) if ($help);

errorout("Options --cern and --grid are mutually exclusive.",1) 
	if(defined($cern) && defined($grid));

$which=1 if (defined($grid));

my $optcnt=0;
$optcnt++ if defined($enableauto);
$optcnt++ if defined($disableauto);
$optcnt++ if defined($renew);
$optcnt++ if defined($status);

errorout("One of --autoenroll, --noautoenroll, --renew or --status must be supplied.",1)
	if (!$optcnt && !defined($cron));

errorout("You must be 'root' to run this program.",1) 
	if ((getpwuid $>) ne 'root');

errorout("Options --autoenroll, --noautoenroll, --renew and --status are mutually exclusive.",1)
        if (!defined($cron) && $optcnt > 1) ;


$hostname=`/bin/hostname -f` if (!defined($hostname));
chomp($hostname);

errorout("Config file not readable ($cfgfile)") 
        if (! -r $cfgfile);


Config::Simple->import_from($cfgfile, \%confvals); # TODO: check error codes ...

if (%confvals) {
 $privpath=$confvals{'default.keypath'} if (defined($confvals{'default.keypath'}));
 $pubpath=$confvals{'default.certpath'} if (defined($confvals{'default.certpath'}));
 $mindays=$confvals{'default.days'} if (defined($confvals{'default.days'}));
 $certuid=$confvals{'default.uid'} if (defined($confvals{'default.uid'}));
 $certgid=$confvals{'default.gid'} if (defined($confvals{'default.gid'}));
 $keytab=$confvals{'default.keytab'} if (defined($confvals{'default.keytab'}));
 $autorenew=$confvals{'default.autorenew'} if (defined($confvals{'default.autorenew'})); 
 $autorenewexec=$confvals{'default.autorenewexec'} if (defined($confvals{'default.autorenewexec'}));
 $hostname=$confvals{'default.hostname'} if (defined($confvals{'default.hostname'}));
 msg("Using settings from config file: $cfgfile") if ($verbose);

 is_int($mindays,'days',$cfgfile);
 is_int($certuid,'uid',$cfgfile);
 is_int($certgid,'gid',$cfgfile);
 is_int($autorenew,'autorenew',$cfgfile);
 is_file($privpath,'keypath',$cfgfile);
 is_file($pubpath,'certpath',$cfgfile);
 is_file($autorenewexec,'autorenewexec',$cfgfile);
 is_file($keytab,'keytab',$cfgfile);

} else {
 msg("Using default settings.") if ($verbose);
}


$keyfile=$privpath."/".$hostname.SUFF->[$which].".key"; $keyfile=~ s#//#/#g;
$csrfile=$privpath."/".$hostname.SUFF->[$which].".csr"; $csrfile=~ s#//#/#g;
$certfile=$pubpath."/".$hostname.SUFF->[$which]; $certfile=~ s#//#/#g;


msg("Initializing Kerberos client") if ($verbose);

if ($usekrb5cfg) {
 msg("Using temporary kerberos configuration file: ".KRB5CFGTMP) if ($verbose);
 errorout("Temporary kerberos configuration file: ".KRB5CFGTMP." not readable ?",1) if (! -r KRB5CFGTMP);
 $ENV{"KRB5_CONFIG"}=KRB5CFGTMP;
}

## set up cache first: libcurl will use it too...

$ENV{"KRB5CCNAME"}=KRB5_CCACHE_NAME;
krb5init($verbose,$debug);

msg("Authenticating using keytab file.") if ($verbose);
$principal=krb5ktauth($hostname,$keytab,KRB5_CCACHE_NAME,$verbose,$debug);
errorout("Cannot authenticate using keytab file.",1) if (!defined($principal)); 

errorout("Requesting/managing certificate for hostname: $hostname".
         " but authenticated as: $principal.",1) 
		if ($principal !~ /^host\/$hostname$/);


if($status) {

  msg("checking status") if ($verbose); 
  msg("Host certificate status: ",0);
  if ($which == 1) { msg("CERN Grid ",0); } else { msg("CERN ",0); }
  msg("Certification Authority");
  msg("--------------------------------------------------------------------------------");
  msg("cert private key file  : ",0);
  if ( -r $keyfile ) { msg("present ",0);} else { msg("absent  ",0); }
  msg(" ($keyfile)");
  msg("cert PEM file          : ",0);
  if ( -r $certfile.".pem" ) { msg("present ",0);} else { msg("absent  ",0); } 
  msg(" ($certfile.pem)");
  msg("cert DER file          : ",0);
  if ( -r $certfile.".crt" ) { msg("present ",0);} else { msg("absent  ",0); }
  msg(" ($certfile.crt)");
  msg("cert days until expiry : ",0);
  if (-r $certfile.".pem") {
    my $ced=checkcertdays($certfile.".pem",$verbose,$debug);
    if ( $ced > -1) { msg($ced); } else { msg("expired "); }
  } else {
    msg("unknown  (no certificate file)");
  }
  msg("cron autorenewal status: ",0);
  if ($autorenew && $autorenew > 0) { msg("enabled "); } else { msg("disabled"); }
  msg("cron autorenewal days  : ",0);
  if ($mindays && $mindays > 0) { msg($mindays); } else { msg("disabled"); }
  msg("cron exec on autorenew : ",0);
  if ($autorenewexec && $autorenew > 0) { msg($autorenewexec); } else { msg("disabled"); }
  msg("cert validity (OCSP)   : ",0);
  if (-r $certfile.".pem") {
      if(verifycert($certfile.".pem",CERT_PUBPATH."".CA_OCSP_ISSCERT->[$which],CA_OCSP,$verbose,$debug))
      { msg("valid   "); } else { msg("revoked "); }
  } else {
    msg("unknown  (no certificate file)"); 
  }
  msg("autoenrollment status  : ",0);
  if (!defined(autoenroll(CHECKIT,$which,$verbose,$debug))) { msg("disabled") } else { msg("enabled "); }
 
  msg("--------------------------------------------------------------------------------");
  exit(0);

} elsif($enableauto) {
  
  errorout("key / cert file(s) already exist, use --force to overwrite.\n".
       	 "private key file: $keyfile\n".
         "cert PEM file:    $certfile.pem\n".
         "cert DER file:    $certfile.crt",1) 
	     if ((-r $keyfile || -r $certfile.".pem" || -r $certfile.".crt") 
		 && !defined($force));
} elsif ($renew || $cron) {
  my $txt=""; if ($which == 1) { $txt="--grid"; }

  if ($cron && $autorenew != 1) {
    msg("Certificate autorenewal disabled in configuration file, not renewing.");
    exit(0);
  } 
 
  if (!-r $certfile.'.pem') {
    msg("No certificate file: $certfile.pem, not renewing (Did you ran --autoenroll ".$txt."?)");
    exit(0);
  } 

  managefiles($csrfile,$keyfile,$certfile,TMPSUFF,$verbose,$debug);

  msg("Checking certificate validity end date.") if ($verbose);

  my $days=checkcertdays($certfile.'.pem',$verbose,$debug);

  if ($days > $mindays && !defined($force)) {
    msg("Not renewing: $certfile.pem still valid for $days days".
        " (min. is $mindays days).");
    exit(0);
  }

  msg("Checking autoenrollment settings.") if ($verbose);
	
  errorout("This system is not set for certificate autoenrollment. ".
         "Did you ran --autoenroll ".$txt." ?",1)
		if (!defined(autoenroll(CHECKIT,$which,$verbose,$debug)));

} elsif ($disableauto) {

  msg("Disabling certificate autoenrollment.") if ($verbose);
  
  if (defined(autoenroll(CHECKIT,$which,$verbose,$debug))) {
     errorout("Cannot disable autoenrollment for this system.",1)	
		if(!defined(autoenroll(DISABLE,$which,$verbose,$debug)));
        msg("Certificate autoenrollment disabled");
  } else {
	msg("This system is not set up for certificate autoenrollment");
  }

  exit(0);

} else {

  errorout("Command line arguments error.",1);

}


if (!defined(autoenroll(CHECKIT,$which,$verbose,$debug))) {
    my $kdc=autoenroll(ENABLE,$which,$verbose,$debug);
    # and we will talk to same KDC CA did.
    my $krb5cfg=krb5cfgfile($kdc,KRB5REALM,$verbose,$debug);
    $ENV{'KRB5_CONFIG'}=$krb5cfg;
    $initial=1;
}


msg("Creating CSR") if ($verbose);
$certreqdata=makecertreq($hostname,$keyfile,$csrfile,$certuid,$certgid,TMPSUFF,$which,$verbose,$debug);

msg("Sending certificate request to CA") if ($verbose);

if ($initial) {

  my $i=0;
  my $sleep=10;
  my $tries=12;

  while($i++<$tries) {
   msg("Waiting for Active Directory data replication - ". $i*$sleep ."s (max:". $sleep*$tries ."s).");
   sleep($sleep);
   msg("Reauthenticating using keytab file.") if ($verbose);
   $principal=krb5ktauth($hostname,$keytab,KRB5_CCACHE_NAME,$verbose,$debug);
   errorout("Cannot authenticate using keytab file.",1) if (!defined($principal)); 

   $certdata=reqcert($certreqdata,$which,$initial,$verbose,$debug);    
   errorout("No certificate data received from CA.",1) if (!defined($certdata));
   next if ($certdata =~ /^NOTYET/);
   last; 
  }

  errorout("No certificate data received from CA. [".$certdata."]",1) if ($certdata =~ /^NOTYET/)

} else {
  $certdata=reqcert($certreqdata,$which,$initial,$verbose,$debug);    
  errorout("No certificate data received from CA.",1) if (!defined($certdata));
}  

writecert($certdata,$certfile,$certuid,$certgid,TMPSUFF,$verbose,$debug);

managefiles($csrfile,$keyfile,$certfile,TMPSUFF,$verbose,$debug);

msg("Certificate obtained from CA, stored as:\n".
    "private key file: $keyfile\n".
    "cert PEM file:    $certfile.pem\n".
    "cert DER file:    $certfile.crt");

if(defined($autorenewexec)) {
 msg("autorenewexec set: executing") if ($verbose);
 myexec($autorenewexec,$verbose);
}

exit(0);

 

__END__

=pod

=head1 NAME

cern-get-certificate - utility to acquire and store CERN Certification Authority and/or CERN Grid Certification Authority host certificate.

=head1 DESCRIPTION

cern-get-certficate uses kerberos host identity to authenticate to CERN CA (Certification Authority) 
and/or CERN Grid CA and request host certificate(s) for local system, then configures the system for autoenrollment 
(automatic renewal of certificate). Installed cron job verifies certificate expiry date daily,
performs auto-renewal and optionally restarts service(s) using the certificate.
It also downloads Certificate Revocation List (CRL) and stores it in local files.


=head1 SYNOPSIS

=over 2

   cern-get-certificate  --help

   cern-get-certificate  --autoenroll | --noautoenroll | --renew
			  [--verbose][--debug][--config CFGFILE]
			  [--force][--usekrb5cfg][--cern | --grid][--hostname HOSTNAME]
   cern-get-certificate --status [--verbose][--debug][--config CFGFILE]
			  [--cern | --grid]	
                                       

=back

=head1 OPTIONS

=over 4

=item B<--help>

Shows this help description

=item B<--autoenroll>

Enable the autoenrollment (automatic renewal of certificate) then obtain 
a host certificate from CERN CA and store it in file.

=item B<--noautoenroll>

Disable the autoenrollment (automatic renewal of certificate). Certificate
is not removed but it remains valid until expiry date.

=item B<--renew>

Renew the certificate. Checks the validity of certificate and requests a new
one if it would expire in less than 7 (default) days from the time of check.

(this option is used mainly in the cron job)

=item B<--status>

Check current status of autoenrollment, certificate expiry and its existence.

=item B<--cern>

Process CERN CA certificates (this is the default option, may be omitted)

=item B<--grid>

Process CERN Grid CA certificates.

=item B<--force>

Override default checks and perform the operation.

=item B<--config CFGFILE>

Use alternate configuration file.
Note: /etc/cron.daily/cern-get-certificate should be altered if non-default 
configuration file is being used.

=item B<--usekrb5cfg>

Use temporary kerberos configuration file: 

/tmp/cgk.krb5.conf 

created by:

 cern-get-keytab --leavekrb5cfg 

for client initialization.

This is to be used in order to guarantee that same Active Directory Domain
Controller that cern-get-keytab used will be used, therefore eliminating the 
need to wait for (asynchronous) AD replication.

=item B<--hostname HOSTNAME>

Request certificate for HOSTNAME instead of default system hostname.
This option is to be used ONLY when system has multiple interfaces / ip addresses 
allocated. A keytab containing entries for non-default HOSTNAME is required.
(this can be obtained with cern-get-keytab) 

HOSTNAME should be specified as fully qualified hostname (XXX.cern.ch)
This option will not funciton for DNS host aliases.

If this option is used, it should be set also in the configuration file
for future certificate renewal.

=back

=head1 CONFIG FILE

 Configuration file /etc/sysconfig/cern-get-certificate contains default 
 settings:

=over 2

=item B<keypath> - default: /etc/pki/tls/private/

 Private path to store certificate key in.

=item B<certpath> - default: /etc/pki/tls/certs/

 Path to store certificate file in.

=item B<days> - default: 7

 If validity of obtained certificate is shorter than defined number of days a new certificate is requested.

=item B<uid> - default: 0 (root)

=item B<gid> - default: 0 (root)

 Certificate files are chown'ed to be owned by designated user on the system.

=item B<autorenew> - default: 1

  Perform automatic certificate renewal.

=item B<autorenewexec> - default: none

  Command to be executed after a certificate
  renewal is performed.

  Example: "/sbin/service httpd reload"

=item B<hostname> - default: none

  hostname for which certificate is to be obtained on multi interface systems.
  Use fully qualified hostname.

  Example: XXX.cern.ch

=back

=head1 EXAMPLES

=over 2

        cern-get-certificate --autoenroll
        cern-get-certificate --autoenroll --grid
	    cern-get-certificate --noautoenroll
	    cern-get-certificate --renew 
	    cern-get-certificate --status
        cern-get-certificate --status --grid
        cern-get-certificate --autoenroll --hostname XXX.cern.ch

=back

=head1 AUTHOR

Jaroslaw Polok <Jaroslaw.Polok@cern.ch>

=head1 NOTES

NO E-MAIL EXPIRATION WANMINGS are sent for CERN/Grid host certificates 
obtained using autoenrollment procedure

File names of stored certificate are:

key: 

          'hostname.cern.ch.key'
        [ 'hostname.cern.ch.grid.key' ]

certificate: 

          'hostname.cern.ch.pem' 
          'hostname.cern.ch.crt'
	[ 'hostname.cern.ch.grid.pem' ]
	[ 'hostname.cern.ch.grid.crt' ]

(in [] names when --grid option is specified.)

=head1 BUGS

?? (none reported ..)



