1 #include "simpleOpensslSigner.h"
4 #include <unordered_map>
7 #include <openssl/ssl.h>
8 #include <openssl/err.h>
9 #include <openssl/bio.h>
10 #include <openssl/bn.h>
11 #include <openssl/engine.h>
12 #include <openssl/x509v3.h>
14 #include "log/logger.hpp"
20 extern std::unordered_map<std::string, Profile> profiles;
22 std::shared_ptr<int> SimpleOpensslSigner::lib_ref = ssl_lib_ref;
24 SimpleOpensslSigner::SimpleOpensslSigner() {
27 SimpleOpensslSigner::~SimpleOpensslSigner() {
30 std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial( Profile& prof, std::shared_ptr<CAConfig> ca ) {
31 uint16_t profile = prof.id;
32 std::string res = readFile( ca->path + "/serial" );
39 if( !bn || !BN_hex2bn( &bn, "1" ) ) {
40 throw std::runtime_error( "Initing serial failed" );
43 if( !BN_hex2bn( &bn, res.c_str() ) ) {
44 throw std::runtime_error( "Parsing serial failed." );
48 std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
50 std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char * ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
51 int len = BN_bn2bin( serial.get(), data.get() );
53 data.get()[len] = 0x0;
54 data.get()[len + 1] = 0x0; // signer id
56 data.get()[len + 2] = profile >> 8;
57 data.get()[len + 3] = profile & 0xFF; // profile id
59 if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
60 throw std::runtime_error( "Big number math failed while fetching random data for serial number." );
63 auto freeMem = []( char *ref ) {
66 std::shared_ptr<char> serStr = std::shared_ptr<char>( BN_bn2hex( serial.get() ), freeMem );
68 writeFile( ca->path + "/serial", serStr.get() );
70 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() ) );
73 std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
74 std::stringstream signlog;
75 logger::logger_set log_set_sign( {logger::log_target( signlog, logger::level::debug )}, logger::auto_register::on );
77 logger::note( "FINE: Profile name is: ", cert->profile );
79 Profile& prof = profiles.at( cert->profile );
80 logger::note( "FINE: Profile ID is: ", prof.id );
82 std::shared_ptr<CAConfig> ca = prof.getCA();
85 logger::error( "ERROR: Signing CA specified in profile could not be loaded." );
86 throw std::runtime_error( "CA-key not found" );
90 throw std::runtime_error( "Cannot sign certificate with CA " + ca->name + " because it has no private key." );
93 logger::note( "FINE: Key for Signing CA is correctly loaded." );
95 logger::note( "INFO: Baseline Key Usage is: ", prof.ku );
96 logger::note( "INFO: Extended Key Usage is: ", prof.eku );
98 logger::note( "FINE: Signing is wanted by: ", cert->wishFrom );
99 logger::note( "FINE: Signing is wanted for: ", cert->wishTo );
101 std::shared_ptr<X509Req> req;
103 if( cert->csr_type == "SPKAC" ) {
104 req = X509Req::parseSPKAC( cert->csr_content );
105 } else if( cert->csr_type == "CSR" ) {
106 req = X509Req::parseCSR( cert->csr_content );
108 logger::errorf( "ERROR: Unknown type (\"%s\") of certification in request.", cert->csr_type );
109 throw std::runtime_error( "Error, unknown REQ rype " + cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classe)s
112 int i = req->verify();
115 throw std::runtime_error( "Request contains a Signature with problems ... " );
116 } else if( i == 0 ) {
117 throw std::runtime_error( "Request contains a Signature that does not match ..." );
119 logger::note( "FINE: Request contains valid self-signature." );
122 // Construct the Certificate
123 X509Cert c = X509Cert();
125 logger::note( "INFO: Populating RDN ..." );
127 for( std::shared_ptr<AVA> a : cert->AVAs ) {
128 logger::notef( "INFO: Trying to add RDN: %s: %s", a->name, a->value );
130 if( a->value.empty() ) {
131 logger::notef( "INFO: Removing empty RDN: %s", a->name );
135 if( a->name == "CN" ) {
136 c.addRDN( NID_commonName, a->value );
137 } else if( a->name == "EMAIL" ) {
138 c.addRDN( NID_pkcs9_emailAddress, a->value );
139 } else if( a->name == "C" ) {
140 c.addRDN( NID_countryName, a->value );
141 } else if( a->name == "L" ) {
142 c.addRDN( NID_localityName, a->value );
143 } else if( a->name == "ST" ) {
144 c.addRDN( NID_stateOrProvinceName, a->value );
145 } else if( a->name == "O" ) {
146 c.addRDN( NID_organizationName, a->value );
147 } else if( a->name == "OU" ) {
148 c.addRDN( NID_organizationalUnitName, a->value );
150 logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name );
151 throw std::runtime_error( "Unhandled/Illegal AVA type" );
155 logger::note( "INFO: Populating Issuer ..." );
156 c.setIssuerNameFrom( ca->ca );
158 logger::note( "INFO: Validating Public key for use in certificate" );
159 logger::note( "INFO: - Checking generic key parameters" );
160 logger::note( "FINE: ->Public Key parameters are okay" );
162 logger::note( "INFO: - Checking blacklists" );
163 logger::note( "FINE: ->Does not appear on any blacklist" );
165 logger::note( "INFO: - Checking trivial factorization" );
166 logger::note( "FINE: ->Trivial factorization not possible" );
168 logger::note( "INFO: - Checking astrological signs" );
169 logger::note( "FINE: ->The stars look good for this one" );
170 logger::note( "FINE: Public key is fine for use in certificate" );
172 logger::note( "INFO: Copying Public Key from Request ..." );
173 c.setPubkeyFrom( req );
174 logger::note( "FINE: Public Key successfully copied from Request." );
177 logger::note( "INFO: Determining Validity Period ..." );
178 std::time_t from, to;
179 std::time_t now = time( 0 );
180 std::pair<bool, std::time_t> parsed;
182 if( ( parsed = parseDate( cert->wishFrom ) ).first /* is of yyyy-mm-dd */ ) {
183 if( parsed.second > now ) {
184 from = parsed.second;
192 if( ( ( from - now ) > /* 2 Weeks */ ( 2 * 7 * 24 * 60 * 60 ) ) || ( ( now - from ) >= 0 ) ) {
196 if( ( parsed = parseDate( cert->wishTo ) ).first /*is of yyyy-mm-dd */ ) {
197 if( parsed.second > from ) {
200 to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
202 } else if( ( parsed = parseYearInterval( from, cert->wishTo ) ).first /*is of [0-9]+y */ ) {
204 } else if( ( parsed = parseMonthInterval( from, cert->wishTo ) ).first /*is of [0-9]+m */ ) {
207 to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
210 time_t limit = prof.maxValidity;
212 if( ( to - from > limit ) || ( to - from < 0 ) ) {
216 c.setTimes( from, to );
217 logger::note( "FINE: Setting validity period successful:" );
220 std::vector<char> timebuf;
222 timeobj = gmtime( &from );
223 timebuf.resize( 128 );
224 timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
225 logger::note( "FINE: - Valid not before: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
227 timeobj = gmtime( &to );
228 timebuf.resize( 128 );
229 timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
230 logger::note( "FINE: - Valid not after: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
234 logger::note( "INFO: Setting extensions:" );
235 c.setExtensions( ca->ca, cert->SANs, prof, ca->crlURL, ca->crtURL );
236 logger::note( "FINE: Setting extensions successful." );
238 logger::note( "INFO: Generating next Serial Number ..." );
239 std::shared_ptr<BIGNUM> ser;
241 std::tie( ser, num ) = nextSerial( prof, ca );
242 c.setSerialNumber( ser.get() );
243 logger::note( "FINE: Certificate Serial Number set to: ", num );
246 logger::note( "INFO: Trying to sign Certificate:" );
247 std::shared_ptr<SignedCertificate> output = c.sign( ca->caKey, cert->md );
248 logger::note( "INFO: Writing certificate to local file." );
249 std::string fn = writeBackFile( num, output->certificate, ca->path );
252 logger::error( "ERROR: failed to get filename for storage of signed certificate." );
253 throw std::runtime_error( "Storage location could not be determined" );
256 logger::note( "FINE: Certificate signed successfully." );
257 logger::note( "FINE: - Certificate written to: ", fn );
259 output->ca_name = ca->name;
260 output->log = signlog.str();
265 std::pair<std::shared_ptr<CRL>, std::string> SimpleOpensslSigner::revoke( std::shared_ptr<CAConfig> ca, std::vector<std::string> serials ) {
266 logger::note( "revoking" );
267 std::string crlpath = ca->path + "/ca.crl";
269 auto crl = std::make_shared<CRL>( crlpath );
270 std::string date = "";
272 logger::note( "adding serials" );
274 for( std::string serial : serials ) {
275 date = crl->revoke( serial, "" );
278 logger::note( "signing CRL" );
280 writeFile( crlpath, crl->toString() );
281 logger::note( "wrote CRL" );
282 return std::pair<std::shared_ptr<CRL>, std::string>( crl, date );