]> WPIA git - cassiopeia.git/blobdiff - src/crypto/simpleOpensslSigner.cpp
fix: use correct prepared statement for writing logs
[cassiopeia.git] / src / crypto / simpleOpensslSigner.cpp
index 914d26e459fff0b9c8b994d2044c4d2392e31834..a6d037188fbbf915336db93e305c9a0d71dc165b 100644 (file)
@@ -2,6 +2,7 @@
 
 #include <sstream>
 #include <unordered_map>
+#include <exception>
 
 #include <openssl/ssl.h>
 #include <openssl/err.h>
 #include <openssl/engine.h>
 #include <openssl/x509v3.h>
 
+#include "log/logger.hpp"
+
 #include "X509.h"
 #include "util.h"
 #include "sslUtil.h"
 
 extern std::unordered_map<std::string, Profile> profiles;
+extern std::unordered_map<std::string, std::shared_ptr<CAConfig>> CAs;
 
 std::shared_ptr<int> SimpleOpensslSigner::lib_ref = ssl_lib_ref;
 
@@ -28,23 +32,23 @@ std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial(
     uint16_t profile = prof.id;
     std::string res = readFile( ca->path + "/serial" );
 
-    BIGNUMbn = 0;
+    BIGNUM *bn = 0;
 
     if( res == "" ) {
         bn = BN_new();
 
-        if( !bn ) {
-            throw "Initing serial failed";
+        if( !bn || !BN_hex2bn( &bn, "1" ) ) {
+            throw std::runtime_error( "Initing serial failed" );
         }
     } else {
         if( !BN_hex2bn( &bn, res.c_str() ) ) {
-            throw "Parsing serial failed.";
+            throw std::runtime_error( "Parsing serial failed." );
         }
     }
 
     std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
 
-    std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char* ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
+    std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char * ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
     int len = BN_bn2bin( serial.get(), data.get() );
 
     data.get()[len] = 0x0;
@@ -54,42 +58,62 @@ std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial(
     data.get()[len + 3] = profile & 0xFF; // profile id
 
     if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
-        throw "Big number math failed while fetching random data for serial number.";
+        throw std::runtime_error( "Big number math failed while fetching random data for serial number." );
     }
 
-    std::shared_ptr<char> serStr = std::shared_ptr<char>(
-        BN_bn2hex( serial.get() ),
-        []( char* ref ) {
-            OPENSSL_free( ref );
-        } );
+    auto freeMem = []( char *ref ) {
+        OPENSSL_free( ref );
+    };
+    std::shared_ptr<char> serStr = std::shared_ptr<char>( BN_bn2hex( serial.get() ), freeMem );
 
     writeFile( ca->path + "/serial", serStr.get() );
 
-    return std::pair<std::shared_ptr<BIGNUM>, std::string>( std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16 , 0 ), BN_free ), std::string( serStr.get() ) );
+    return std::pair<std::shared_ptr<BIGNUM>, std::string>( std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16, 0 ), BN_free ), std::string( serStr.get() ) );
 }
 
 std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
     std::stringstream signlog;
+    logger::logger_set log_set_sign( {logger::log_target( signlog, logger::level::debug )}, logger::auto_register::on );
+
+    std::shared_ptr<CAConfig> ca;
+    Profile *prof;
 
-    signlog << "FINE: profile is " << cert->profile << std::endl;
+    if( cert->ocspCA != "" ) {
+        auto caIterator = CAs.find( cert->ocspCA );
 
-    Profile& prof = profiles.at( cert->profile );
-    signlog << "FINE: Profile id is: " << prof.id << std::endl;
+        if( caIterator == CAs.end() ) {
+            logger::error( "ERROR: Signing CA specified in request for an OCSP cert could not be loaded." );
+            throw std::runtime_error( "CA-key for OCSP cert not found" );
+        }
 
-    std::shared_ptr<CAConfig> ca = prof.getCA();
+        ca = caIterator->second;
+        logger::note( "Trying to fetch OCSP-profile" );
+        prof = &profiles.at( "0100-ocsp" );
+        logger::note( "Done with it" );
+    } else {
+        logger::note( "FINE: Profile name is: ", cert->profile );
+
+        prof = &profiles.at( cert->profile );
+        logger::note( "FINE: Profile ID is: ", prof->id );
+        ca = prof->getCA();
+    }
 
     if( !ca ) {
-        signlog << "ERROR: Signing CA specified in profile could not be loaded." << std::endl;
-        throw "CA-key not found";
+        logger::error( "ERROR: Signing CA specified in profile could not be loaded." );
+        throw std::runtime_error( "CA-key not found" );
+    }
+
+    if( !ca->caKey ) {
+        throw std::runtime_error( "Cannot sign certificate with CA " + ca->name + " because it has no private key." );
     }
 
-    signlog << "FINE: Key for Signing CA is correctly loaded." << std::endl;
+    logger::note( "FINE: Key for Signing CA is correctly loaded." );
 
