From 6121035a7d8ea738bc89c2de8e6602fb1099b0e2 Mon Sep 17 00:00:00 2001 From: Benny Baumann Date: Wed, 22 Mar 2017 23:39:44 +0100 Subject: [PATCH] fmt: whitespace, padding and indentation formatting Change-Id: I10baff23ab801e4b6fa47f3e943172bbce726ba5 --- src/apps/client.cpp | 18 ++++--- src/apps/signer.cpp | 5 +- src/config.cpp | 4 +- src/crypto/CRL.cpp | 55 ++++++++++--------- src/crypto/X509.cpp | 54 +++++++++---------- src/crypto/remoteSigner.cpp | 19 ++++--- src/crypto/simpleOpensslSigner.cpp | 34 ++++++------ src/crypto/sslUtil.cpp | 50 +++++++++-------- src/crypto/sslUtil.h | 11 ++-- src/db/psql.cpp | 84 ++++++++++++++++------------- src/io/bios.h | 16 +++--- src/io/opensslBIO.cpp | 32 ++++++----- src/io/opensslBIO.h | 2 +- src/io/record.cpp | 41 ++++++++------ src/io/record.h | 4 +- src/io/recordHandler.cpp | 11 ++-- src/io/slipBio.cpp | 87 +++++++++++++++++++----------- src/util.cpp | 10 ++-- src/util.h | 0 test/src/X509Req.cpp | 2 +- test/src/bioWrapper.cpp | 2 +- 21 files changed, 311 insertions(+), 230 deletions(-) mode change 100755 => 100644 src/util.h diff --git a/src/apps/client.cpp b/src/apps/client.cpp index 8744743..c3a0115 100644 --- a/src/apps/client.cpp +++ b/src/apps/client.cpp @@ -59,6 +59,7 @@ int main( int argc, const char* argv[] ) { if( argc == 2 && std::string( "--once" ) == argv[1] ) { once = true; } + if( argc == 2 && std::string( "--reset" ) == argv[1] ) { resetOnly = true; } @@ -80,9 +81,10 @@ int main( int argc, const char* argv[] ) { logger::fatal( "Error: no serial device is given!" ); return -1; } + std::shared_ptr jp = std::make_shared( sqlHost, sqlUser, sqlPass, sqlDB ); std::shared_ptr b = openSerial( serialPath ); - std::shared_ptr m( toBio(), BIO_meth_free); + std::shared_ptr m( toBio(), BIO_meth_free ); std::shared_ptr slip1( BIO_new( m.get() ), BIO_free ); static_cast( slip1->ptr )->setTarget( std::make_shared( b ), false ); auto sign = std::make_shared( slip1, generateSSLContext( false ) ); @@ -98,7 +100,7 @@ int main( int argc, const char* argv[] ) { time_t lastCRLCheck = 0; while( true ) { - try { + try { time_t current; time( ¤t ); @@ -114,11 +116,13 @@ int main( int argc, const char* argv[] ) { } std::shared_ptr job; + try { job = jp->fetchJob(); } catch ( std::exception &e ){ - logger::errorf ( "Exception while fetchJob: %s", e.what() ); - } + logger::errorf( "Exception while fetchJob: %s", e.what() ); + } + if( !job ) { sleep( 5 ); continue; @@ -126,7 +130,7 @@ int main( int argc, const char* argv[] ) { std::shared_ptr logPtr = openLogfile( std::string( "logs/" ) + job->id + std::string( "_" ) + job->warning + std::string( ".log" ) ); - logger::logger_set log_set({logger::log_target(*logPtr, logger::level::debug)}, logger::auto_register::on); + logger::logger_set log_set( {logger::log_target( *logPtr, logger::level::debug )}, logger::auto_register::on ); logger::note( "TASK ID: ", job->id ); logger::note( "TRY: ", job->warning ); @@ -168,7 +172,7 @@ int main( int argc, const char* argv[] ) { } logger::note( "FINE: CERTIFICATE LOG:\n", res->log, - "FINE: CERTIFICATE:\n", res->certificate ); + "FINE: CERTIFICATE:\n", res->certificate ); std::string fn = writeBackFile( job->target.c_str(), res->certificate, keyDir ); @@ -222,7 +226,7 @@ int main( int argc, const char* argv[] ) { return 0; } } catch ( std::exception &e ){ - logger::errorf ( "std::exception in mainloop: %s", e.what() ); + logger::errorf( "std::exception in mainloop: %s", e.what() ); } } diff --git a/src/apps/signer.cpp b/src/apps/signer.cpp index 1db3e14..80b5a71 100644 --- a/src/apps/signer.cpp +++ b/src/apps/signer.cpp @@ -54,6 +54,7 @@ int main( int argc, const char* argv[] ) try { DefaultRecordHandler* dh = new DefaultRecordHandler( std::shared_ptr( new SimpleOpensslSigner( ) ), slip1 ); logger::note( "Entering mainloop" ); + while( true ) { try { dh->handle(); @@ -72,12 +73,14 @@ int main( int argc, const char* argv[] ) try { }catch( std::exception &e){ printf( "Fatal Error (+logger failed): %s!\n", e.what() ); } + return -1; } catch( ... ) { - try{ + try { logger::fatal( "Fatal Error: Unknown Exception!\n" ); }catch( std::exception &e){ printf( "Fatal Error (+ logger failed): %s!\n", e.what() ); } + return -1; } diff --git a/src/config.cpp b/src/config.cpp index 164e0bb..a4d3284 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -23,7 +23,7 @@ std::shared_ptr> parseConf( std::st if( !config.is_open() ) { logger::notef( "Where is \"%s\"?", path ); - throw std::runtime_error("Config missing"); + throw std::runtime_error( "Config missing" ); } std::string line1; @@ -117,7 +117,7 @@ int parseProfiles() { closedir( dir ); } else { - throw std::runtime_error("Directory with CAConfigs not found"); + throw std::runtime_error( "Directory with CAConfigs not found" ); } profiles.emplace( profileName, prof ); diff --git a/src/crypto/CRL.cpp b/src/crypto/CRL.cpp index 01f8af5..f9159fc 100644 --- a/src/crypto/CRL.cpp +++ b/src/crypto/CRL.cpp @@ -16,34 +16,36 @@ CRL::CRL( std::string path ) { std::string CRL::revoke( std::string serial, std::string time ) { BIGNUM* serBN = 0; - logger::note("parsing serial"); + logger::note( "parsing serial" ); + if( ! BN_hex2bn( &serBN, serial.c_str() ) ) { - throw std::runtime_error("hex2bn malloc fail"); + throw std::runtime_error( "hex2bn malloc fail" ); } std::shared_ptr serBNP( serBN, BN_free ); std::shared_ptr ser( BN_to_ASN1_INTEGER( serBN, NULL ), ASN1_INTEGER_free ); if( !ser ) { - throw std::runtime_error("BN Malloc fail"); + throw std::runtime_error( "BN Malloc fail" ); } - logger::note("building current time"); + logger::note( "building current time" ); std::shared_ptr tmptm( ASN1_TIME_new(), ASN1_TIME_free ); if( !tmptm ) { - throw std::runtime_error("ASN1-Time Malloc fail"); + throw std::runtime_error( "ASN1-Time Malloc fail" ); } X509_gmtime_adj( tmptm.get(), 0 ); - logger::note("creating entry"); + logger::note( "creating entry" ); X509_REVOKED* rev = X509_REVOKED_new(); X509_REVOKED_set_serialNumber( rev, ser.get() ); if( time != "" ) { - ASN1_TIME_set_string( tmptm.get(), time.data() ); + ASN1_TIME_set_string( tmptm.get(), time.data() ); } + X509_REVOKED_set_revocationDate( rev, tmptm.get() ); X509_CRL_add0_revoked( crl.get(), rev ); @@ -58,38 +60,39 @@ std::string CRL::revoke( std::string serial, std::string time ) { } void CRL::sign( std::shared_ptr ca ) { - if(!ca->caKey){ - throw new std::invalid_argument("Cannot sign CRL with CA " + ca->name + " because it has no private key."); + if( !ca->caKey ) { + throw new std::invalid_argument( "Cannot sign CRL with CA " + ca->name + " because it has no private key." ); } // Updating necessary CRL props std::shared_ptr tmptm( ASN1_TIME_new(), ASN1_TIME_free ); if( !tmptm ) { - throw std::runtime_error("ASN1-Time Malloc fail"); + throw std::runtime_error( "ASN1-Time Malloc fail" ); } X509_gmtime_adj( tmptm.get(), 0 ); - logger::note("setting issuer"); + logger::note( "setting issuer" ); + if( !X509_CRL_set_issuer_name( crl.get(), X509_get_subject_name( ca->ca.get() ) ) ) { - throw std::runtime_error("Setting issuer failed"); + throw std::runtime_error( "Setting issuer failed" ); } - logger::note("setting update"); + logger::note( "setting update" ); X509_CRL_set_lastUpdate( crl.get(), tmptm.get() ); if( !X509_time_adj_ex( tmptm.get(), 1, 10, NULL ) ) { - throw std::runtime_error("Updating time failed"); + throw std::runtime_error( "Updating time failed" ); } - logger::note("setting next update"); + logger::note( "setting next update" ); X509_CRL_set_nextUpdate( crl.get(), tmptm.get() ); - logger::note("sorting"); + logger::note( "sorting" ); // Sorting and signing X509_CRL_sort( crl.get() ); - logger::note("signing"); + logger::note( "signing" ); X509_CRL_sign( crl.get(), ca->caKey.get(), EVP_sha256() ); } @@ -112,18 +115,18 @@ std::string CRL::getSignature() { const X509_ALGOR *palg; const ASN1_BIT_STRING *psig; - X509_CRL_get0_signature(crl.get(), &psig, &palg); - int len = i2d_X509_ALGOR( const_cast(palg), NULL ); - len += i2d_ASN1_BIT_STRING( const_cast(psig), NULL ); - len += i2d_ASN1_TIME( const_cast(X509_CRL_get0_lastUpdate(crl.get())), NULL ); - len += i2d_ASN1_TIME( const_cast(X509_CRL_get0_nextUpdate(crl.get())), NULL ); + X509_CRL_get0_signature( crl.get(), &psig, &palg ); + int len = i2d_X509_ALGOR( const_cast( palg ), NULL ); + len += i2d_ASN1_BIT_STRING( const_cast( psig ), NULL ); + len += i2d_ASN1_TIME( const_cast( X509_CRL_get0_lastUpdate( crl.get() ) ), NULL ); + len += i2d_ASN1_TIME( const_cast( X509_CRL_get0_nextUpdate( crl.get() ) ), NULL ); unsigned char* buffer = ( unsigned char* ) OPENSSL_malloc( len ); unsigned char* pos = buffer; - i2d_X509_ALGOR( const_cast(palg), &pos ); - i2d_ASN1_BIT_STRING( const_cast(psig), &pos ); - i2d_ASN1_TIME( const_cast(X509_CRL_get0_lastUpdate(crl.get())), &pos ); - i2d_ASN1_TIME( const_cast(X509_CRL_get0_nextUpdate(crl.get())), &pos ); + i2d_X509_ALGOR( const_cast( palg ), &pos ); + i2d_ASN1_BIT_STRING( const_cast( psig ), &pos ); + i2d_ASN1_TIME( const_cast( X509_CRL_get0_lastUpdate( crl.get() ) ), &pos ); + i2d_ASN1_TIME( const_cast( X509_CRL_get0_nextUpdate( crl.get() ) ), &pos ); std::string res = std::string( ( char* ) buffer, len ); OPENSSL_free( buffer ); diff --git a/src/crypto/X509.cpp b/src/crypto/X509.cpp index f9dbc7a..e304b90 100644 --- a/src/crypto/X509.cpp +++ b/src/crypto/X509.cpp @@ -11,7 +11,7 @@ X509Req::X509Req( X509_REQ* csr ) : req( csr, X509_REQ_free ) { EVP_PKEY* pkt = X509_REQ_get_pubkey( req.get() ); if( !pkt ) { - throw std::runtime_error("Error extracting public key"); + throw std::runtime_error( "Error extracting public key" ); } pk = std::shared_ptr( pkt, EVP_PKEY_free ); @@ -19,21 +19,21 @@ X509Req::X509Req( X509_REQ* csr ) : req( csr, X509_REQ_free ) { X509Req::X509Req( std::string spkac ) { if( spkac.compare( 0, 6, "SPKAC=" ) != 0 ) { - throw std::runtime_error("Error: not a SPKAC"); + throw std::runtime_error( "Error: not a SPKAC" ); } spkac = spkac.substr( 6 ); NETSCAPE_SPKI* spki_p = NETSCAPE_SPKI_b64_decode( spkac.c_str(), spkac.size() ); if( !spki_p ) { - throw std::runtime_error("Error: decode failed"); + throw std::runtime_error( "Error: decode failed" ); } spki = std::shared_ptr( spki_p, NETSCAPE_SPKI_free ); EVP_PKEY* pkt_p = NETSCAPE_SPKI_get_pubkey( spki.get() ); if( !pkt_p ) { - throw std::runtime_error("Error: reading SPKAC Pubkey failed"); + throw std::runtime_error( "Error: reading SPKAC Pubkey failed" ); } pk = std::shared_ptr( pkt_p, EVP_PKEY_free ); @@ -56,10 +56,10 @@ std::shared_ptr X509Req::parseCSR( std::string content ) { X509_REQ* req = PEM_read_bio_X509_REQ( in.get(), NULL, NULL, NULL ); if( !req ) { - throw std::runtime_error("Error parsing CSR"); + throw std::runtime_error( "Error parsing CSR" ); } - return std::shared_ptr( new X509Req( req )); // TODO ask + return std::shared_ptr( new X509Req( req ) ); // TODO ask } std::shared_ptr X509Req::parseSPKAC( std::string content ) { @@ -94,19 +94,19 @@ X509Cert::X509Cert() { X509* c = X509_new(); if( !c ) { - throw std::runtime_error("malloc failed"); + throw std::runtime_error( "malloc failed" ); } target = std::shared_ptr( c, X509_free ); if( !X509_set_version( c, 2 ) ) { - throw std::runtime_error("Setting X509-version to 3 failed"); + throw std::runtime_error( "Setting X509-version to 3 failed" ); } X509_NAME* subjectP = X509_NAME_new(); if( !subjectP ) { - throw std::runtime_error("malloc failure in construct."); + throw std::runtime_error( "malloc failure in construct." ); } subject = std::shared_ptr( subjectP, X509_NAME_free ); @@ -114,13 +114,13 @@ X509Cert::X509Cert() { void X509Cert::addRDN( int nid, std::string data ) { if( ! X509_NAME_add_entry_by_NID( subject.get(), nid, MBSTRING_UTF8, ( unsigned char* )const_cast( data.data() ), data.size(), -1, 0 ) ) { - throw std::runtime_error("malloc failure in RDN"); + throw std::runtime_error( "malloc failure in RDN" ); } } void X509Cert::setIssuerNameFrom( std::shared_ptr caCert ) { if( !X509_set_issuer_name( target.get(), X509_get_subject_name( caCert.get() ) ) ) { - throw std::runtime_error("Error setting Issuer name"); + throw std::runtime_error( "Error setting Issuer name" ); } } @@ -128,14 +128,14 @@ void X509Cert::setPubkeyFrom( std::shared_ptr req ) { std::shared_ptr pktmp = req->getPkey(); if( !X509_set_pubkey( target.get(), pktmp.get() ) ) { - throw std::runtime_error("Setting public key failed."); + throw std::runtime_error( "Setting public key failed." ); } } void X509Cert::setSerialNumber( BIGNUM* num ) { ASN1_INTEGER *i = BN_to_ASN1_INTEGER( num, NULL); - X509_set_serialNumber(target.get(), i); - ASN1_INTEGER_free(i); + X509_set_serialNumber( target.get(), i ); + ASN1_INTEGER_free( i ); } void X509Cert::setTimes( uint32_t before, uint32_t after ) { @@ -173,7 +173,7 @@ static X509_EXTENSION* do_ext_i2d( int ext_nid, int crit, ASN1_VALUE* ext_struc return ext; merr: - throw std::runtime_error("memerr"); + throw std::runtime_error( "memerr" ); } void X509Cert::setExtensions( std::shared_ptr caCert, std::vector>& sans, Profile& prof, std::string crlURL, std::string crtURL ) { @@ -183,8 +183,8 @@ void X509Cert::setExtensions( std::shared_ptr caCert, std::vector caCert, std::vectortype = name->type == "DNS" ? GEN_DNS : name->type == "email" ? GEN_EMAIL : 0; // GEN_EMAIL; @@ -211,7 +211,7 @@ void X509Cert::setExtensions( std::shared_ptr caCert, std::vectord.ia5 = ASN1_IA5STRING_new() ) || !ASN1_STRING_set( gen->d.ia5, name->content.data(), name->content.size() ) ) { GENERAL_NAME_free( gen ); - throw std::runtime_error("initing iasting5 failed"); + throw std::runtime_error( "initing iasting5 failed" ); } sk_GENERAL_NAME_push( gens.get(), gen ); @@ -225,7 +225,7 @@ void X509Cert::setExtensions( std::shared_ptr caCert, std::vector X509Cert::sign( std::shared_ptr caKey, std::string signAlg ) { if( !X509_set_subject_name( target.get(), subject.get() ) ) { - throw std::runtime_error("error setting subject"); + throw std::runtime_error( "error setting subject" ); } const EVP_MD* md; @@ -237,15 +237,15 @@ std::shared_ptr X509Cert::sign( std::shared_ptr caK } else if( signAlg == "sha256" ) { md = EVP_sha256(); } else if( signAlg == "sha1" ) { - throw std::runtime_error("Refusing to sign with weak signature algorithm (SHA-1)."); + throw std::runtime_error( "Refusing to sign with weak signature algorithm (SHA-1)." ); } else if( signAlg == "md5" ) { - throw std::runtime_error("Refusing to sign with weak signature algorithm (MD5)."); + throw std::runtime_error( "Refusing to sign with weak signature algorithm (MD5)." ); } else { - throw std::runtime_error("Unknown signature algorithm"); + throw std::runtime_error( "Unknown signature algorithm" ); } if( !X509_sign( target.get(), caKey.get(), md ) ) { - throw std::runtime_error("Signing failed."); + throw std::runtime_error( "Signing failed." ); } //X509_print_fp( stdout, target.get() ); @@ -253,7 +253,7 @@ std::shared_ptr X509Cert::sign( std::shared_ptr caK std::shared_ptr mem = std::shared_ptr( BIO_new( BIO_s_mem() ), BIO_free ); if( !mem ) { - throw std::runtime_error("Failed to allocate memory for the signed certificate."); + throw std::runtime_error( "Failed to allocate memory for the signed certificate." ); } PEM_write_bio_X509( mem.get(), target.get() ); @@ -264,10 +264,10 @@ std::shared_ptr X509Cert::sign( std::shared_ptr caK auto res = std::make_shared(); res->certificate = std::string( buf->data, buf->data + buf->length ); - std::shared_ptr ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(target.get()), NULL ), BN_free ); + std::shared_ptr ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( target.get() ), NULL ), BN_free ); if( !ser ) { - throw std::runtime_error("Failed to retrieve certificate serial of signed certificate."); + throw std::runtime_error( "Failed to retrieve certificate serial of signed certificate." ); } std::shared_ptr serStr( diff --git a/src/crypto/remoteSigner.cpp b/src/crypto/remoteSigner.cpp index a953458..c52936b 100644 --- a/src/crypto/remoteSigner.cpp +++ b/src/crypto/remoteSigner.cpp @@ -75,7 +75,7 @@ std::shared_ptr RemoteSigner::sign( std::shared_ptr( head.command )) { + switch( static_cast( head.command ) ) { case RecordHeader::SignerResult::CERTIFICATE: result->certificate = payload; break; @@ -107,7 +107,7 @@ std::shared_ptr RemoteSigner::sign( std::shared_ptr RemoteSigner::sign( std::shared_ptr pem( PEM_read_bio_X509( bios.get(), NULL, 0, NULL ), X509_free ); if( !pem ) { - throw std::runtime_error("Pem was not readable"); + throw std::runtime_error( "Pem was not readable" ); } - std::shared_ptr ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(pem.get()), NULL), BN_free ); + std::shared_ptr ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( pem.get() ), NULL ), BN_free ); std::shared_ptr serStr( BN_bn2hex( ser.get() ), []( char* p ) { @@ -133,9 +133,11 @@ std::shared_ptr RemoteSigner::sign( std::shared_ptr, std::string> RemoteSigner::revoke( std::shared_p std::string date; if( static_cast( head.command ) != RecordHeader::SignerResult::REVOKED ) { - throw std::runtime_error("Protocol violation"); + throw std::runtime_error( "Protocol violation" ); } const unsigned char* buffer2 = reinterpret_cast( payload.data() ); @@ -196,7 +198,7 @@ std::pair, std::string> RemoteSigner::revoke( std::shared_p payload = parseCommandChunked( head, conn ); if( static_cast( head.command ) != RecordHeader::SignerResult::FULL_CRL ) { - throw std::runtime_error("Protocol violation"); + throw std::runtime_error( "Protocol violation" ); } std::string name_bak = ca->path + std::string( "/ca.crl.bak" ); @@ -204,9 +206,10 @@ std::pair, std::string> RemoteSigner::revoke( std::shared_p crl = std::make_shared( name_bak ); if( crl->verify( ca ) ) { - if( rename( name_bak.c_str(), tgtName.c_str() ) != 0 ){ + if( rename( name_bak.c_str(), tgtName.c_str() ) != 0 ) { logger::warn( "Moving new CRL over old CRL failed" ); } + logger::note( "CRL is now valid again" ); } else { logger::warn( "CRL is still broken... Please, help me" ); @@ -214,9 +217,11 @@ std::pair, std::string> RemoteSigner::revoke( std::shared_p } logger::note( "Closing SSL connection" ); + if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { // need to close the connection twice logger::warn( "SSL shutdown failed" ); } + logger::note( "SSL connection closed" ); return { crl, date }; diff --git a/src/crypto/simpleOpensslSigner.cpp b/src/crypto/simpleOpensslSigner.cpp index 6987d2c..b569ef2 100644 --- a/src/crypto/simpleOpensslSigner.cpp +++ b/src/crypto/simpleOpensslSigner.cpp @@ -36,12 +36,12 @@ std::pair, std::string> SimpleOpensslSigner::nextSerial( if( res == "" ) { bn = BN_new(); - if( !bn || !BN_hex2bn( &bn, "1" )) { - throw std::runtime_error("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 std::runtime_error("Parsing serial failed."); + throw std::runtime_error( "Parsing serial failed." ); } } @@ -57,7 +57,7 @@ std::pair, 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 std::runtime_error("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 serStr = std::shared_ptr( @@ -68,12 +68,12 @@ std::pair, std::string> SimpleOpensslSigner::nextSerial( writeFile( ca->path + "/serial", serStr.get() ); - return std::pair, std::string>( std::shared_ptr( BN_bin2bn( data.get(), len + 4 + 16 , 0 ), BN_free ), std::string( serStr.get() ) ); + return std::pair, std::string>( std::shared_ptr( BN_bin2bn( data.get(), len + 4 + 16, 0 ), BN_free ), std::string( serStr.get() ) ); } std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptr cert ) { std::stringstream signlog; - logger::logger_set log_set_sign({logger::log_target(signlog, logger::level::debug)}, logger::auto_register::on); + logger::logger_set log_set_sign( {logger::log_target( signlog, logger::level::debug )}, logger::auto_register::on ); logger::note( "FINE: Profile name is: ", cert->profile ); @@ -84,10 +84,11 @@ std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptrcaKey){ - throw std::runtime_error("Cannot sign certificate with CA " + ca->name + " because it has no private key."); + + if( !ca->caKey ) { + throw std::runtime_error( "Cannot sign certificate with CA " + ca->name + " because it has no private key." ); } logger::note( "FINE: Key for Signing CA is correctly loaded." ); @@ -106,15 +107,15 @@ std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptrcsr_content ); } else { 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 + 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 std::runtime_error("Request contains a Signature with problems ... "); + throw std::runtime_error( "Request contains a Signature with problems ... " ); } else if( i == 0 ) { - throw std::runtime_error("Request contains a Signature that does not match ..."); + throw std::runtime_error( "Request contains a Signature that does not match ..." ); } else { logger::note( "FINE: Request contains valid self-signature." ); } @@ -126,10 +127,12 @@ std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptr a : cert->AVAs ) { 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); + logger::notef( "INFO: Removing empty RDN: %s", a->name ); continue; } + if( a->name == "CN" ) { c.addRDN( NID_commonName, a->value ); } else if( a->name == "EMAIL" ) { @@ -146,7 +149,7 @@ std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptrvalue ); } else { logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name ); - throw std::runtime_error("Unhandled/Illegal AVA type"); + throw std::runtime_error( "Unhandled/Illegal AVA type" ); } } @@ -248,7 +251,7 @@ std::shared_ptr SimpleOpensslSigner::sign( std::shared_ptr, std::string> SimpleOpensslSigner::revoke( std::s std::string date = ""; logger::note( "adding serials" ); + for( std::string serial : serials ) { date = crl->revoke( serial, "" ); } diff --git a/src/crypto/sslUtil.cpp b/src/crypto/sslUtil.cpp index d7fddfe..8a68c61 100644 --- a/src/crypto/sslUtil.cpp +++ b/src/crypto/sslUtil.cpp @@ -97,7 +97,7 @@ std::shared_ptr generateSSLContext( bool server ) { } ); if( !SSL_CTX_set_cipher_list( ctx.get(), "HIGH:+CAMELLIA256:!eNull:!aNULL:!ADH:!MD5:-RSA+AES+SHA1:!RC4:!DES:!3DES:!SEED:!EXP:!AES128:!CAMELLIA128" ) ) { - throw std::runtime_error("Cannot set cipher list. Your source is broken."); + throw std::runtime_error( "Cannot set cipher list. Your source is broken." ); } SSL_CTX_set_verify( ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback ); @@ -105,7 +105,7 @@ std::shared_ptr generateSSLContext( bool server ) { SSL_CTX_use_PrivateKey_file( ctx.get(), server ? "keys/signer_server.key" : "keys/signer_client.key", SSL_FILETYPE_PEM ); if( 1 != SSL_CTX_load_verify_locations( ctx.get(), "keys/ca.crt", 0 ) ) { - throw std::runtime_error("Cannot load CA store for certificate validation."); + throw std::runtime_error( "Cannot load CA store for certificate validation." ); } if( server ) { @@ -126,12 +126,13 @@ std::shared_ptr generateSSLContext( bool server ) { dh_param = std::shared_ptr( DH_new(), DH_free ); logger::note( "Generating DH params" ); BN_GENCB *cb = BN_GENCB_new(); - BN_GENCB_set(cb, gencb, NULL); + BN_GENCB_set( cb, gencb, NULL ); if( !DH_generate_parameters_ex( dh_param.get(), 2048, 5, cb ) ) { - throw std::runtime_error("DH generation failed"); + throw std::runtime_error( "DH generation failed" ); } - BN_GENCB_free(cb); + + BN_GENCB_free( cb ); std::cout << std::endl; paramfile = std::shared_ptr( fopen( "dh_param.pem", "w" ), fclose ); @@ -143,7 +144,7 @@ std::shared_ptr generateSSLContext( bool server ) { } if( !SSL_CTX_set_tmp_dh( ctx.get(), dh_param.get() ) ) { - throw std::runtime_error("Cannot set tmp dh."); + throw std::runtime_error( "Cannot set tmp dh." ); } } @@ -154,7 +155,7 @@ void setupSerial( std::shared_ptr f ) { struct termios attr; if( tcgetattr( fileno( f.get() ), &attr ) ) { - throw std::runtime_error("failed to get attrs"); + throw std::runtime_error( "failed to get attrs" ); } attr.c_iflag &= ~( IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON ); @@ -167,7 +168,7 @@ void setupSerial( std::shared_ptr f ) { cfsetospeed( &attr, B115200 ); if( tcsetattr( fileno( f.get() ), TCSANOW, &attr ) ) { - throw std::runtime_error("failed to get attrs"); + throw std::runtime_error( "failed to get attrs" ); } } @@ -192,35 +193,40 @@ extern std::string crtPrefix; CAConfig::CAConfig( const std::string& name ) : path( "ca/" + name ), name( name ) { ca = loadX509FromFile( path + "/ca.crt" ); - if (!ca) { - throw new std::invalid_argument("ca name: " + name + " contains unreadable certificate."); + + if( !ca ) { + throw new std::invalid_argument( "ca name: " + name + " contains unreadable certificate." ); } caKey = loadPkeyFromFile( path + "/ca.key" ); ASN1_TIME* tm = X509_get_notBefore( ca.get() ); // tm MUST NOT be free'd; duplicate for owning copy. - notBefore = std::shared_ptr( ASN1_STRING_dup(tm), ASN1_TIME_free ); + notBefore = std::shared_ptr( ASN1_STRING_dup( tm ), ASN1_TIME_free ); + + std::size_t pos = name.find( "_" ); - std::size_t pos = name.find("_"); - if (pos == std::string::npos) { - throw new std::invalid_argument("ca name: " + name + " is malformed."); + if( pos == std::string::npos ) { + throw new std::invalid_argument( "ca name: " + name + " is malformed." ); } - std::size_t pos2 = name.find("_", pos + 1); - if (pos2 == std::string::npos) { - throw new std::invalid_argument("ca name: " + name + " is malformed."); + + std::size_t pos2 = name.find( "_", pos + 1 ); + + if( pos2 == std::string::npos ) { + throw new std::invalid_argument( "ca name: " + name + " is malformed." ); } - crlURL = crlPrefix + "/g2/" + name.substr(pos+1, pos2-pos - 1) + "/" + name.substr(0,pos) + "-" + name.substr(pos2+1) + ".crl"; - crtURL = crtPrefix + "/g2/" + name.substr(pos+1, pos2-pos - 1) + "/" + name.substr(0,pos) + "-" + name.substr(pos2+1) + ".crt"; + crlURL = crlPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crl"; + crtURL = crtPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crt"; } std::string timeToString( std::shared_ptr time ) { - std::shared_ptr gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free ); + std::shared_ptr gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free ); std::string strdate( ( char* ) ASN1_STRING_get0_data( gtime.get() ), ASN1_STRING_length( gtime.get() ) ); - logger::notef("openssl formatted me a date: %s", strdate); + logger::notef( "openssl formatted me a date: %s", strdate ); + if( strdate[strdate.size() - 1] != 'Z' ) { - throw std::runtime_error("Got invalid date?"); + throw std::runtime_error( "Got invalid date?" ); } return strdate.substr( 0, strdate.size() - 1 ); diff --git a/src/crypto/sslUtil.h b/src/crypto/sslUtil.h index 569c200..2ecba42 100644 --- a/src/crypto/sslUtil.h +++ b/src/crypto/sslUtil.h @@ -36,14 +36,15 @@ struct Profile { std::time_t maxValidity; std::shared_ptr getCA() { std::shared_ptr min = nullptr; + for( auto it = ca.rbegin(); it != ca.rend(); it++ ) { - if( X509_cmp_current_time( ( *it )->notBefore.get() ) < 0) { - if(min != nullptr){ - if(strcmp(min->name.c_str(), (*it)->name.c_str()) < 0){ + if( X509_cmp_current_time( ( *it )->notBefore.get() ) < 0 ) { + if( min != nullptr ) { + if( strcmp( min->name.c_str(), ( *it )->name.c_str() ) < 0 ) { min = *it; } - }else{ - min=*it; + } else { + min = *it; } } } diff --git a/src/db/psql.cpp b/src/db/psql.cpp index 053f11b..4121994 100644 --- a/src/db/psql.cpp +++ b/src/db/psql.cpp @@ -8,15 +8,15 @@ #include PostgresJobProvider::PostgresJobProvider( const std::string& server, const std::string& user, const std::string& password, const std::string& database ): - c("dbname="+database+" host="+server+" user="+user+" password=" + password + " client_encoding=UTF-8 application_name=cassiopeia-client"){ + c( "dbname=" + database + " host=" + server + " user=" + user + " password=" + password + " client_encoding=UTF-8 application_name=cassiopeia-client" ) { // TODO better connection string generation?? } std::shared_ptr PostgresJobProvider::fetchJob() { std::string q = "SELECT id, \"targetId\", task, \"executeFrom\", \"executeTo\", warning FROM jobs WHERE state='open' AND warning < 3"; - pqxx::work txn(c); - pqxx::result result = txn.exec(q); + pqxx::work txn( c ); + pqxx::result result = txn.exec( q ); auto job = std::make_shared(); @@ -28,8 +28,8 @@ std::shared_ptr PostgresJobProvider::fetchJob() { job->id = result[0]["id"].as(); job->target = result[0]["\"targetId\""].as(); job->task = result[0]["task"].as(); - job->from = result[0]["\"executeFrom\""].as(""); - job->to = result[0]["\"executeTo\""].as(""); + job->from = result[0]["\"executeFrom\""].as( "" ); + job->to = result[0]["\"executeTo\""].as( "" ); job->warning = result[0]["warning"].as(); logger::notef( "Got a job: (id=%s, target=%s, task=%s, from=%s, to=%s, warnings=%s)", job->id, job->target, job->task, job->from, job->to, job->warning ); @@ -38,38 +38,41 @@ std::shared_ptr PostgresJobProvider::fetchJob() { } void PostgresJobProvider::finishJob( std::shared_ptr job ) { - pqxx::work txn(c); + pqxx::work txn( c ); std::string q = "UPDATE jobs SET state='done' WHERE id=" + txn.quote( job->id ); - pqxx::result r = txn.exec(q); + pqxx::result r = txn.exec( q ); if( r.affected_rows() != 1 ) { - throw std::runtime_error("No database entry found."); + throw std::runtime_error( "No database entry found." ); } + txn.commit(); } void PostgresJobProvider::failJob( std::shared_ptr job ) { - pqxx::work txn(c); + pqxx::work txn( c ); std::string q = "UPDATE jobs SET warning = warning + 1 WHERE id=" + txn.quote( job->id ); - pqxx::result r = txn.exec(q); + pqxx::result r = txn.exec( q ); if( r.affected_rows() != 1 ) { - throw std::runtime_error("No database entry found."); + throw std::runtime_error( "No database entry found." ); } + txn.commit(); } std::shared_ptr PostgresJobProvider::fetchTBSCert( std::shared_ptr job ) { - pqxx::work txn(c); + pqxx::work txn( c ); auto cert = std::make_shared(); std::string q = "SELECT md, profile, csr_name, csr_type, keyname FROM certs INNER JOIN profiles ON profiles.id = certs.profile WHERE certs.id=" + txn.quote( job->target ); - pqxx::result r = txn.exec(q); + pqxx::result r = txn.exec( q ); if( r.size() != 1 ) { - throw std::runtime_error("Error, no or multiple certs found"); - } + throw std::runtime_error( "Error, no or multiple certs found" ); + } + auto ro = r[0]; std::string profileName = ro["keyname"].as(); @@ -93,7 +96,7 @@ std::shared_ptr PostgresJobProvider::fetchTBSCert( std::shared_p std::cout << "Fetching SANs" << std::endl; - for( auto row = r.begin(); row != r.end(); ++row) { + for( auto row = r.begin(); row != r.end(); ++row ) { auto nSAN = std::make_shared(); nSAN->content = row["contents"].as(); nSAN->type = row["type"].as(); @@ -103,7 +106,7 @@ std::shared_ptr PostgresJobProvider::fetchTBSCert( std::shared_p q = "SELECT name, value FROM \"certAvas\" WHERE \"certId\"=" + txn.quote( job->target ); r = txn.exec( q ); - for( auto row = r.begin(); row != r.end(); ++row) { + for( auto row = r.begin(); row != r.end(); ++row ) { auto nAVA = std::make_shared(); nAVA->name = row["name"].as(); nAVA->value = row["value"].as(); @@ -113,58 +116,65 @@ std::shared_ptr PostgresJobProvider::fetchTBSCert( std::shared_p return cert; } -std::string pgTime( std::string isoTime){ - return isoTime.substr(0, 8) + " " + isoTime.substr(8, 6); +std::string pgTime( std::string isoTime ) { + return isoTime.substr( 0, 8 ) + " " + isoTime.substr( 8, 6 ); } void PostgresJobProvider::writeBack( std::shared_ptr job, std::shared_ptr res ) { - pqxx::work txn(c); + pqxx::work txn( c ); std::string id = "SELECT id FROM cacerts WHERE keyname=" + txn.quote( res->ca_name ); - pqxx::result r = txn.exec(id); + pqxx::result r = txn.exec( id ); std::string read_id; - if( r.size() != 1) { - throw std::runtime_error("Error while inserting new ca cert not found"); + if( r.size() != 1 ) { + throw std::runtime_error( "Error while inserting new ca cert not found" ); } else { read_id = r[0]["id"].as(); } + std::string serial = res->serial; - std::transform(serial.begin(), serial.end(), serial.begin(), ::tolower); - if(serial[0] == '0'){ - serial = serial.substr(1); + std::transform( serial.begin(), serial.end(), serial.begin(), ::tolower ); + + if( serial[0] == '0' ) { + serial = serial.substr( 1 ); } - std::string q = "UPDATE certs SET crt_name=" + txn.quote( res->crt_name ) + ", serial=" + txn.quote( serial ) + ", \"caid\" = " + txn.quote( read_id ) + ", created=" + txn.quote( pgTime(res->before) ) + ", expire=" + txn.quote( pgTime(res->after) ) + " WHERE id=" + txn.quote( job->target ); + + std::string q = "UPDATE certs SET crt_name=" + txn.quote( res->crt_name ) + ", serial=" + txn.quote( serial ) + ", \"caid\" = " + txn.quote( read_id ) + ", created=" + txn.quote( pgTime( res->before ) ) + ", expire=" + txn.quote( pgTime( res->after ) ) + " WHERE id=" + txn.quote( job->target ); // TODO write more thingies back r = txn.exec( q ); - if( r.affected_rows() != 1 ){ - throw std::runtime_error("Only one row should be updated."); + + if( r.affected_rows() != 1 ) { + throw std::runtime_error( "Only one row should be updated." ); } + txn.commit(); } std::pair PostgresJobProvider::getRevocationInfo( std::shared_ptr job ) { - pqxx::work txn(c); + pqxx::work txn( c ); std::string q = "SELECT certs.serial, cacerts.keyname FROM certs INNER JOIN cacerts ON certs.\"caid\" = cacerts.id WHERE certs.id = " + txn.quote( job->target ); pqxx::result r = txn.exec( q ); - if( r.size() != 1) { - throw std::runtime_error("Only one row expected but multiple found."); + + if( r.size() != 1 ) { + throw std::runtime_error( "Only one row expected but multiple found." ); } - return {r[0][0].as(), r[0][1].as()}; } void PostgresJobProvider::writeBackRevocation( std::shared_ptr job, std::string date ) { - logger::notef( "Revoking at %s", date); - pqxx::work txn(c); + logger::notef( "Revoking at %s", date ); + pqxx::work txn( c ); logger::note( "executing" ); pqxx::result r = txn.exec( "UPDATE certs SET revoked = " + txn.quote( pgTime( date ) ) + " WHERE id = " + txn.quote( job->target ) ); - if( r.affected_rows() != 1 ){ - throw std::runtime_error("Only one row should be updated."); + + if( r.affected_rows() != 1 ) { + throw std::runtime_error( "Only one row should be updated." ); } + logger::note( "committing" ); txn.commit(); logger::note( "committed" ); diff --git a/src/io/bios.h b/src/io/bios.h index b1acf18..3bbb66b 100644 --- a/src/io/bios.h +++ b/src/io/bios.h @@ -68,14 +68,14 @@ BIO_METHOD* toBio() { template BIO_METHOD* toBio( int ( *newfunc )( BIO* ) ) { - BIO_METHOD *meth = BIO_meth_new(T::typeID, T::getName()); - BIO_meth_set_write(meth, BIOWrapper::write); - BIO_meth_set_read(meth, BIOWrapper::read); - BIO_meth_set_puts(meth, BIOWrapper::puts); - BIO_meth_set_gets(meth, BIOWrapper::gets); - BIO_meth_set_ctrl(meth, BIOWrapper::ctrl); - BIO_meth_set_destroy(meth, BIOWrapper::free); - BIO_meth_set_create(meth, newfunc); + BIO_METHOD *meth = BIO_meth_new( T::typeID, T::getName() ); + BIO_meth_set_write( meth, BIOWrapper::write ); + BIO_meth_set_read( meth, BIOWrapper::read ); + BIO_meth_set_puts( meth, BIOWrapper::puts ); + BIO_meth_set_gets( meth, BIOWrapper::gets ); + BIO_meth_set_ctrl( meth, BIOWrapper::ctrl ); + BIO_meth_set_destroy( meth, BIOWrapper::free ); + BIO_meth_set_create( meth, newfunc ); return meth; } diff --git a/src/io/opensslBIO.cpp b/src/io/opensslBIO.cpp index 02fd472..1369960 100644 --- a/src/io/opensslBIO.cpp +++ b/src/io/opensslBIO.cpp @@ -1,7 +1,7 @@ #include "opensslBIO.h" #include -OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr _b ) : b( _b ), buffer( 2*0xFFFF+20, 0 ), pos(0) { +OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr _b ) : b( _b ), buffer( 2 * 0xFFFF + 20, 0 ), pos( 0 ) { } OpensslBIOWrapper::~OpensslBIOWrapper() { @@ -30,31 +30,37 @@ int OpensslBIOWrapper::gets( char* str, int size ) { const char* OpensslBIOWrapper::getName() { return "OpenSSLWrapper"; } -std::string OpensslBIOWrapper::readLine(){ +std::string OpensslBIOWrapper::readLine() { int target = 0; - while(1){ - logger::debug("doing data"); - while(target < pos){ - if(buffer[target] == '\n'){ + + while( 1 ) { + logger::debug( "doing data" ); + + while( target < pos ) { + if( buffer[target] == '\n' ) { target++; - std::string res(buffer.data(), 0, target); - std::copy(buffer.data() + target, buffer.data() + pos, buffer.data() ); + std::string res( buffer.data(), 0, target ); + std::copy( buffer.data() + target, buffer.data() + pos, buffer.data() ); pos -= target; - logger::debug("emit"); + logger::debug( "emit" ); return res; } + target++; } + std::stringstream ss; ss << "target: " << target << ", pos:" << pos; - logger::debug(ss.str()); - int dlen = read(buffer.data() + pos, buffer.size() - pos); - if ( dlen <= 0 ){ + logger::debug( ss.str() ); + int dlen = read( buffer.data() + pos, buffer.size() - pos ); + + if( dlen <= 0 ) { throw eof_exception(); } + std::stringstream ss2; ss2 << "done: " << dlen; - logger::debug(ss2.str()); + logger::debug( ss2.str() ); pos += dlen; } } diff --git a/src/io/opensslBIO.h b/src/io/opensslBIO.h index 994b7bc..1cf96f8 100644 --- a/src/io/opensslBIO.h +++ b/src/io/opensslBIO.h @@ -26,5 +26,5 @@ public: std::string readLine(); }; -class eof_exception : public std::exception{ +class eof_exception : public std::exception { }; diff --git a/src/io/record.cpp b/src/io/record.cpp index 4cc5b89..268897d 100644 --- a/src/io/record.cpp +++ b/src/io/record.cpp @@ -27,17 +27,18 @@ std::string toHexAndChecksum( const std::string& src ) { void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr bio ) { std::stringstream ss; ss << data.size(); - logger::debugf( "Record payload length: %s", ss.str() ); + logger::debugf( "Record payload length: %s", ss.str() ); size_t pos = 0; head.offset = 0; head.totalLength = data.size(); + do { - size_t toTransfer = std::min(static_cast(0xF000), data.size() - pos); + size_t toTransfer = std::min( static_cast( 0xF000 ), data.size() - pos ); head.payloadLength = toTransfer; std::string s; s += head.packToString(); - s += data.substr(pos, toTransfer); + s += data.substr( pos, toTransfer ); std::string res = toHexAndChecksum( s ); @@ -47,7 +48,7 @@ void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr io){ - logger::note("reading"); +std::string parseCommandChunked( RecordHeader& head, std::shared_ptr io ) { + logger::note( "reading" ); std::string payload = parseCommand( head, io->readLine() ); - std::string all(head.totalLength, ' '); + std::string all( head.totalLength, ' ' ); auto target = all.begin(); size_t pos = 0; RecordHeader head2; - while(true) { + + while( true ) { pos += head.payloadLength; - target = std::copy ( payload.begin(), payload.end(), target); - if(pos >= head.totalLength) { + target = std::copy( payload.begin(), payload.end(), target ); + + if( pos >= head.totalLength ) { break; } - logger::note("chunk digested, reading next one"); + + logger::note( "chunk digested, reading next one" ); + payload = parseCommand( head2, io->readLine() ); - if(!head2.isFollowupOf(head)){ - throw std::runtime_error("Error, header of follow up chunk was malformed"); + + if( !head2.isFollowupOf( head ) ) { + throw std::runtime_error( "Error, header of follow up chunk was malformed" ); } + head = head2; } + return all; } diff --git a/src/io/record.h b/src/io/record.h index 48dd8af..5d6e659 100644 --- a/src/io/record.h +++ b/src/io/record.h @@ -90,7 +90,7 @@ public: void unpackFromString( const std::string& str ) { if( str.size() != RECORD_HEADER_SIZE ) { - throw std::runtime_error("Invalid string length"); + throw std::runtime_error( "Invalid string length" ); } auto it = str.cbegin(); @@ -108,6 +108,6 @@ public: }; std::string parseCommand( RecordHeader& head, const std::string& input ); -std::string parseCommandChunked( RecordHeader& head, std::shared_ptr conn); +std::string parseCommandChunked( RecordHeader& head, std::shared_ptr conn ); void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr bio ); diff --git a/src/io/recordHandler.cpp b/src/io/recordHandler.cpp index f8c2185..2eb8358 100644 --- a/src/io/recordHandler.cpp +++ b/src/io/recordHandler.cpp @@ -45,7 +45,7 @@ public: RecordHandlerSession( DefaultRecordHandler* parent, std::shared_ptr signer, std::shared_ptr ctx, std::shared_ptr output ) : tbs( std::make_shared() ), - logFile(openLogfile( "logs/log_" + timestamp() ) ), + logFile( openLogfile( "logs/log_" + timestamp() ) ), logger{ std::cout, *logFile } { this->parent = parent; this->signer = signer; @@ -160,9 +160,11 @@ public: } logger::note( "Shutting down SSL" ); + if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { logger::warn( "ERROR: SSL shutdown failed." ); } + io->ctrl( BIO_CTRL_FLUSH, 0, NULL ); logger::note( "Shutted down SSL" ); @@ -207,7 +209,7 @@ public: break; default: - throw std::runtime_error("Unimplemented"); + throw std::runtime_error( "Unimplemented" ); } } }; @@ -222,13 +224,14 @@ void DefaultRecordHandler::reset() { void DefaultRecordHandler::handle() { if( !currentSession ) { - (void) BIO_reset( bio.get() ); + ( void ) BIO_reset( bio.get() ); logger::note( "New session allocated." ); currentSession = std::make_shared( this, signer, ctx, bio ); } + try { currentSession->work(); - } catch( eof_exception e ){ + } catch( eof_exception e ) { reset(); } } diff --git a/src/io/slipBio.cpp b/src/io/slipBio.cpp index 29bc41e..619159f 100644 --- a/src/io/slipBio.cpp +++ b/src/io/slipBio.cpp @@ -61,6 +61,7 @@ int SlipBIO::write( const char* buf, int num ) { #ifdef SLIP_IO_DEBUG logger::notef( "slip-out: %s", toHex( buf, num ) ); #endif + if( waitForReset ) { logger::note( "denying read because of reset-need!" ); return -1; @@ -111,7 +112,7 @@ int SlipBIO::write( const char* buf, int num ) { #endif if( dlen < 0 ) { - throw std::runtime_error("Error, target write failed"); + throw std::runtime_error( "Error, target write failed" ); } else if( dlen == 0 ) { // sleep logger::note( "waiting for write ability" ); @@ -132,25 +133,30 @@ int SlipBIO::read( char* buf, int size ) { #ifdef UNMASK_DEBUG logger::note( "starting read" ); #endif + // while we have no data to decode or unmasking does not yield a full package while( decodeTarget == 0 ) { if( waitForReset ) { logger::note( "denying read because of reset-need!" ); return -1; } - if(decodePos < rawPos) { + + if( decodePos < rawPos ) { int res = unmask(); + if( res == 1 ) { continue; // probably Packet :-) - } else if(res == -1) { + } else if( res == -1 ) { logger::note( "sending reset because of malfomed packet" ); - return -1; + return -1; } } - if( decodeTarget != 0 ){ + + if( decodeTarget != 0 ) { // we have data now, emit it! break; } + // we have no data, read more if( buffer.size() - rawPos < 64 ) { // not enough space... package is too big @@ -171,19 +177,23 @@ int SlipBIO::read( char* buf, int size ) { #endif int len = target->read( buffer.data() + rawPos, buffer.size() - rawPos ); #ifdef RAW_IO_DEBUG - logger::note( toHex(buffer.data() + rawPos, len ) ); + logger::note( toHex( buffer.data() + rawPos, len ) ); #endif + if( len > 0 ) { rawPos += len; } else { - logger::note("Reporting EOS from slip"); + logger::note( "Reporting EOS from slip" ); return -1; //decodeTarget = 0; //failed = true; } } - if( waitForReset ) return -1; + + if( waitForReset ) { + return -1; + } int len = std::min( decodeTarget, ( unsigned int ) size ); // a package finished, return it @@ -197,8 +207,8 @@ int SlipBIO::read( char* buf, int size ) { convert << ", requested were: " << size; logger::note( convert.str() ); #endif - - if(decodeTarget == 0 && rawPos <= decodePos + 1){ + + if( decodeTarget == 0 && rawPos <= decodePos + 1 ) { // compact the remaining at most 1 byte of raw data buffer[0] = buffer[decodePos]; rawPos -= decodePos; @@ -219,23 +229,25 @@ long SlipBIO::ctrl( int cmod, long arg1, void* arg2 ) { if( cmod == BIO_CTRL_RESET ) { decodeTarget = 0; + if( server ) { waitForReset = false; waitForConnection = true; resetCounter = -1; } else { static char ctr = 8; - char resetSequence[] = {SLIP_CONNECTION, 1,2,3,4,5,6,7, ctr}; + char resetSequence[] = {SLIP_CONNECTION, 1, 2, 3, 4, 5, 6, 7, ctr}; target->write( resetSequence, 9 ); header = {1, 2, 3, 4, 5, 6, 7, ctr}; resetCounter = -1; waitForConnection = true; logger::note( "Resetting SLIP layer" ); } + return 0; - }else if(cmod == BIO_CTRL_FLUSH ){ + } else if( cmod == BIO_CTRL_FLUSH ) { #ifdef UNMASK_DEBUG - logger::note( "flush requested "); + logger::note( "flush requested " ); #endif } @@ -257,82 +269,94 @@ int SlipBIO::unmask() { } logger::note( "unmasking" ); #endif - if( waitForConnection ){ + + if( waitForConnection ) { #ifdef UNMASK_DEBUG logger::note( "scanning for connection" ); #endif decodeTarget = 0; + if( server ) { #ifdef UNMASK_DEBUG - logger::note( "on server site, waiting for CONNECTION-byte"); + logger::note( "on server site, waiting for CONNECTION-byte" ); #endif - while(decodePos < rawPos) { - if(buffer[decodePos] == SLIP_CONNECTION) { + + while( decodePos < rawPos ) { + if( buffer[decodePos] == SLIP_CONNECTION ) { resetCounter = 0; #ifdef UNMASK_DEBUG logger::note( "got connection byte" ); #endif - } else if(resetCounter >= 0) { + } else if( resetCounter >= 0 ) { header[resetCounter] = buffer[decodePos]; resetCounter++; } + decodePos++; - if( resetCounter >= ((int) header.size()) ){ + + if( resetCounter >= ( ( int ) header.size() ) ) { waitForConnection = false; char data[] = { SLIP_CONNECTION }; - target->write( data, 1); + target->write( data, 1 ); #ifdef UNMASK_DEBUG - logger::notef( "SLIP, initing connection with ping-seq %s:", toHex(header.data(), header.size()) ); + logger::notef( "SLIP, initing connection with ping-seq %s:", toHex( header.data(), header.size() ) ); #endif target->write( header.data(), header.size() ); break; } } - if( decodePos >= rawPos ){ + + if( decodePos >= rawPos ) { decodePos = 0; rawPos = 0; return 0; // no package } - + } else { - while(decodePos < rawPos) { - if(buffer[decodePos] == SLIP_CONNECTION) { + while( decodePos < rawPos ) { + if( buffer[decodePos] == SLIP_CONNECTION ) { #ifdef UNMASK_DEBUG logger::note( "got connbyte" ); #endif resetCounter = 0; - } else if(resetCounter >= 0) { + } else if( resetCounter >= 0 ) { #ifdef UNMASK_DEBUG logger::note( "got head-byte" ); #endif - if(buffer[decodePos] == header[resetCounter]) { + + if( buffer[decodePos] == header[resetCounter] ) { resetCounter++; } else { resetCounter = -1; } } + decodePos++; - if( resetCounter >= ((int) header.size()) ){ + + if( resetCounter >= ( ( int ) header.size() ) ) { waitForConnection = false; #ifdef UNMASK_DEBUG - logger::note("connection found! :-)!"); + logger::note( "connection found! :-)!" ); #endif break; } } - if( decodePos >= rawPos ){ + + if( decodePos >= rawPos ) { rawPos = 0; decodePos = 0; return 0; // no package } } } + unsigned int j = decodeTarget; for( unsigned int i = decodePos; i < rawPos; i++ ) { - if(waitForConnection && buffer[i] != SLIP_CONNECTION ) { + if( waitForConnection && buffer[i] != SLIP_CONNECTION ) { continue; } + if( buffer[i] == SLIP_ESCAPE_CHAR ) { i++; @@ -374,6 +398,7 @@ int SlipBIO::unmask() { logger::note( "error connection failed" ); return -1; } + logger::note( "got package border; slip re-validated SHOULD NEVER HAPPEN!!" ); decodeTarget = 0; waitForConnection = false; diff --git a/src/util.cpp b/src/util.cpp index e721021..55d5864 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -29,7 +29,7 @@ std::string writeBackFile( const std::string& serial, const std::string& cert, c if( 0 != mkdir( filename.c_str(), 0755 ) ) { if( EEXIST != errno ) { - throw std::runtime_error("Storage location could not be determined"); + throw std::runtime_error( "Storage location could not be determined" ); } //! \FIXME: Check this is a directory @@ -144,7 +144,7 @@ std::pair parseMonthInterval( std::time_t t, const std::string& da try { size_t end = 0; - int num = std::stoi( date.substr( 0, date.size() - 1 ) , &end ); + int num = std::stoi( date.substr( 0, date.size() - 1 ), &end ); if( end != date.size() - 1 ) { return std::pair( false, 0 ); @@ -191,16 +191,18 @@ std::unique_ptr openLogfile( const std::string &name ) { auto res = std::make_unique( tname ); if( ! res->good() ) { - throw std::runtime_error( std::string("Failed to open file for logging: " ) + name ); + throw std::runtime_error( std::string( "Failed to open file for logging: " ) + name ); } return res; } -std::string timestamp(){ +std::string timestamp() { time_t c_time; + if( time( &c_time ) == -1 ) { throw std::runtime_error( "Error while fetching time?" ); } + return std::to_string( c_time ); } diff --git a/src/util.h b/src/util.h old mode 100755 new mode 100644 diff --git a/test/src/X509Req.cpp b/test/src/X509Req.cpp index 0d8300b..f8bb604 100644 --- a/test/src/X509Req.cpp +++ b/test/src/X509Req.cpp @@ -15,7 +15,7 @@ BOOST_AUTO_TEST_CASE( CSR ) { ERR_load_crypto_strings(); ERR_free_strings(); SSL_load_error_strings(); - ERR_print_errors_fp(stdout); + ERR_print_errors_fp( stdout ); BOOST_REQUIRE( ERR_peek_error() == 0 ); // Testing a valid CSR diff --git a/test/src/bioWrapper.cpp b/test/src/bioWrapper.cpp index 1f6d705..dbf6a6d 100644 --- a/test/src/bioWrapper.cpp +++ b/test/src/bioWrapper.cpp @@ -40,7 +40,7 @@ const char* OpensslBIO1::getName() { BOOST_AUTO_TEST_SUITE( TestBioWrapper ) BOOST_AUTO_TEST_CASE( BasicCalls ) { - std::shared_ptr m(toBio(), BIO_meth_free); + std::shared_ptr m( toBio(), BIO_meth_free ); std::shared_ptr n( BIO_new( m.get() ), BIO_free ); OpensslBIO* o = new OpensslBIOWrapper( n ); OpensslBIO1* data = ( OpensslBIO1* ) n->ptr; -- 2.39.2