]> WPIA git - cassiopeia.git/blob - src/crypto/simpleOpensslSigner.cpp
a6d037188fbbf915336db93e305c9a0d71dc165b
[cassiopeia.git] / src / crypto / simpleOpensslSigner.cpp
1 #include "simpleOpensslSigner.h"
2
3 #include <sstream>
4 #include <unordered_map>
5 #include <exception>
6
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>
13
14 #include "log/logger.hpp"
15
16 #include "X509.h"
17 #include "util.h"
18 #include "sslUtil.h"
19
20 extern std::unordered_map<std::string, Profile> profiles;
21 extern std::unordered_map<std::string, std::shared_ptr<CAConfig>> CAs;
22
23 std::shared_ptr<int> SimpleOpensslSigner::lib_ref = ssl_lib_ref;
24
25 SimpleOpensslSigner::SimpleOpensslSigner() {
26 }
27
28 SimpleOpensslSigner::~SimpleOpensslSigner() {
29 }
30
31 std::pair<std::shared_ptr<BIGNUM>, std::string> SimpleOpensslSigner::nextSerial( Profile& prof, std::shared_ptr<CAConfig> ca ) {
32     uint16_t profile = prof.id;
33     std::string res = readFile( ca->path + "/serial" );
34
35     BIGNUM *bn = 0;
36
37     if( res == "" ) {
38         bn = BN_new();
39
40         if( !bn || !BN_hex2bn( &bn, "1" ) ) {
41             throw std::runtime_error( "Initing serial failed" );
42         }
43     } else {
44         if( !BN_hex2bn( &bn, res.c_str() ) ) {
45             throw std::runtime_error( "Parsing serial failed." );
46         }
47     }
48
49     std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
50
51     std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char * ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
52     int len = BN_bn2bin( serial.get(), data.get() );
53
54     data.get()[len] = 0x0;
55     data.get()[len + 1] = 0x0; // signer id
56
57     data.get()[len + 2] = profile >> 8;
58     data.get()[len + 3] = profile & 0xFF; // profile id
59
60     if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
61         throw std::runtime_error( "Big number math failed while fetching random data for serial number." );
62     }
63
64     auto freeMem = []( char *ref ) {
65         OPENSSL_free( ref );
66     };
67     std::shared_ptr<char> serStr = std::shared_ptr<char>( BN_bn2hex( serial.get() ), freeMem );
68
69     writeFile( ca->path + "/serial", serStr.get() );
70
71     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() ) );
72 }
73
74 std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
75     std::stringstream signlog;
76     logger::logger_set log_set_sign( {logger::log_target( signlog, logger::level::debug )}, logger::auto_register::on );
77
78     std::shared_ptr<CAConfig> ca;
79     Profile *prof;
80
81     if( cert->ocspCA != "" ) {
82         auto caIterator = CAs.find( cert->ocspCA );
83
84         if( caIterator == CAs.end() ) {
85             logger::error( "ERROR: Signing CA specified in request for an OCSP cert could not be loaded." );
86             throw std::runtime_error( "CA-key for OCSP cert not found" );
87         }
88
89         ca = caIterator->second;
90         logger::note( "Trying to fetch OCSP-profile" );
91         prof = &profiles.at( "0100-ocsp" );
92         logger::note( "Done with it" );
93     } else {
94         logger::note( "FINE: Profile name is: ", cert->profile );
95
96         prof = &profiles.at( cert->profile );
97         logger::note( "FINE: Profile ID is: ", prof->id );
98         ca = prof->getCA();
99     }
100
101     if( !ca ) {
102         logger::error( "ERROR: Signing CA specified in profile could not be loaded." );
103         throw std::runtime_error( "CA-key not found" );
104     }
105
106     if( !ca->caKey ) {
107         throw std::runtime_error( "Cannot sign certificate with CA " + ca->name + " because it has no private key." );
108     }
109
110     logger::note( "FINE: Key for Signing CA is correctly loaded." );
111
112     logger::note( "INFO: Baseline Key Usage is: ", prof->ku );
113     logger::note( "INFO: Extended Key Usage is: ", prof->eku );
114
115     logger::note( "FINE: Signing is wanted by: ", cert->wishFrom );
116     logger::note( "FINE: Signing is wanted for: ", cert->wishTo );
117
118     std::shared_ptr<X509Req> req;
119
120     if( cert->csr_type == "SPKAC" ) {
121         req = X509Req::parseSPKAC( cert->csr_content );
122     } else if( cert->csr_type == "CSR" ) {
123         req = X509Req::parseCSR( cert->csr_content );
124     } else {
125         logger::errorf( "ERROR: Unknown type (\"%s\") of certification in request.", cert->csr_type );
126         throw std::runtime_error( "Error, unknown REQ rype " + cert->csr_type ); //! \fixme: Pointer instead of string, please use proper exception classe)s
127     }
128
129     int i = req->verify();
130
131     if( i < 0 ) {
132         throw std::runtime_error( "Request contains a Signature with problems ... " );
133     } else if( i == 0 ) {
134         throw std::runtime_error( "Request contains a Signature that does not match ..." );
135     } else {
136         logger::note( "FINE: Request contains valid self-signature." );
137     }
138
139     // Construct the Certificate
140     X509Cert c = X509Cert();
141
142     logger::note( "INFO: Populating RDN ..." );
143
144     for( std::shared_ptr<AVA> a : cert->AVAs ) {
145         logger::notef( "INFO: Trying to add RDN: %s: %s", a->name, a->value );
146
147         if( a->value.empty() ) {
148             logger::notef( "INFO: Removing empty RDN: %s", a->name );
149             continue;
150         }
151
152         if( a->name == "CN" ) {
153             c.addRDN( NID_commonName, a->value );
154         } else if( a->name == "EMAIL" ) {
155             c.addRDN( NID_pkcs9_emailAddress, a->value );
156         } else if( a->name == "C" ) {
157             c.addRDN( NID_countryName, a->value );
158         } else if( a->name == "L" ) {
159             c.addRDN( NID_localityName, a->value );
160         } else if( a->name == "ST" ) {
161             c.addRDN( NID_stateOrProvinceName, a->value );
162         } else if( a->name == "O" ) {
163             c.addRDN( NID_organizationName, a->value );
164         } else if( a->name == "OU" ) {
165             c.addRDN( NID_organizationalUnitName, a->value );
166         } else {
167             logger::error( "ERROR: Trying to add illegal RDN/AVA type: ", a->name );
168             throw std::runtime_error( "Unhandled/Illegal AVA type" );
169         }
170     }
171
172     logger::note( "INFO: Populating Issuer ..." );
173     c.setIssuerNameFrom( ca->ca );
174
175     logger::note( "INFO: Validating Public key for use in certificate" );
176     logger::note( "INFO: - Checking generic key parameters" );
177     logger::note( "FINE:   ->Public Key parameters are okay" );
178
179     logger::note( "INFO: - Checking blacklists" );
180     logger::note( "FINE:   ->Does not appear on any blacklist" );
181
182     logger::note( "INFO: - Checking trivial factorization" );
183     logger::note( "FINE:   ->Trivial factorization not possible" );
184
185     logger::note( "INFO: - Checking astrological signs" );
186     logger::note( "FINE:   ->The stars look good for this one" );
187     logger::note( "FINE: Public key is fine for use in certificate" );
188
189     logger::note( "INFO: Copying Public Key from Request ..." );
190     c.setPubkeyFrom( req );
191     logger::note( "FINE: Public Key successfully copied from Request." );
192
193     {
194         logger::note( "INFO: Determining Validity Period ..." );
195         std::time_t from, to;
196         std::time_t now = time( 0 );
197         std::pair<bool, std::time_t> parsed;
198
199         if( ( parsed = parseDate( cert->wishFrom ) ).first /* is of yyyy-mm-dd */ ) {
200             if( parsed.second > now ) {
201                 from = parsed.second;
202             } else { // fail
203                 from = now;
204             }
205         } else {
206             from = now;
207         }
208
209         if( ( ( from - now ) > /* 2 Weeks */ ( 2 * 7 * 24 * 60 * 60 ) ) || ( ( now - from ) >= 0 ) ) {
210             from = now;
211         }
212
213         if( ( parsed = parseDate( cert->wishTo ) ).first /*is of yyyy-mm-dd */ ) {
214             if( parsed.second > from ) {
215                 to = parsed.second;
216             } else {
217                 to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
218             }
219         } else if( ( parsed = parseYearInterval( from, cert->wishTo ) ).first /*is of [0-9]+y */ ) {
220             to = parsed.second;
221         } else if( ( parsed = parseMonthInterval( from, cert->wishTo ) ).first /*is of [0-9]+m */ ) {
222             to = parsed.second;
223         } else {
224             to = from + /*2 Years */ 2 * 365 * 24 * 60 * 60;
225         }
226
227         time_t limit = prof->maxValidity;
228
229         if( ( to - from > limit ) || ( to - from < 0 ) ) {
230             to = from + limit;
231         }
232
233         c.setTimes( from, to );
234         logger::note( "FINE: Setting validity period successful:" );
235         {
236             struct tm *timeobj;
237             std::vector<char> timebuf;
238
239             timeobj = gmtime( &from );
240             timebuf.resize( 128 );
241             timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
242             logger::note( "FINE: - Valid not before: ", std::string( timebuf.cbegin(), timebuf.cend() ) );
243
244             timeobj = gmtime( &to );
245             timebuf.resize( 128 );
246             timebuf.resize( std::strftime( const_cast<char *>( timebuf.data() ), timebuf.size(), "%F %T %Z", timeobj ) );
247             logger::note( "FINE: - Valid not after:  ", std::string( timebuf.cbegin(), timebuf.cend() ) );
248         }
249     }
250
251     logger::note( "INFO: Setting extensions:" );
252     c.setExtensions( ca->ca, cert->SANs, *prof, ca->crlURL, ca->crtURL );
253     logger::note( "FINE: Setting extensions successful." );
254
255     logger::note( "INFO: Generating next Serial Number ..." );
256     std::shared_ptr<BIGNUM> ser;
257     std::string num;
258     std::tie( ser, num ) = nextSerial( *prof, ca );
259     c.setSerialNumber( ser.get() );
260     logger::note( "FINE: Certificate Serial Number set to: ", num );
261
262     {
263         logger::note( "INFO: Trying to sign Certificate:" );
264         std::shared_ptr<SignedCertificate> output = c.sign( ca->caKey, cert->md );
265         logger::note( "INFO: Writing certificate to local file." );
266         std::string fn = writeBackFile( num, output->certificate, ca->path );
267
268         if( fn.empty() ) {
269             logger::error( "ERROR: failed to get filename for storage of signed certificate." );
270             throw std::runtime_error( "Storage location could not be determined" );
271         }
272
273         logger::note( "FINE: Certificate signed successfully." );
274         logger::note( "FINE: - Certificate written to: ", fn );
275
276         output->ca_name = ca->name;
277         output->log = signlog.str();
278         return output;
279     }
280 }
281
282 std::pair<std::shared_ptr<CRL>, std::string> SimpleOpensslSigner::revoke( std::shared_ptr<CAConfig> ca, std::vector<std::string> serials ) {
283     logger::note( "revoking" );
284     std::string crlpath = ca->path + "/ca.crl";
285
286     auto crl = std::make_shared<CRL>( crlpath );
287     std::string date = "";
288
289     logger::note( "adding serials" );
290
291     for( std::string serial : serials ) {
292         date = crl->revoke( serial, "" );
293     }
294
295     logger::note( "signing CRL" );
296     crl->sign( ca );
297     writeFile( crlpath, crl->toString() );
298     logger::note( "wrote CRL" );
299     return std::pair<std::shared_ptr<CRL>, std::string>( crl, date );
300 }