]> WPIA git - cassiopeia.git/blob - src/crypto/sslUtil.cpp
506e27fde2209cd7df62b80bc7a0a96d6ed03381
[cassiopeia.git] / src / crypto / sslUtil.cpp
1 #include "sslUtil.h"
2
3 #include <sys/types.h>
4 #include <termios.h>
5 #include <unistd.h>
6
7 #include <iostream>
8
9 #include "crypto/CRL.h"
10 #include "log/logger.hpp"
11
12 std::shared_ptr<int> ssl_lib_ref(
13     new int( SSL_library_init() ),
14     []( int* ref ) {
15         delete ref;
16
17         EVP_cleanup();
18         CRYPTO_cleanup_all_ex_data();
19     } );
20
21 std::shared_ptr<X509> loadX509FromFile( const std::string& filename ) {
22     std::shared_ptr<FILE> f( fopen( filename.c_str(), "r" ), fclose );
23
24     if( !f ) {
25         return std::shared_ptr<X509>();
26     }
27
28     X509 *key = PEM_read_X509( f.get(), NULL, NULL, 0 );
29
30     if( !key ) {
31         return std::shared_ptr<X509>();
32     }
33
34     return std::shared_ptr<X509>(
35         key,
36         []( X509* ref ) {
37             X509_free( ref );
38         } );
39 }
40
41 std::shared_ptr<EVP_PKEY> loadPkeyFromFile( const std::string& filename ) {
42     std::shared_ptr<FILE> f(
43         fopen( filename.c_str(), "r" ),
44         []( FILE* ptr ) {
45             if( ptr ) {
46                 fclose( ptr );
47             }
48         } );
49
50     if( !f ) {
51         return std::shared_ptr<EVP_PKEY>();
52     }
53
54     EVP_PKEY *key = PEM_read_PrivateKey( f.get(), NULL, NULL, 0 );
55
56     if( !key ) {
57         return std::shared_ptr<EVP_PKEY>();
58     }
59
60     return std::shared_ptr<EVP_PKEY>(
61         key,
62         []( EVP_PKEY* ref ) {
63             EVP_PKEY_free( ref );
64         } );
65 }
66
67 int gencb( int a, int b, BN_GENCB *g ) {
68     ( void ) a;
69     ( void ) b;
70     ( void ) g;
71
72     std::cout << ( a == 0 ? "." : "+" ) << std::flush;
73
74     return 1;
75 }
76
77 static int verify_callback( int preverify_ok, X509_STORE_CTX *ctx ) {
78     if( !preverify_ok ) {
79         //auto cert = X509_STORE_CTX_get_current_cert(ctx);
80         //BIO *o = BIO_new_fp(stdout,BIO_NOCLOSE);
81         //X509_print_ex(o, cert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
82         //BIO_free(o);
83
84         logger::errorf( "Verification failed: %s because %s", preverify_ok, X509_STORE_CTX_get_error( ctx ) );
85     }
86
87     return preverify_ok;
88 }
89
90 static std::shared_ptr<DH> dh_param;
91
92 std::shared_ptr<SSL_CTX> generateSSLContext( bool server ) {
93     std::shared_ptr<SSL_CTX> ctx = std::shared_ptr<SSL_CTX>(
94         SSL_CTX_new( TLS_method() ),
95         []( SSL_CTX* p ) {
96             SSL_CTX_free( p );
97         } );
98
99     if( !SSL_CTX_set_cipher_list( ctx.get(), "HIGH:+CAMELLIA256:!eNull:!aNULL:!ADH:!MD5:-RSA+AES+SHA1:!RC4:!DES:!3DES:!SEED:!EXP:!AES128:!CAMELLIA128" ) ) {
100         throw std::runtime_error( "Cannot set cipher list. Your source is broken." );
101     }
102
103     SSL_CTX_set_verify( ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback );
104     SSL_CTX_use_certificate_file( ctx.get(), server ? "keys/signer_server.crt" : "keys/signer_client.crt", SSL_FILETYPE_PEM );
105     SSL_CTX_use_PrivateKey_file( ctx.get(), server ? "keys/signer_server.key" : "keys/signer_client.key", SSL_FILETYPE_PEM );
106
107     if( 1 != SSL_CTX_load_verify_locations( ctx.get(), "keys/ca.crt", 0 ) ) {
108         throw std::runtime_error( "Cannot load CA store for certificate validation." );
109     }
110
111     if( server ) {
112         STACK_OF( X509_NAME ) *names = SSL_load_client_CA_file( "keys/env.crt" );
113
114         if( names ) {
115             SSL_CTX_set_client_CA_list( ctx.get(), names );
116         } else {
117             // error
118         }
119
120         if( !dh_param ) {
121             std::shared_ptr<FILE> paramfile( fopen( "dh_param.pem", "r" ), fclose );
122
123             if( paramfile ) {
124                 dh_param = std::shared_ptr<DH>( PEM_read_DHparams( paramfile.get(), NULL, NULL, NULL ), DH_free );
125             } else {
126                 dh_param = std::shared_ptr<DH>( DH_new(), DH_free );
127                 logger::note( "Generating DH params" );
128                 BN_GENCB *cb = BN_GENCB_new();
129                 BN_GENCB_set( cb, gencb, NULL );
130
131                 if( !DH_generate_parameters_ex( dh_param.get(), 2048, 5, cb ) ) {
132                     throw std::runtime_error( "DH generation failed" );
133                 }
134
135                 BN_GENCB_free( cb );
136
137                 std::cout << std::endl;
138                 paramfile = std::shared_ptr<FILE>( fopen( "dh_param.pem", "w" ), fclose );
139
140                 if( paramfile ) {
141                     PEM_write_DHparams( paramfile.get(), dh_param.get() );
142                 }
143             }
144         }
145
146         if( !SSL_CTX_set_tmp_dh( ctx.get(), dh_param.get() ) ) {
147             throw std::runtime_error( "Cannot set tmp dh." );
148         }
149     }
150
151     return ctx;
152 }
153
154 void setupSerial( std::shared_ptr<FILE> f ) {
155     struct termios attr;
156
157     if( tcgetattr( fileno( f.get() ), &attr ) ) {
158         throw std::runtime_error( "failed to get attrs" );
159     }
160
161     attr.c_iflag &= ~( IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON );
162     attr.c_oflag &= ~OPOST;
163     attr.c_lflag &= ~( ECHO | ECHONL | ICANON | ISIG | IEXTEN );
164     attr.c_cflag &= ~( CSIZE | PARENB );
165     attr.c_cflag |= CS8;
166
167     cfsetispeed( &attr, B115200 );
168     cfsetospeed( &attr, B115200 );
169
170     if( tcsetattr( fileno( f.get() ), TCSANOW, &attr ) ) {
171         throw std::runtime_error( "failed to get attrs" );
172     }
173 }
174
175 std::shared_ptr<BIO> openSerial( const std::string& name ) {
176     std::shared_ptr<FILE> f( fopen( name.c_str(), "r+" ), fclose );
177
178     if( !f ) {
179         logger::error( "Opening serial device failed." );
180         return std::shared_ptr<BIO>();
181     }
182
183     setupSerial( f );
184     return std::shared_ptr<BIO>(
185         BIO_new_fd( fileno( f.get() ), 0 ),
186         [f]( BIO* b ) {
187             BIO_free( b );
188         } );
189 }
190
191 extern std::string crlPrefix;
192 extern std::string crtPrefix;
193
194 CAConfig::CAConfig( const std::string& name ) : path( "ca/" + name ), name( name ) {
195     ca = loadX509FromFile( path + "/ca.crt" );
196
197     if( !ca ) {
198         throw new std::invalid_argument( "ca name: " + name + " contains unreadable certificate." );
199     }
200
201     caKey = loadPkeyFromFile( path + "/ca.key" );
202
203     ASN1_TIME *tm = X509_get_notBefore( ca.get() ); // tm MUST NOT be free'd; duplicate for owning copy.
204     notBefore = std::shared_ptr<ASN1_TIME>( ASN1_STRING_dup( tm ), ASN1_TIME_free );
205
206     std::size_t pos = name.find( "_" );
207
208     if( pos == std::string::npos ) {
209         throw new std::invalid_argument( "ca name: " + name + " is malformed." );
210     }
211
212     std::size_t pos2 = name.find( "_", pos + 1 );
213
214     if( pos2 == std::string::npos ) {
215         throw new std::invalid_argument( "ca name: " + name + " is malformed." );
216     }
217
218     crlURL = crlPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crl";
219     crtURL = crtPrefix + "/g2/" + name.substr( pos + 1, pos2 - pos - 1 ) + "/" + name.substr( 0, pos ) + "-" + name.substr( pos2 + 1 ) + ".crt";
220 }
221
222 std::string timeToString( std::shared_ptr<ASN1_TIME> time ) {
223     std::shared_ptr<ASN1_GENERALIZEDTIME> gtime( ASN1_TIME_to_generalizedtime( time.get(), 0 ), ASN1_GENERALIZEDTIME_free );
224     std::string strdate( ( char * ) ASN1_STRING_get0_data( gtime.get() ), ASN1_STRING_length( gtime.get() ) );
225
226     logger::notef( "openssl formatted me a date: %s", strdate );
227
228     if( strdate[strdate.size() - 1] != 'Z' ) {
229         throw std::runtime_error( "Got invalid date?" );
230     }
231
232     return strdate.substr( 0, strdate.size() - 1 );
233 }
234
235 void extractTimes( std::shared_ptr<X509> target,  std::shared_ptr<SignedCertificate> cert ) {
236     cert->before = timeToString( std::shared_ptr<ASN1_TIME>( X509_get_notBefore( target.get() ), [target]( auto p ) {
237         ( void )p;
238     } ) );
239     cert->after = timeToString( std::shared_ptr<ASN1_TIME>( X509_get_notAfter( target.get() ), [target]( auto p ) {
240         ( void )p;
241     } ) );
242 }
243
244 bool CAConfig::crlNeedsResign() {
245     auto crl = std::make_shared<CRL>( path + "/ca.crl" );
246     return crl->needsResign();
247 }