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