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