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