-    signlog << "INFO: Baseline Key Usage is: " << prof.ku << std::endl;
-    signlog << "INFO: Extended Key Usage is: " << prof.eku << std::endl;
+    logger::note( "INFO: Baseline Key Usage is: ", prof->ku );
+    logger::note( "INFO: Extended Key Usage is: ", prof->eku );
 
-    signlog << "FINE: Signing is wanted by: " << cert->wishFrom << std::endl;
-    signlog << "FINE: Signing is wanted for: " << cert->wishTo << std::endl;
+    logger::note( "FINE: Signing is wanted by: ", cert->wishFrom );
+    logger::note( "FINE: Signing is wanted for: ", cert->wishTo );
 
     std::shared_ptr<X509Req> req;
 
@@ -98,26 +122,32 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
     } else if( cert->csr_type == "CSR" ) {
         req = X509Req::parseCSR( cert->csr_content );
     } else {
-        signlog << "ERROR: Unknown type of certification in request: " << cert->csr_type << std::endl;
-        throw "Error, unknown REQ rype " + ( cert->csr_type );
+        logger::errorf( "ERROR: Unknown type (\"%s\") of certification in request.", cert->csr_type );
+        throw std::runtime_error( "Error, unknown REQ rype " + cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classe)s
     }
 
     int i = req->verify();
 
     if( i < 0 ) {
-        throw "Request contains a Signature with problems ... ";
+        throw std::runtime_error( "Request contains a Signature with problems ... " );
     } else if( i == 0 ) {
-        throw "Request contains a Signature that does not match ...";
+        throw std::runtime_error( "Request contains a Signature that does not match ..." );
     } else {
-        signlog << "FINE: Request contains valid self-signature." << std::endl;
+        logger::note( "FINE: Request contains valid self-signature." );
     }
 
     // Construct the Certificate
     X509Cert c = X509Cert();
 
-    signlog << "INFO: Populating RDN ..." << std::endl;
+    logger::note( "INFO: Populating RDN ..." );
+
     for( std::shared_ptr<AVA> a : cert->AVAs ) {
-        signlog << "INFO: Trying to add RDN: " << a->name << ": " << a->value << std::endl;
+        logger::notef( "INFO: Trying to add RDN: %s: %s", a->name, a->value );
+
+        if( a->value.empty() ) {
+            logger::notef( "INFO: Removing empty RDN: %s", a->name );
+            continue;
+        }
 
         if( a->name == "CN" ) {
             c.addRDN( NID_commonName, a->value );
@@ -134,34 +164,34 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
         } else if( a->name == "OU" ) {
             c.addRDN( NID_organizationalUnitName, a->value );
         } else {
-            signlog << "ERROR: Trying to add illegal RDN/AVA type: " << a->name << std::endl;
-            throw "Unhandled/Illegal AVA type";
+            logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name );
+            throw std::runtime_error( "Unhandled/Illegal AVA type" );
         }
     }
 
-    signlog << "INFO: Populating Issuer ..." << std::endl;
+    logger::note( "INFO: Populating Issuer ..." );
     c.setIssuerNameFrom( ca->ca );
 
-    signlog << "INFO: Validating Public key for use in certificate" << std::endl;
-    signlog << "INFO: - Checking generic key parameters" << std::endl;
-    signlog << "FINE:   ->Public Key parameters are okay" << std::endl;
+    logger::note( "INFO: Validating Public key for use in certificate" );
+    logger::note( "INFO: - Checking generic key parameters" );
+    logger::note( "FINE:   ->Public Key parameters are okay" );
 
-    signlog << "INFO: - Checking blacklists" << std::endl;
-    signlog << "FINE:   ->Does not appear on any blacklist" << std::endl;
+    logger::note( "INFO: - Checking blacklists" );
+    logger::note( "FINE:   ->Does not appear on any blacklist" );
 
-    signlog << "INFO: - Checking trivial factorization" << std::endl;
-    signlog << "FINE:   ->Trivial factorization not possible" << std::endl;
+    logger::note( "INFO: - Checking trivial factorization" );
+    logger::note( "FINE:   ->Trivial factorization not possible" );
 
-    signlog << "INFO: - Checking astrological signs" << std::endl;
-    signlog << "FINE:   ->The stars look good for this one" << std::endl;
-    signlog << "FINE: Public key is fine for use in certificate" << std::endl;
+    logger::note( "INFO: - Checking astrological signs" );
+    logger::note( "FINE:   ->The stars look good for this one" );
+    logger::note( "FINE: Public key is fine for use in certificate" );
 
-    signlog << "INFO: Copying Public Key from Request ..." << std::endl;
+    logger::note( "INFO: Copying Public Key from Request ..." );
     c.setPubkeyFrom( req );
-    signlog << "FINE: Public Key successfully copied from Request." << std::endl;
+    logger::note( "FINE: Public Key successfully copied from Request." );
 
     {
-        signlog << "INFO: Determining Validity Period ..." << std::endl;
+        logger::note( "INFO: Determining Validity Period ..." );
         std::time_t from, to;
         std::time_t now = time( 0 );
         std::pair<bool, std::time_t> parsed;
@@ -176,7 +206,7 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
             from = now;
         }
 
