]> WPIA git - cassiopeia.git/blob - src/recordHandler.cpp
add: sample communication over serial line
[cassiopeia.git] / src / recordHandler.cpp
1 #include "recordHandler.h"
2
3 #include <termios.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 #include <iostream>
11
12 #include <openssl/ssl.h>
13
14 #include "database.h"
15 #include "record.h"
16 #include "opensslBIO.h"
17 #include "simpleOpensslSigner.h"
18 #include "slipBio.h"
19
20 class RecordHandlerSession {
21 public:
22     uint32_t sessid;
23     uint32_t lastCommandCount;
24
25     std::shared_ptr<TBSCertificate> tbs;
26     std::shared_ptr<SignedCertificate> result;
27
28     SSL* ssl;
29
30     std::shared_ptr<OpensslBIOWrapper> io;
31     DefaultRecordHandler* parent;
32     std::shared_ptr<Signer> signer;
33
34     RecordHandlerSession( DefaultRecordHandler* parent, std::shared_ptr<Signer> signer, std::shared_ptr<SSL_CTX> ctx, BIO* output ) :
35         tbs( new TBSCertificate() ) {
36         this->parent = parent;
37         this->signer = signer;
38
39         ssl = SSL_new( ctx.get() );
40         BIO* bio = output;//BIO_new( BIO_f_ssl() );
41         //SSL_set_accept_state( ssl );
42         //SSL_set_bio( ssl, output, output );
43         //BIO_set_ssl( bio, ssl, BIO_NOCLOSE );
44         io = std::shared_ptr<OpensslBIOWrapper>( new OpensslBIOWrapper( bio ) );
45     }
46
47     void respondCommand( RecordHeader::SignerResult res, std::string payload ) {
48         RecordHeader rh;
49         rh.command = ( uint16_t ) res;
50         rh.flags = 0;
51         rh.command_count = 0; // TODO i++
52         rh.totalLength = payload.size();
53         sendCommand( rh, payload, io );
54     }
55
56     void work() {
57         std::vector<char> buffer( 2048, 0 );
58         int res = io->read( buffer.data(), buffer.capacity() );
59
60         if( res <= 0 ) {
61             parent->reset();
62             return;
63         }
64
65         std::string content( buffer.data(), res );
66
67         try {
68             RecordHeader head;
69             std::string payload = parseCommand( head, content );
70             execute( head, payload );
71         } catch( const char* msg ) {
72             std::cout << msg << std::endl;
73             parent->reset();
74             return;
75         }
76     }
77
78     void execute( RecordHeader& head, std::string data ) {
79         if( head.totalLength != head.payloadLength || head.offset != 0 ) {
80             throw "Error, chunking not supported yet";
81         }
82
83         switch( ( RecordHeader::SignerCommand ) head.command ) {
84         case RecordHeader::SignerCommand::SET_CSR: // setCSR
85             tbs->csr_content = data;
86             tbs->csr_type = "CSR";
87             std::cout << "CSR read" << std::endl;
88             break;
89
90         case RecordHeader::SignerCommand::SET_SIGNATURE_TYPE:
91             tbs->md = "sha256"; // TODO use content ;-)
92             break;
93
94         case RecordHeader::SignerCommand::SET_PROFILE:
95             // TODO
96             tbs->profile = data;
97             break;
98
99         case RecordHeader::SignerCommand::ADD_SAN: {
100             size_t pos = data.find( "," );
101
102             if( pos == std::string::npos ) {
103             } else {
104                 std::shared_ptr<SAN> san( new SAN() );
105                 san->type = data.substr( 0, pos );
106                 san->content = data.substr( pos + 1 );
107                 tbs->SANs.push_back( san );
108             }
109         }
110         break;
111
112         case RecordHeader::SignerCommand::ADD_AVA: {
113             size_t pos = data.find( "," );
114
115             if( pos == std::string::npos ) {
116                 // error
117             } else {
118                 std::shared_ptr<AVA> ava( new AVA() );
119                 ava->name = data.substr( 0, pos );
120                 ava->value = data.substr( pos + 1 );
121                 tbs->AVAs.push_back( ava );
122             }
123         }
124         break;
125
126         case RecordHeader::SignerCommand::ADD_PROOF_LINE:
127             break;
128
129         case RecordHeader::SignerCommand::SIGN:
130             result = signer->sign( tbs );
131             std::cout << "res: " << result->certificate << std::endl;
132             result->log = "I am a dummy log.\nI signed that thing ;-) \n";
133             respondCommand( RecordHeader::SignerResult::SAVE_LOG, result->log );
134             break;
135
136         case RecordHeader::SignerCommand::LOG_SAVED:
137             if( result ) {
138                 respondCommand( RecordHeader::SignerResult::CERTIFICATE, result->certificate );
139             }
140
141             break;
142
143         default:
144             throw "Unimplemented";
145         }
146     }
147 };
148
149 DefaultRecordHandler::DefaultRecordHandler( std::shared_ptr<Signer> signer, BIO* bio ) :
150     currentSession() {
151
152     this->signer = signer;
153
154     ctx = std::shared_ptr<SSL_CTX>( SSL_CTX_new( TLSv1_method() ), SSL_CTX_free );
155     SSL_CTX_use_certificate_file( ctx.get(), "testdata/server.crt", SSL_FILETYPE_PEM );
156     SSL_CTX_use_PrivateKey_file( ctx.get(), "testdata/server.key", SSL_FILETYPE_PEM );
157
158     this->bio = bio;
159 }
160
161 void DefaultRecordHandler::reset() {
162     currentSession = std::shared_ptr<RecordHandlerSession>();
163 }
164
165 void DefaultRecordHandler::handle() {
166     if( !currentSession ) {
167         std::cout << "session allocated" << std::endl;
168         currentSession = std::shared_ptr<RecordHandlerSession>( new RecordHandlerSession( this, signer, ctx, bio ) );
169     }
170
171     currentSession->work();
172 }
173
174 int count = 0;
175 void send( std::shared_ptr<OpensslBIOWrapper> bio, RecordHeader& head, RecordHeader::SignerCommand cmd, std::string data ) {
176     head.command = ( uint16_t ) cmd;
177     head.command_count++;
178     head.totalLength = data.size();
179     sendCommand( head, data, bio );
180 }
181
182 void setupSerial( FILE* f ) {
183     struct termios attr;
184
185     if( tcgetattr( fileno( f ), &attr ) ) {
186         throw "failed to get attrs";
187     }
188
189     attr.c_iflag &= ~( IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON );
190     attr.c_oflag &= ~OPOST;
191     attr.c_lflag &= ~( ECHO | ECHONL | ICANON | ISIG | IEXTEN );
192     attr.c_cflag &= ~( CSIZE | PARENB );
193     attr.c_cflag |= CS8;
194
195     if( tcsetattr( fileno( f ), TCSANOW, &attr ) ) {
196         throw "failed to get attrs";
197     }
198 }
199
200 int handlermain( int argc, const char* argv[] ) {
201     ( void ) argc;
202     ( void ) argv;
203     std::shared_ptr<OpensslBIOWrapper> bio( new OpensslBIOWrapper( BIO_new_fd( 0, 0 ) ) );
204     std::string data =
205         "-----BEGIN CERTIFICATE REQUEST-----\n"
206         "MIIBSzCBtQIBADAMMQowCAYDVQQDDAFhMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n"
207         "iQKBgQDerBEpIShJlx3zzl4AOS1NcwEg4iAWknQeTtI8B5dnk+l5HkOdTxqeehZn\n"
208         "iZnuIuYXA+JWmoECg/w69+N5zw2BabelgK3cSvRqycwPEU/gceGJZTaBfkkN0hBk\n"
209         "rpXDiLSlox5oeR150MrsHvVc+W2e+0jW1tuhz4QLzn8/uI/toQIDAQABoAAwDQYJ\n"
210         "KoZIhvcNAQELBQADgYEATQU5VrgQAkvpCvIwRUyjj9YAa9E014tNY0jMcBdv95fy\n"
211         "/f49zIcVtUJuZuEwY6uDZQqfAm+8CLNpOCICH/Qw7YOe+s/Yw7a8rk5VqLtgxR4M\n"
212         "z6DUeVL0zYFoLUxIje9yDU3pWmPvyVaBPdo0DguZwFMfiWwzhkUDeQgyeaiMvQA=\n"
213         "-----END CERTIFICATE REQUEST-----";
214     RecordHeader head;
215     head.flags = 0;
216     head.sessid = 13;
217
218     //---
219
220     SSL_library_init();
221
222     if( argc >= 2 ) {
223         FILE* f = fopen( "/dev/ttyUSB0", "r+" );
224
225         if( !f ) {
226             std::cout << "Opening /dev/ttyUSB0 bio failed" << std::endl;
227             return -1;
228         }
229
230         setupSerial( f );
231
232         BIO* b = BIO_new_fd( fileno( f ), 0 );
233         BIO* slip1 = BIO_new( toBio<SlipBIO>() );
234         ( ( SlipBIO* )slip1->ptr )->setTarget( std::shared_ptr<OpensslBIO>( new OpensslBIOWrapper( b ) ) );
235         std::shared_ptr<OpensslBIOWrapper> conn( new OpensslBIOWrapper( slip1 ) );
236         send( conn, head, RecordHeader::SignerCommand::SET_CSR, data );
237         send( conn, head, RecordHeader::SignerCommand::SET_SIGNATURE_TYPE, "sha256" );
238         send( conn, head, RecordHeader::SignerCommand::SET_PROFILE, "1" );
239         send( conn, head, RecordHeader::SignerCommand::ADD_AVA, "CN,commonName" );
240         send( conn, head, RecordHeader::SignerCommand::ADD_SAN, "DNS,*.example.com" );
241         send( conn, head, RecordHeader::SignerCommand::SIGN, "" );
242         send( conn, head, RecordHeader::SignerCommand::LOG_SAVED, "" );
243         std::vector<char> buffer( 2048 * 4 );
244
245         for( int i = 0; i < 2; i++ ) {
246             try {
247                 int length = BIO_read( slip1, buffer.data(), buffer.size() );
248                 RecordHeader head;
249                 std::string payload = parseCommand( head, std::string( buffer.data(), length ) );
250                 std::cout << "Data: " << std::endl << payload << std::endl;
251             } catch( const char* msg ) {
252                 std::cout << msg << std::endl;
253                 return -1;
254             }
255         }
256
257         std::cout << "sent things" << std::endl;
258
259         return 0;
260     }
261
262     FILE* f = fopen( "/dev/ttyS0", "r+" );
263
264     if( !f ) {
265         std::cout << "Opening /dev/ttyS0 bio failed" << std::endl;
266         return -1;
267     }
268
269     setupSerial( f );
270
271     BIO* conn =  BIO_new_fd( fileno( f ), 0 );
272     BIO* slip1 = BIO_new( toBio<SlipBIO>() );
273     ( ( SlipBIO* )slip1->ptr )->setTarget( std::shared_ptr<OpensslBIO>( new OpensslBIOWrapper( conn ) ) );
274     DefaultRecordHandler* dh = new DefaultRecordHandler( std::shared_ptr<Signer>( new SimpleOpensslSigner() ), slip1 );
275
276     try {
277         while( true ) {
278             dh->handle();
279         }
280     } catch( char const* ch ) {
281         std::cout << "Exception: " << ch << std::endl;
282     }
283
284     return 0;
285 }