if( argc == 2 && std::string( "--once" ) == argv[1] ) {
once = true;
}
+
if( argc == 2 && std::string( "--reset" ) == argv[1] ) {
resetOnly = true;
}
logger::fatal( "Error: no serial device is given!" );
return -1;
}
+
std::shared_ptr<JobProvider> jp = std::make_shared<PostgresJobProvider>( sqlHost, sqlUser, sqlPass, sqlDB );
std::shared_ptr<BIO> b = openSerial( serialPath );
- std::shared_ptr<BIO_METHOD> m( toBio<SlipBIO>(), BIO_meth_free);
+ std::shared_ptr<BIO_METHOD> m( toBio<SlipBIO>(), BIO_meth_free );
std::shared_ptr<BIO> slip1( BIO_new( m.get() ), BIO_free );
static_cast<SlipBIO*>( slip1->ptr )->setTarget( std::make_shared<OpensslBIOWrapper>( b ), false );
auto sign = std::make_shared<RemoteSigner>( slip1, generateSSLContext( false ) );
time_t lastCRLCheck = 0;
while( true ) {
- try {
+ try {
time_t current;
time( ¤t );
}
std::shared_ptr<Job> 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;
std::shared_ptr<std::ofstream> 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 );
}
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 );
return 0;
}
} catch ( std::exception &e ){
- logger::errorf ( "std::exception in mainloop: %s", e.what() );
+ logger::errorf( "std::exception in mainloop: %s", e.what() );
}
}
DefaultRecordHandler* dh = new DefaultRecordHandler( std::shared_ptr<Signer>( new SimpleOpensslSigner( ) ), slip1 );
logger::note( "Entering mainloop" );
+
while( true ) {
try {
dh->handle();
}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;
}
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;
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 );
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<BIGNUM> serBNP( serBN, BN_free );
std::shared_ptr<ASN1_INTEGER> 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<ASN1_TIME> 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 );
}
void CRL::sign( std::shared_ptr<CAConfig> 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<ASN1_TIME> 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() );
}
const X509_ALGOR *palg;
const ASN1_BIT_STRING *psig;
- X509_CRL_get0_signature(crl.get(), &psig, &palg);
- int len = i2d_X509_ALGOR( const_cast<X509_ALGOR*>(palg), NULL );
- len += i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>(psig), NULL );
- len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_lastUpdate(crl.get())), NULL );
- len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_nextUpdate(crl.get())), NULL );
+ X509_CRL_get0_signature( crl.get(), &psig, &palg );
+ int len = i2d_X509_ALGOR( const_cast<X509_ALGOR*>( palg ), NULL );
+ len += i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>( psig ), NULL );
+ len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_lastUpdate( crl.get() ) ), NULL );
+ len += i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_nextUpdate( crl.get() ) ), NULL );
unsigned char* buffer = ( unsigned char* ) OPENSSL_malloc( len );
unsigned char* pos = buffer;
- i2d_X509_ALGOR( const_cast<X509_ALGOR*>(palg), &pos );
- i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>(psig), &pos );
- i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_lastUpdate(crl.get())), &pos );
- i2d_ASN1_TIME( const_cast<ASN1_TIME*>(X509_CRL_get0_nextUpdate(crl.get())), &pos );
+ i2d_X509_ALGOR( const_cast<X509_ALGOR*>( palg ), &pos );
+ i2d_ASN1_BIT_STRING( const_cast<ASN1_BIT_STRING*>( psig ), &pos );
+ i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_lastUpdate( crl.get() ) ), &pos );
+ i2d_ASN1_TIME( const_cast<ASN1_TIME*>( X509_CRL_get0_nextUpdate( crl.get() ) ), &pos );
std::string res = std::string( ( char* ) buffer, len );
OPENSSL_free( buffer );
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<EVP_PKEY>( pkt, EVP_PKEY_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<NETSCAPE_SPKI>( 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<EVP_PKEY>( pkt_p, EVP_PKEY_free );
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<X509Req>( new X509Req( req )); // TODO ask
+ return std::shared_ptr<X509Req>( new X509Req( req ) ); // TODO ask
}
std::shared_ptr<X509Req> X509Req::parseSPKAC( std::string content ) {
X509* c = X509_new();
if( !c ) {
- throw std::runtime_error("malloc failed");
+ throw std::runtime_error( "malloc failed" );
}
target = std::shared_ptr<X509>( 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<X509_NAME>( subjectP, X509_NAME_free );
void X509Cert::addRDN( int nid, std::string data ) {
if( ! X509_NAME_add_entry_by_NID( subject.get(), nid, MBSTRING_UTF8, ( unsigned char* )const_cast<char*>( 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<X509> 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" );
}
}
std::shared_ptr<EVP_PKEY> 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 ) {
return ext;
merr:
- throw std::runtime_error("memerr");
+ throw std::runtime_error( "memerr" );
}
void X509Cert::setExtensions( std::shared_ptr<X509> caCert, std::vector<std::shared_ptr<SAN>>& sans, Profile& prof, std::string crlURL, std::string crtURL ) {
std::string ku = std::string( "critical," ) + prof.ku;
add_ext( caCert, target, NID_key_usage, ku.c_str() );
add_ext( caCert, target, NID_ext_key_usage, prof.eku.c_str() );
- add_ext( caCert, target, NID_info_access, ("OCSP;URI:http://ocsp.cacert.org,caIssuers;URI:" + crtURL).c_str() );
- add_ext( caCert, target, NID_crl_distribution_points, ("URI:" + crlURL).c_str() );
+ add_ext( caCert, target, NID_info_access, ( "OCSP;URI:http://ocsp.cacert.org,caIssuers;URI:" + crtURL ).c_str() );
+ add_ext( caCert, target, NID_crl_distribution_points, ( "URI:" + crlURL ).c_str() );
if( sans.empty() ) {
return;
GENERAL_NAME* gen = GENERAL_NAME_new();
if( !gen ) {
- throw std::runtime_error("Malloc failure.");
+ throw std::runtime_error( "Malloc failure." );
}
gen->type = name->type == "DNS" ? GEN_DNS : name->type == "email" ? GEN_EMAIL : 0; // GEN_EMAIL;
|| !( gen->d.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 );
std::shared_ptr<SignedCertificate> X509Cert::sign( std::shared_ptr<EVP_PKEY> 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;
} 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() );
std::shared_ptr<BIO> mem = std::shared_ptr<BIO>( 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() );
auto res = std::make_shared<SignedCertificate>();
res->certificate = std::string( buf->data, buf->data + buf->length );
- std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(target.get()), NULL ), BN_free );
+ std::shared_ptr<BIGNUM> 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<char> serStr(
RecordHeader head;
std::string payload = parseCommandChunked( head, conn );
- switch( static_cast<RecordHeader::SignerResult>( head.command )) {
+ switch( static_cast<RecordHeader::SignerResult>( head.command ) ) {
case RecordHeader::SignerResult::CERTIFICATE:
result->certificate = payload;
break;
int dlen = BIO_write( bios.get(), buf, len );
if( dlen <= 0 ) {
- throw std::runtime_error("Memory error.");
+ throw std::runtime_error( "Memory error." );
}
len -= dlen;
std::shared_ptr<X509> 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<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber(pem.get()), NULL), BN_free );
+ std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( pem.get() ), NULL ), BN_free );
std::shared_ptr<char> serStr(
BN_bn2hex( ser.get() ),
[]( char* 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 result;
std::string date;
if( static_cast<RecordHeader::SignerResult>( head.command ) != RecordHeader::SignerResult::REVOKED ) {
- throw std::runtime_error("Protocol violation");
+ throw std::runtime_error( "Protocol violation" );
}
const unsigned char* buffer2 = reinterpret_cast<const unsigned char*>( payload.data() );
payload = parseCommandChunked( head, conn );
if( static_cast<RecordHeader::SignerResult>( 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" );
crl = std::make_shared<CRL>( 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" );
}
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 };
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." );
}
}
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<char> serStr = std::shared_ptr<char>(
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);
+ 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 );
if( !ca ) {
logger::error( "ERROR: Signing CA specified in profile could not be loaded." );
- throw std::runtime_error("CA-key not found");
+ 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.");
+
+ 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." );
req = X509Req::parseCSR( cert->csr_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." );
}
for( std::shared_ptr<AVA> 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" ) {
c.addRDN( NID_organizationalUnitName, a->value );
} 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" );
}
}
if( fn.empty() ) {
logger::error( "ERROR: failed to get filename for storage of signed certificate." );
- throw std::runtime_error("Storage location could not be determined");
+ throw std::runtime_error( "Storage location could not be determined" );
}
logger::note( "FINE: Certificate signed successfully." );
std::string date = "";
logger::note( "adding serials" );
+
for( std::string serial : serials ) {
date = crl->revoke( serial, "" );
}
} );
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 );
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 ) {
dh_param = std::shared_ptr<DH>( 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<FILE>( fopen( "dh_param.pem", "w" ), fclose );
}
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." );
}
}
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 );
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" );
}
}
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_TIME>( ASN1_STRING_dup(tm), ASN1_TIME_free );
+ notBefore = std::shared_ptr<ASN1_TIME>( 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<ASN1_TIME> time ) {
- std::shared_ptr<ASN1_GENERALIZEDTIME> gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free );
+ std::shared_ptr<ASN1_GENERALIZEDTIME> 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 );
std::time_t maxValidity;
std::shared_ptr<CAConfig> getCA() {
std::shared_ptr<CAConfig> 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;
}
}
}
#include <exception>
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<Job> 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<Job>();
job->id = result[0]["id"].as<std::string>();
job->target = result[0]["\"targetId\""].as<std::string>();
job->task = result[0]["task"].as<std::string>();
- job->from = result[0]["\"executeFrom\""].as<std::string>("");
- job->to = result[0]["\"executeTo\""].as<std::string>("");
+ job->from = result[0]["\"executeFrom\""].as<std::string>( "" );
+ job->to = result[0]["\"executeTo\""].as<std::string>( "" );
job->warning = result[0]["warning"].as<std::string>();
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 );
}
void PostgresJobProvider::finishJob( std::shared_ptr<Job> 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> 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<TBSCertificate> PostgresJobProvider::fetchTBSCert( std::shared_ptr<Job> job ) {
- pqxx::work txn(c);
+ pqxx::work txn( c );
auto cert = std::make_shared<TBSCertificate>();
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<std::string>();
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<SAN>();
nSAN->content = row["contents"].as<std::string>();
nSAN->type = row["type"].as<std::string>();
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<AVA>();
nAVA->name = row["name"].as<std::string>();
nAVA->value = row["value"].as<std::string>();
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> job, std::shared_ptr<SignedCertificate> 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>();
}
+
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<std::string, std::string> PostgresJobProvider::getRevocationInfo( std::shared_ptr<Job> 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<std::string>(), r[0][1].as<std::string>()};
}
void PostgresJobProvider::writeBackRevocation( std::shared_ptr<Job> 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" );
template <typename T>
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;
}
#include "opensslBIO.h"
#include <log/logger.hpp>
-OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr<BIO> _b ) : b( _b ), buffer( 2*0xFFFF+20, 0 ), pos(0) {
+OpensslBIOWrapper::OpensslBIOWrapper( std::shared_ptr<BIO> _b ) : b( _b ), buffer( 2 * 0xFFFF + 20, 0 ), pos( 0 ) {
}
OpensslBIOWrapper::~OpensslBIOWrapper() {
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;
}
}
std::string readLine();
};
-class eof_exception : public std::exception{
+class eof_exception : public std::exception {
};
void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr<OpensslBIO> 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<size_t>(0xF000), data.size() - pos);
+ size_t toTransfer = std::min( static_cast<size_t>( 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 );
pos += toTransfer;
head.offset += 1;
- } while(pos < data.size());
+ } while( pos < data.size() );
}
int32_t fromHexDigit( char c ) {
return res;
}
-std::string parseCommand( RecordHeader& head, const std::string& input) {
+std::string parseCommand( RecordHeader& head, const std::string& input ) {
logger::debug( "FINE: RECORD input: ", input );
int32_t dlen = ( input.size() - 2 ) / 2;
std::stringstream ss;
ss << "Expected: " << expectedTotalLength << ", Got: " << input.size();
logger::error( ss.str() );
- throw std::length_error("Error, invalid length");
+ throw std::length_error( "Error, invalid length" );
}
+
if( checksum != -1 || error || dlen < RECORD_HEADER_SIZE ) {
- throw std::runtime_error("Error, invalid checksum");
+ throw std::runtime_error( "Error, invalid checksum" );
}
data.pop_back();
return data;
}
-std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> io){
- logger::note("reading");
+std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> 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;
}
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();
};
std::string parseCommand( RecordHeader& head, const std::string& input );
-std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> conn);
+std::string parseCommandChunked( RecordHeader& head, std::shared_ptr<OpensslBIOWrapper> conn );
void sendCommand( RecordHeader& head, const std::string& data, std::shared_ptr<OpensslBIO> bio );
RecordHandlerSession( DefaultRecordHandler* parent, std::shared_ptr<Signer> signer, std::shared_ptr<SSL_CTX> ctx, std::shared_ptr<BIO> output ) :
tbs( std::make_shared<TBSCertificate>() ),
- logFile(openLogfile( "logs/log_" + timestamp() ) ),
+ logFile( openLogfile( "logs/log_" + timestamp() ) ),
logger{ std::cout, *logFile } {
this->parent = parent;
this->signer = signer;
}
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" );
break;
default:
- throw std::runtime_error("Unimplemented");
+ throw std::runtime_error( "Unimplemented" );
}
}
};
void DefaultRecordHandler::handle() {
if( !currentSession ) {
- (void) BIO_reset( bio.get() );
+ ( void ) BIO_reset( bio.get() );
logger::note( "New session allocated." );
currentSession = std::make_shared<RecordHandlerSession>( this, signer, ctx, bio );
}
+
try {
currentSession->work();
- } catch( eof_exception e ){
+ } catch( eof_exception e ) {
reset();
}
}
#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;
#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" );
#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
#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
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;
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
}
}
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++;
logger::note( "error connection failed" );
return -1;
}
+
logger::note( "got package border; slip re-validated SHOULD NEVER HAPPEN!!" );
decodeTarget = 0;
waitForConnection = false;
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
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<bool, time_t>( false, 0 );
auto res = std::make_unique<std::ofstream>( 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 );
}
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
BOOST_AUTO_TEST_SUITE( TestBioWrapper )
BOOST_AUTO_TEST_CASE( BasicCalls ) {
- std::shared_ptr<BIO_METHOD> m(toBio<OpensslBIO1>(), BIO_meth_free);
+ std::shared_ptr<BIO_METHOD> m( toBio<OpensslBIO1>(), BIO_meth_free );
std::shared_ptr<BIO> n( BIO_new( m.get() ), BIO_free );
OpensslBIO* o = new OpensslBIOWrapper( n );
OpensslBIO1* data = ( OpensslBIO1* ) n->ptr;