-        if( ((from - now) > /* 2 Weeks */ (2 * 7 * 24 * 60 * 60)) || ((now - from) >= 0) ) {
+        if( ( ( from - now ) > /* 2 Weeks */ ( 2 * 7 * 24 * 60 * 60 ) ) || ( ( now - from ) >= 0 ) ) {
             from = now;
         }
 
@@ -194,72 +224,77 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
             to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
         }
 
-        time_t limit = prof.maxValidity;
+        time_t limit = prof->maxValidity;
 
-        if( (to - from > limit) || (to - from < 0) ) {
+        if( ( to - from > limit ) || ( to - from < 0 ) ) {
             to = from + limit;
         }
 
         c.setTimes( from, to );
-        signlog << "FINE: Setting validity period successful:" << std::endl;
+        logger::note( "FINE: Setting validity period successful:" );
         {
-            struct tmtimeobj;
+            struct tm *timeobj;
             std::vector<char> timebuf;
 
-            timeobj = gmtime(&from);
-            timebuf.resize(128);
-            timebuf.resize(std::strftime(const_cast<char *>(timebuf.data()), timebuf.size(), "%F %T %Z", timeobj));
-            signlog << "FINE: - Valid not before: " << std::string(timebuf.cbegin(), timebuf.cend()) << std::endl;
+            timeobj = gmtime( &from );
+            timebuf.resize( 128 );
+            timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
+            logger::note( "FINE: - Valid not before: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
 
-            timeobj = gmtime(&to);
-            timebuf.resize(128);
-            timebuf.resize(std::strftime(const_cast<char *>(timebuf.data()), timebuf.size(), "%F %T %Z", timeobj));
-            signlog << "FINE: - Valid not after:  " << std::string(timebuf.cbegin(), timebuf.cend()) << std::endl;
+            timeobj = gmtime( &to );
+            timebuf.resize( 128 );
+            timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
+            logger::note( "FINE: - Valid not after:  ", std::string( timebuf.cbegin(), timebuf.cend() ) );
         }
     }
 
-    signlog << "INFO: Setting extensions:" << std::endl;
-    c.setExtensions( ca->ca, cert->SANs, prof );
-    signlog << "FINE: Setting extensions successful." << std::endl;
+    logger::note( "INFO: Setting extensions:" );
+    c.setExtensions( ca->ca, cert->SANs, *prof, ca->crlURL, ca->crtURL );
+    logger::note( "FINE: Setting extensions successful." );
 
-    signlog << "INFO: Generating next Serial Number ..." << std::endl;
+    logger::note( "INFO: Generating next Serial Number ..." );
     std::shared_ptr<BIGNUM> ser;
     std::string num;
-    std::tie( ser, num ) = nextSerial( prof, ca );
+    std::tie( ser, num ) = nextSerial( *prof, ca );
     c.setSerialNumber( ser.get() );
-    signlog << "FINE: Certificate Serial Number set to:" << num << std::endl;
+    logger::note( "FINE: Certificate Serial Number set to: ", num );
 
     {
-        signlog << "INFO: Trying to sign Certificate:" << std::endl;
+        logger::note( "INFO: Trying to sign Certificate:" );
         std::shared_ptr<SignedCertificate> output = c.sign( ca->caKey, cert->md );
-        signlog << "INFO: Writing certificate to local file." << std::endl;
+        logger::note( "INFO: Writing certificate to local file." );
         std::string fn = writeBackFile( num, output->certificate, ca->path );
 
         if( fn.empty() ) {
-            signlog << "ERROR: failed to get filename for storage of signed certificate." << std::endl;
-            throw "Storage location could not be determined";
+            logger::error( "ERROR: failed to get filename for storage of signed certificate." );
+            throw std::runtime_error( "Storage location could not be determined" );
         }
-        signlog << "FINE: Certificate signed successfully." << std::endl;
-        signlog << "FINE: - Certificate written to: " << fn << std::endl;
+
+        logger::note( "FINE: Certificate signed successfully." );
+        logger::note( "FINE: - Certificate written to: ", fn );
 
         output->ca_name = ca->name;
         output->log = signlog.str();
         return output;
     }
-
 }
 
 std::pair<std::shared_ptr<CRL>, std::string> SimpleOpensslSigner::revoke( std::shared_ptr<CAConfig> ca, std::vector<std::string> serials ) {
+    logger::note( "revoking" );
     std::string crlpath = ca->path + "/ca.crl";
 
-    std::shared_ptr<CRL> crl( new CRL( crlpath ) );
+    auto crl = std::make_shared<CRL>( crlpath );
     std::string date = "";
 
+    logger::note( "adding serials" );
+
     for( std::string serial : serials ) {
         date = crl->revoke( serial, "" );
     }
 
+    logger::note( "signing CRL" );
     crl->sign( ca );
     writeFile( crlpath, crl->toString() );
+    logger::note( "wrote CRL" );
     return std::pair<std::shared_ptr<CRL>, std::string>( crl, date );
 }