]> WPIA git - cassiopeia.git/blob - src/crypto/remoteSigner.cpp
c06af91bc3a48700300c6cd89fdb774d1e1289cb
[cassiopeia.git] / src / crypto / remoteSigner.cpp
1 #include "remoteSigner.h"
2
3 #include "log/logger.hpp"
4 #include "util.h"
5
6 #include <iostream>
7
8 #include <openssl/ssl.h>
9 #include <openssl/bn.h>
10
11 RemoteSigner::RemoteSigner( std::shared_ptr<BIO> target, std::shared_ptr<SSL_CTX> ctx ) : target( target ), ctx( ctx ) {
12 }
13
14 RemoteSigner::~RemoteSigner() {
15 }
16
17 void RemoteSigner::send( std::shared_ptr<OpensslBIOWrapper> bio, RecordHeader& head, RecordHeader::SignerCommand cmd, std::string data ) {
18     head.command = static_cast<uint16_t>( cmd );
19     head.command_count++;
20     head.totalLength = data.size();
21     sendCommand( head, data, bio );
22 }
23
24 std::shared_ptr<SignedCertificate> RemoteSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
25     ( void )BIO_reset( target.get() );
26
27     std::shared_ptr<SSL> ssl( SSL_new( ctx.get() ), SSL_free );
28     std::shared_ptr<BIO> bio( BIO_new( BIO_f_ssl() ), BIO_free );
29     SSL_set_connect_state( ssl.get() );
30     SSL_set_bio( ssl.get(), target.get(), target.get() );
31     BIO_set_ssl( bio.get(), ssl.get(), BIO_NOCLOSE );
32     auto conn = std::make_shared<OpensslBIOWrapper>( bio );
33     RecordHeader head;
34     head.flags = 0;
35     head.sessid = 13;
36
37     if( cert->csr_type == "CSR" ) {
38         send( conn, head, RecordHeader::SignerCommand::SET_CSR, cert->csr_content );
39     } else if( cert->csr_type == "SPKAC" ) {
40         send( conn, head, RecordHeader::SignerCommand::SET_SPKAC, cert->csr_content );
41     } else {
42         logger::error( "Unknown csr_type: ", cert->csr_type );
43         return nullptr;
44     }
45
46     send( conn, head, RecordHeader::SignerCommand::SET_SIGNATURE_TYPE, cert->md );
47
48     if( !cert->ocspCA.empty() ) {
49         send( conn, head, RecordHeader::SignerCommand::SET_OCSP_TARGET_CA, cert->ocspCA );
50     } else {
51         send( conn, head, RecordHeader::SignerCommand::SET_PROFILE, cert->profile );
52     }
53
54     send( conn, head, RecordHeader::SignerCommand::SET_WISH_FROM, cert->wishFrom );
55     send( conn, head, RecordHeader::SignerCommand::SET_WISH_TO, cert->wishTo );
56
57     for( auto& ava : cert->AVAs ) {
58         if( ava->name.find( "," ) != std::string::npos ) {
59             // invalid ava
60             return nullptr;
61         }
62
63         send( conn, head, RecordHeader::SignerCommand::ADD_AVA, ava->name + "," + ava->value );
64     }
65
66     for( auto& san : cert->SANs ) {
67         if( san->type.find( "," ) != std::string::npos ) {
68             // invalid ava
69             return nullptr;
70         }
71
72         send( conn, head, RecordHeader::SignerCommand::ADD_SAN, san->type + "," + san->content );
73     }
74
75     send( conn, head, RecordHeader::SignerCommand::SIGN, "" );
76     send( conn, head, RecordHeader::SignerCommand::LOG_SAVED, "" );
77     auto result = std::make_shared<SignedCertificate>();
78
79     for( int i = 0; i < 3; i++ ) {
80         try {
81             RecordHeader head;
82             std::string payload = parseCommandChunked( head, conn );
83
84             switch( static_cast<RecordHeader::SignerResult>( head.command ) ) {
85             case RecordHeader::SignerResult::CERTIFICATE:
86                 result->certificate = payload;
87                 break;
88
89             case RecordHeader::SignerResult::SAVE_LOG:
90                 result->log = payload;
91                 break;
92
93             case RecordHeader::SignerResult::SIGNING_CA:
94                 result->ca_name = payload;
95                 break;
96
97             default:
98                 logger::error( "Invalid Message" );
99                 break;
100             }
101         } catch( const std::exception& msg ) {
102             logger::error( msg.what() );
103             return std::shared_ptr<SignedCertificate>();
104         }
105     }
106
107     if( result ) {
108         std::shared_ptr<BIO> bios( BIO_new( BIO_s_mem() ), BIO_free );
109         const char *buf = result->certificate.data();
110         unsigned int len = result->certificate.size();
111
112         while( len > 0 ) {
113             int dlen = BIO_write( bios.get(), buf, len );
114
115             if( dlen <= 0 ) {
116                 throw std::runtime_error( "Memory error." );
117             }
118
119             len -= dlen;
120             buf += dlen;
121         }
122
123         std::shared_ptr<X509> pem( PEM_read_bio_X509( bios.get(), NULL, 0, NULL ), X509_free );
124
125         if( !pem ) {
126             throw std::runtime_error( "Pem was not readable" );
127         }
128
129         std::shared_ptr<BIGNUM> ser( ASN1_INTEGER_to_BN( X509_get_serialNumber( pem.get() ), NULL ), BN_free );
130         auto freeMem = []( char *p ) {
131             OPENSSL_free( p );
132         }; // OPENSSL_free is a macro...
133         std::shared_ptr<char> serStr( BN_bn2hex( ser.get() ), freeMem );
134
135         extractTimes( pem, result );
136
137         result->serial = std::string( serStr.get() );
138     }
139
140     logger::note( "Closing SSL connection" );
141
142     if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { // need to close the connection twice
143         logger::warn( "SSL shutdown failed" );
144     }
145
146     logger::note( "SSL connection closed" );
147
148     return result;
149 }
150
151 std::pair<std::shared_ptr<CRL>, std::string> RemoteSigner::revoke( std::shared_ptr<CAConfig> ca, std::vector<std::string> serials ) {
152     ( void )BIO_reset( target.get() );
153
154     std::shared_ptr<SSL> ssl( SSL_new( ctx.get() ), SSL_free );
155     std::shared_ptr<BIO> bio( BIO_new( BIO_f_ssl() ), BIO_free );
156     SSL_set_connect_state( ssl.get() );
157     SSL_set_bio( ssl.get(), target.get(), target.get() );
158     BIO_set_ssl( bio.get(), ssl.get(), BIO_NOCLOSE );
159     auto conn = std::make_shared<OpensslBIOWrapper>( bio );
160
161     RecordHeader head;
162     head.flags = 0;
163     head.sessid = 13;
164
165     for( auto& serial : serials ) {
166         send( conn, head, RecordHeader::SignerCommand::ADD_SERIAL, serial );
167     }
168
169     std::string payload = ca->name;
170     send( conn, head, RecordHeader::SignerCommand::REVOKE, payload );
171
172     payload = parseCommandChunked( head, conn );
173
174     std::string tgtName = ca->path + std::string( "/ca.crl" );
175     auto crl = std::make_shared<CRL>( tgtName );
176     std::string date;
177
178     if( static_cast<RecordHeader::SignerResult>( head.command ) != RecordHeader::SignerResult::REVOKED ) {
179         throw std::runtime_error( "Protocol violation" );
180     }
181
182     const unsigned char *buffer2 = reinterpret_cast<const unsigned char *>( payload.data() );
183     const unsigned char *pos = buffer2;
184     ASN1_TIME *time = d2i_ASN1_TIME( NULL, &pos, payload.size() );
185     ASN1_TIME_free( time );
186     date = payload.substr( 0, pos - buffer2 );
187     std::string rest = payload.substr( pos - buffer2 );
188
189     for( std::string& serial : serials ) {
190         crl->revoke( serial, date );
191     }
192
193     crl->setSignature( rest );
194     bool ok = crl->verify( ca );
195
196     if( ok ) {
197         logger::note( "CRL verificated successfully" );
198         writeFile( tgtName, crl->toString() );
199     } else {
200         logger::warn( "CRL is broken, trying to recover" );
201         send( conn, head, RecordHeader::SignerCommand::GET_FULL_CRL, ca->name );
202
203         payload = parseCommandChunked( head, conn );
204
205         if( static_cast<RecordHeader::SignerResult>( head.command ) != RecordHeader::SignerResult::FULL_CRL ) {
206             throw std::runtime_error( "Protocol violation" );
207         }
208
209         std::string name_bak = ca->path + std::string( "/ca.crl.bak" );
210         writeFile( name_bak, payload );
211         crl = std::make_shared<CRL>( name_bak );
212
213         if( crl->verify( ca ) ) {
214             if( rename( name_bak.c_str(), tgtName.c_str() ) != 0 ) {
215                 logger::warn( "Moving new CRL over old CRL failed" );
216             }
217
218             logger::note( "CRL is now valid again" );
219         } else {
220             logger::warn( "CRL is still broken... Please, help me" );
221         }
222     }
223
224     logger::note( "Closing SSL connection" );
225
226     if( !SSL_shutdown( ssl.get() ) && !SSL_shutdown( ssl.get() ) ) { // need to close the connection twice
227         logger::warn( "SSL shutdown failed" );
228     }
229
230     logger::note( "SSL connection closed" );
231
232     return { crl, date };
233 }
234
235 void RemoteSigner::setLog( std::shared_ptr<std::ostream> target ) {
236     this->log = target;
237 }