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