1 #include "simpleOpensslSigner.h"
4 #include <unordered_map>
6 #include <openssl/ssl.h>
7 #include <openssl/err.h>
8 #include <openssl/bio.h>
9 #include <openssl/bn.h>
10 #include <openssl/engine.h>
11 #include <openssl/x509v3.h>
13 #include "log/logger.hpp"
19 extern std::unordered_map<std::string, Profile> profiles;
21 std::shared_ptr<int> SimpleOpensslSigner::lib_ref = ssl_lib_ref;
23 SimpleOpensslSigner::SimpleOpensslSigner() {
26 SimpleOpensslSigner::~SimpleOpensslSigner() {
29 std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial( Profile& prof, std::shared_ptr<CAConfig> ca ) {
30 uint16_t profile = prof.id;
31 std::string res = readFile( ca->path + "/serial" );
38 if( !bn || !BN_hex2bn( &bn, "1" )) {
39 throw "Initing serial failed";
42 if( !BN_hex2bn( &bn, res.c_str() ) ) {
43 throw "Parsing serial failed.";
47 std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
49 std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char* ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
50 int len = BN_bn2bin( serial.get(), data.get() );
52 data.get()[len] = 0x0;
53 data.get()[len + 1] = 0x0; // signer id
55 data.get()[len + 2] = profile >> 8;
56 data.get()[len + 3] = profile & 0xFF; // profile id
58 if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
59 throw "Big number math failed while fetching random data for serial number.";
62 std::shared_ptr<char> serStr = std::shared_ptr<char>(
63 BN_bn2hex( serial.get() ),
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 "CA-key not found";
89 logger::note( "FINE: Key for Signing CA is correctly loaded." );
91 logger::note( "INFO: Baseline Key Usage is: ", prof.ku );
92 logger::note( "INFO: Extended Key Usage is: ", prof.eku );
94 logger::note( "FINE: Signing is wanted by: ", cert->wishFrom );
95 logger::note( "FINE: Signing is wanted for: ", cert->wishTo );
97 std::shared_ptr<X509Req> req;
99 if( cert->csr_type == "SPKAC" ) {
100 req = X509Req::parseSPKAC( cert->csr_content );
101 } else if( cert->csr_type == "CSR" ) {
102 req = X509Req::parseCSR( cert->csr_content );
104 logger::errorf( "ERROR: Unknown type (\"%s\") of certification in request.", cert->csr_type );
105 throw "Error, unknown REQ rype " + ( cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classes
108 int i = req->verify();
111 throw "Request contains a Signature with problems ... ";
112 } else if( i == 0 ) {
113 throw "Request contains a Signature that does not match ...";
115 logger::note( "FINE: Request contains valid self-signature." );
118 // Construct the Certificate
119 X509Cert c = X509Cert();
121 logger::note( "INFO: Populating RDN ..." );
123 for( std::shared_ptr<AVA> a : cert->AVAs ) {
124 logger::notef( "INFO: Trying to add RDN: %s: %s", a->name, a->value );
126 if( a->name == "CN" ) {
127 c.addRDN( NID_commonName, a->value );
128 } else if( a->name == "EMAIL" ) {
129 c.addRDN( NID_pkcs9_emailAddress, a->value );
130 } else if( a->name == "C" ) {
131 c.addRDN( NID_countryName, a->value );
132 } else if( a->name == "L" ) {
133 c.addRDN( NID_localityName, a->value );
134 } else if( a->name == "ST" ) {
135 c.addRDN( NID_stateOrProvinceName, a->value );
136 } else if( a->name == "O" ) {
137 c.addRDN( NID_organizationName, a->value );
138 } else if( a->name == "OU" ) {
139 c.addRDN( NID_organizationalUnitName, a->value );
141 logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name );
142 throw "Unhandled/Illegal AVA type";
146 logger::note( "INFO: Populating Issuer ..." );
147 c.setIssuerNameFrom( ca->ca );
149 logger::note( "INFO: Validating Public key for use in certificate" );
150 logger::note( "INFO: - Checking generic key parameters" );
151 logger::note( "FINE: ->Public Key parameters are okay" );
153 logger::note( "INFO: - Checking blacklists" );
154 logger::note( "FINE: ->Does not appear on any blacklist" );
156 logger::note( "INFO: - Checking trivial factorization" );
157 logger::note( "FINE: ->Trivial factorization not possible" );
159 logger::note( "INFO: - Checking astrological signs" );
160 logger::note( "FINE: ->The stars look good for this one" );
161 logger::note( "FINE: Public key is fine for use in certificate" );
163 logger::note( "INFO: Copying Public Key from Request ..." );
164 c.setPubkeyFrom( req );
165 logger::note( "FINE: Public Key successfully copied from Request." );
168 logger::note( "INFO: Determining Validity Period ..." );
169 std::time_t from, to;
170 std::time_t now = time( 0 );
171 std::pair<bool, std::time_t> parsed;
173 if( ( parsed = parseDate( cert->wishFrom ) ).first /* is of yyyy-mm-dd */ ) {
174 if( parsed.second > now ) {
175 from = parsed.second;
183 if( ( ( from - now ) > /* 2 Weeks */ ( 2 * 7 * 24 * 60 * 60 ) ) || ( ( now - from ) >= 0 ) ) {
187 if( ( parsed = parseDate( cert->wishTo ) ).first /*is of yyyy-mm-dd */ ) {
188 if( parsed.second > from ) {
191 to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
193 } else if( ( parsed = parseYearInterval( from, cert->wishTo ) ).first /*is of [0-9]+y */ ) {
195 } else if( ( parsed = parseMonthInterval( from, cert->wishTo ) ).first /*is of [0-9]+m */ ) {
198 to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
201 time_t limit = prof.maxValidity;
203 if( ( to - from > limit ) || ( to - from < 0 ) ) {
207 c.setTimes( from, to );
208 logger::note( "FINE: Setting validity period successful:" );
211 std::vector<char> timebuf;
213 timeobj = gmtime( &from );
214 timebuf.resize( 128 );
215 timebuf.resize( std::strftime( const_cast<char*>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
216 logger::note( "FINE: - Valid not before: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
218 timeobj = gmtime( &to );
219 timebuf.resize( 128 );
220 timebuf.resize( std::strftime( const_cast<char*>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
221 logger::note( "FINE: - Valid not after: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
225 logger::note( "INFO: Setting extensions:" );
226 c.setExtensions( ca->ca, cert->SANs, prof, ca->crlURL, ca->crtURL );
227 logger::note( "FINE: Setting extensions successful." );
229 logger::note( "INFO: Generating next Serial Number ..." );
230 std::shared_ptr<BIGNUM> ser;
232 std::tie( ser, num ) = nextSerial( prof, ca );
233 c.setSerialNumber( ser.get() );
234 logger::note( "FINE: Certificate Serial Number set to: ", num );
237 logger::note( "INFO: Trying to sign Certificate:" );
238 std::shared_ptr<SignedCertificate> output = c.sign( ca->caKey, cert->md );
239 logger::note( "INFO: Writing certificate to local file." );
240 std::string fn = writeBackFile( num, output->certificate, ca->path );
243 logger::error( "ERROR: failed to get filename for storage of signed certificate." );
244 throw "Storage location could not be determined";
247 logger::note( "FINE: Certificate signed successfully." );
248 logger::note( "FINE: - Certificate written to: ", fn );
250 output->ca_name = ca->name;
251 output->log = signlog.str();
256 std::pair<std::shared_ptr<CRL>, std::string> SimpleOpensslSigner::revoke( std::shared_ptr<CAConfig> ca, std::vector<std::string> serials ) {
257 logger::note( "revoking" );
258 std::string crlpath = ca->path + "/ca.crl";
260 auto crl = std::make_shared<CRL>( crlpath );
261 std::string date = "";
263 logger::note( "adding serials" );
264 for( std::string serial : serials ) {
265 date = crl->revoke( serial, "" );
268 logger::note( "signing CRL" );
270 writeFile( crlpath, crl->toString() );
271 logger::note( "wrote CRL" );
272 return std::pair<std::shared_ptr<CRL>, std::string>( crl, date );