/
ssl_connection.v
584 lines (513 loc) · 15.2 KB
/
ssl_connection.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
module mbedtls
import io
import net
import time
const ctr_drbg = C.mbedtls_ctr_drbg_context{}
const entropy = C.mbedtls_entropy_context{}
fn init() {
$if trace_ssl ? {
eprintln(@METHOD)
}
unsafe { // Unsafe is needed for taking an address of const
C.mbedtls_ctr_drbg_init(&mbedtls.ctr_drbg)
C.mbedtls_entropy_init(&mbedtls.entropy)
ret := C.mbedtls_ctr_drbg_seed(&mbedtls.ctr_drbg, C.mbedtls_entropy_func, &mbedtls.entropy,
0, 0)
if ret != 0 {
C.mbedtls_ctr_drbg_free(&mbedtls.ctr_drbg)
panic('Failed to seed ssl context: ${ret}')
}
}
}
struct SSLCerts {
cacert C.mbedtls_x509_crt
client_cert C.mbedtls_x509_crt
client_key C.mbedtls_pk_context
}
// SSLConn is the current connection
pub struct SSLConn {
config SSLConnectConfig
mut:
server_fd C.mbedtls_net_context
ssl C.mbedtls_ssl_context
conf C.mbedtls_ssl_config
certs &SSLCerts = unsafe { nil }
handle int
duration time.Duration
opened bool
owns_socket bool
}
// SSLListener listens on a TCP port and accepts connection secured with TLS
pub struct SSLListener {
saddr string
config SSLConnectConfig
mut:
server_fd C.mbedtls_net_context
ssl C.mbedtls_ssl_context
conf C.mbedtls_ssl_config
certs &SSLCerts = unsafe { nil }
opened bool
// handle int
// duration time.Duration
}
// create a new SSLListener binding to `saddr`
pub fn new_ssl_listener(saddr string, config SSLConnectConfig) !&SSLListener {
mut listener := &SSLListener{
saddr: saddr
config: config
}
listener.init()!
listener.opened = true
return listener
}
// finish the listener and clean up resources
pub fn (mut l SSLListener) shutdown() ! {
$if trace_ssl ? {
eprintln(@METHOD)
}
if unsafe { l.certs != nil } {
C.mbedtls_x509_crt_free(&l.certs.cacert)
C.mbedtls_x509_crt_free(&l.certs.client_cert)
C.mbedtls_pk_free(&l.certs.client_key)
}
C.mbedtls_ssl_free(&l.ssl)
C.mbedtls_ssl_config_free(&l.conf)
if l.opened {
C.mbedtls_net_free(&l.server_fd)
}
}
// internal function to init and bind the listener
fn (mut l SSLListener) init() ! {
$if trace_ssl ? {
eprintln(@METHOD)
}
lhost, lport := net.split_address(l.saddr)!
if l.config.cert == '' || l.config.cert_key == '' {
return error('No certificate or key provided')
}
if l.config.validate && l.config.verify == '' {
return error('No root CA provided')
}
C.mbedtls_net_init(&l.server_fd)
C.mbedtls_ssl_init(&l.ssl)
C.mbedtls_ssl_config_init(&l.conf)
l.certs = &SSLCerts{}
C.mbedtls_x509_crt_init(&l.certs.client_cert)
C.mbedtls_pk_init(&l.certs.client_key)
unsafe {
C.mbedtls_ssl_conf_rng(&l.conf, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
mut ret := 0
if l.config.in_memory_verification {
if l.config.verify != '' {
ret = C.mbedtls_x509_crt_parse(&l.certs.cacert, l.config.verify.str,
l.config.verify.len + 1)
}
if l.config.cert != '' {
ret = C.mbedtls_x509_crt_parse(&l.certs.client_cert, l.config.cert.str,
l.config.cert.len + 1)
}
if l.config.cert_key != '' {
unsafe {
ret = C.mbedtls_pk_parse_key(&l.certs.client_key, l.config.cert_key.str,
l.config.cert_key.len + 1, 0, 0, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
}
} else {
if l.config.verify != '' {
ret = C.mbedtls_x509_crt_parse_file(&l.certs.cacert, &char(l.config.verify.str))
}
ret = C.mbedtls_x509_crt_parse_file(&l.certs.client_cert, &char(l.config.cert.str))
unsafe {
ret = C.mbedtls_pk_parse_keyfile(&l.certs.client_key, &char(l.config.cert_key.str),
0, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
}
if l.config.validate {
C.mbedtls_ssl_conf_authmode(&l.conf, C.MBEDTLS_SSL_VERIFY_REQUIRED)
}
mut bind_ip := unsafe { nil }
if lhost != '' {
bind_ip = voidptr(lhost.str)
}
bind_port := lport.str()
ret = C.mbedtls_net_bind(&l.server_fd, bind_ip, voidptr(bind_port.str), C.MBEDTLS_NET_PROTO_TCP)
if ret != 0 {
return error_with_code("can't bind to ${l.saddr}", ret)
}
ret = C.mbedtls_ssl_config_defaults(&l.conf, C.MBEDTLS_SSL_IS_SERVER, C.MBEDTLS_SSL_TRANSPORT_STREAM,
C.MBEDTLS_SSL_PRESET_DEFAULT)
if ret != 0 {
return error_with_code("can't to set config defaults", ret)
}
C.mbedtls_ssl_conf_ca_chain(&l.conf, &l.certs.cacert, unsafe { nil })
ret = C.mbedtls_ssl_conf_own_cert(&l.conf, &l.certs.client_cert, &l.certs.client_key)
if ret != 0 {
return error_with_code("can't load certificate", ret)
}
ret = C.mbedtls_ssl_setup(&l.ssl, &l.conf)
if ret != 0 {
return error_with_code("can't setup ssl", ret)
}
}
// accepts a new connection and returns a SSLConn of the connected client
pub fn (mut l SSLListener) accept() !&SSLConn {
mut conn := &SSLConn{
config: l.config
opened: true
}
// TODO: save the client's IP address somewhere (maybe add a field to SSLConn ?)
mut ret := C.mbedtls_net_accept(&l.server_fd, &conn.server_fd, unsafe { nil }, 0,
unsafe { nil })
if ret != 0 {
return error_with_code("can't accept connection", ret)
}
conn.handle = conn.server_fd.fd
conn.owns_socket = true
C.mbedtls_ssl_init(&conn.ssl)
C.mbedtls_ssl_config_init(&conn.conf)
ret = C.mbedtls_ssl_setup(&conn.ssl, &l.conf)
if ret != 0 {
return error_with_code('SSL setup failed', ret)
}
C.mbedtls_ssl_set_bio(&conn.ssl, &conn.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
unsafe { nil })
ret = C.mbedtls_ssl_handshake(&conn.ssl)
for ret != 0 {
if ret != C.MBEDTLS_ERR_SSL_WANT_READ && ret != C.MBEDTLS_ERR_SSL_WANT_WRITE {
return error_with_code('SSL handshake failed', ret)
}
ret = C.mbedtls_ssl_handshake(&conn.ssl)
}
return conn
}
[params]
pub struct SSLConnectConfig {
verify string // the path to a rootca.pem file, containing trusted CA certificate(s)
cert string // the path to a cert.pem file, containing client certificate(s) for the request
cert_key string // the path to a key.pem file, containing private keys for the client certificate(s)
validate bool // set this to true, if you want to stop requests, when their certificates are found to be invalid
in_memory_verification bool // if true, verify, cert, and cert_key are read from memory, not from a file
}
// new_ssl_conn returns a new SSLConn with the given config.
pub fn new_ssl_conn(config SSLConnectConfig) !&SSLConn {
$if trace_ssl ? {
eprintln(@METHOD)
}
mut conn := &SSLConn{
config: config
}
conn.init() or { return err }
return conn
}
// Select operation
enum Select {
read
write
except
}
// shutdown terminates the ssl connection and does cleanup
pub fn (mut s SSLConn) shutdown() ! {
$if trace_ssl ? {
eprintln(@METHOD)
}
if !s.opened {
return error('ssl connection not open')
}
if unsafe { s.certs != nil } {
C.mbedtls_x509_crt_free(&s.certs.cacert)
C.mbedtls_x509_crt_free(&s.certs.client_cert)
C.mbedtls_pk_free(&s.certs.client_key)
}
C.mbedtls_ssl_free(&s.ssl)
C.mbedtls_ssl_config_free(&s.conf)
if s.owns_socket {
net.shutdown(s.handle)
net.close(s.handle)!
}
}
// connect to server using mbedtls
fn (mut s SSLConn) init() ! {
$if trace_ssl ? {
eprintln(@METHOD)
}
C.mbedtls_net_init(&s.server_fd)
C.mbedtls_ssl_init(&s.ssl)
C.mbedtls_ssl_config_init(&s.conf)
mut ret := 0
ret = C.mbedtls_ssl_config_defaults(&s.conf, C.MBEDTLS_SSL_IS_CLIENT, C.MBEDTLS_SSL_TRANSPORT_STREAM,
C.MBEDTLS_SSL_PRESET_DEFAULT)
if ret != 0 {
return error_with_code('Failed to set SSL configuration', ret)
}
unsafe {
C.mbedtls_ssl_conf_rng(&s.conf, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
if s.config.verify != '' || s.config.cert != '' || s.config.cert_key != '' {
s.certs = &SSLCerts{}
C.mbedtls_x509_crt_init(&s.certs.cacert)
C.mbedtls_x509_crt_init(&s.certs.client_cert)
C.mbedtls_pk_init(&s.certs.client_key)
}
if s.config.in_memory_verification {
if s.config.verify != '' {
ret = C.mbedtls_x509_crt_parse(&s.certs.cacert, s.config.verify.str,
s.config.verify.len + 1)
}
if s.config.cert != '' {
ret = C.mbedtls_x509_crt_parse(&s.certs.client_cert, s.config.cert.str,
s.config.cert.len + 1)
}
if s.config.cert_key != '' {
unsafe {
ret = C.mbedtls_pk_parse_key(&s.certs.client_key, s.config.cert_key.str,
s.config.cert_key.len + 1, 0, 0, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
}
} else {
if s.config.verify != '' {
ret = C.mbedtls_x509_crt_parse_file(&s.certs.cacert, &char(s.config.verify.str))
}
if s.config.cert != '' {
ret = C.mbedtls_x509_crt_parse_file(&s.certs.client_cert, &char(s.config.cert.str))
}
if s.config.cert_key != '' {
unsafe {
ret = C.mbedtls_pk_parse_keyfile(&s.certs.client_key, &char(s.config.cert_key.str),
0, C.mbedtls_ctr_drbg_random, &mbedtls.ctr_drbg)
}
}
}
if ret < 0 {
return error_with_code('Failed to set certificates', ret)
}
if unsafe { s.certs != nil } {
C.mbedtls_ssl_conf_ca_chain(&s.conf, &s.certs.cacert, 0)
C.mbedtls_ssl_conf_own_cert(&s.conf, &s.certs.client_cert, &s.certs.client_key)
}
if s.config.validate {
C.mbedtls_ssl_conf_authmode(&s.conf, C.MBEDTLS_SSL_VERIFY_REQUIRED)
} else {
C.mbedtls_ssl_conf_authmode(&s.conf, C.MBEDTLS_SSL_VERIFY_OPTIONAL)
}
ret = C.mbedtls_ssl_setup(&s.ssl, &s.conf)
if ret != 0 {
return error_with_code('Failed to setup SSL connection', ret)
}
}
// connect sets up an ssl connection on an existing TCP connection
pub fn (mut s SSLConn) connect(mut tcp_conn net.TcpConn, hostname string) ! {
$if trace_ssl ? {
eprintln('${@METHOD} hostname: ${hostname}')
}
if s.opened {
return error('ssl connection already open')
}
s.handle = tcp_conn.sock.handle
s.duration = 30 * time.second
mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
if ret != 0 {
return error_with_code('Failed to set hostname', ret)
}
s.server_fd.fd = s.handle
C.mbedtls_ssl_set_bio(&s.ssl, &s.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
C.mbedtls_net_recv_timeout)
ret = C.mbedtls_ssl_handshake(&s.ssl)
if ret != 0 {
return error_with_code('SSL handshake failed', ret)
}
s.opened = true
}
// dial opens an ssl connection on hostname:port
pub fn (mut s SSLConn) dial(hostname string, port int) ! {
$if trace_ssl ? {
eprintln('${@METHOD} hostname: ${hostname} | port: ${port}')
}
s.owns_socket = true
if s.opened {
return error('ssl connection already open')
}
s.duration = 30 * time.second
mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
if ret != 0 {
return error_with_code('Failed to set hostname', ret)
}
port_str := port.str()
ret = C.mbedtls_net_connect(&s.server_fd, &char(hostname.str), &char(port_str.str),
C.MBEDTLS_NET_PROTO_TCP)
if ret != 0 {
return error_with_code('Failed to connect to host', ret)
}
C.mbedtls_ssl_set_bio(&s.ssl, &s.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
C.mbedtls_net_recv_timeout)
s.handle = s.server_fd.fd
ret = C.mbedtls_ssl_handshake(&s.ssl)
if ret != 0 {
return error_with_code('SSL handshake failed', ret)
}
s.opened = true
}
// peer_addr retrieves the ip address and port number used by the peer
pub fn (s &SSLConn) peer_addr() !net.Addr {
return net.peer_addr_from_socket_handle(s.handle)
}
// socket_read_into_ptr reads `len` bytes into `buf`
pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) !int {
mut res := 0
$if trace_ssl ? {
defer {
if len > 0 {
eprintln('${@METHOD} res: ${res}: buf_ptr: ${voidptr(buf_ptr):x}, len: ${len}, hex: ${unsafe { buf_ptr.vbytes(len).hex() }} data: `${unsafe { buf_ptr.vstring_with_len(len) }}`')
}
}
}
for {
res = C.mbedtls_ssl_read(&s.ssl, buf_ptr, len)
if res > 0 {
return res
} else if res == 0 {
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: io.Eof')
}
return io.Eof{}
} else {
match res {
C.MBEDTLS_ERR_SSL_WANT_READ {
ready := @select(s.handle, .read, s.duration)!
if !ready {
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: net.err_timed_out, C.MBEDTLS_ERR_SSL_WANT_READ')
}
return net.err_timed_out
}
}
C.MBEDTLS_ERR_SSL_WANT_WRITE {
ready := @select(s.handle, .write, s.duration)!
if !ready {
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: net.err_timed_out, C.MBEDTLS_ERR_SSL_WANT_WRITE')
}
return net.err_timed_out
}
}
C.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY {
break
}
else {
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: could not read using SSL')
}
return error_with_code('Could not read using SSL', res)
}
}
}
}
return res
}
// read reads data from the ssl connection into `buffer`
pub fn (mut s SSLConn) read(mut buffer []u8) !int {
$if trace_ssl ? {
eprintln('${@METHOD} buffer.len: ${buffer.len}')
}
return s.socket_read_into_ptr(&u8(buffer.data), buffer.len)
}
// write_ptr writes `len` bytes from `bytes` to the ssl connection
pub fn (mut s SSLConn) write_ptr(bytes &u8, len int) !int {
mut total_sent := 0
$if trace_ssl ? {
defer {
eprintln('${@METHOD} total_sent: ${total_sent}, bytes: ${voidptr(bytes):x}, len: ${len}, hex: ${unsafe { bytes.vbytes(len).hex() }}, data:-=-=-=-\n${unsafe { bytes.vstring_with_len(len) }}\n-=-=-=-')
}
}
unsafe {
mut ptr_base := bytes
for total_sent < len {
ptr := ptr_base + total_sent
remaining := len - total_sent
mut sent := C.mbedtls_ssl_write(&s.ssl, ptr, remaining)
if sent <= 0 {
match sent {
C.MBEDTLS_ERR_SSL_WANT_READ {
for {
ready := @select(s.handle, .read, s.duration)!
if ready {
break
}
}
continue
}
C.MBEDTLS_ERR_SSL_WANT_WRITE {
for {
ready := @select(s.handle, .write, s.duration)!
if ready {
break
}
}
continue
}
else {
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: could not write SSL, sent: ${sent}')
}
return error_with_code('Could not write using SSL', sent)
}
}
}
total_sent += sent
}
}
return total_sent
}
// write writes data from `bytes` to the ssl connection
pub fn (mut s SSLConn) write(bytes []u8) !int {
return s.write_ptr(&u8(bytes.data), bytes.len)
}
// write_string writes a string to the ssl connection
pub fn (mut s SSLConn) write_string(str string) !int {
$if trace_ssl ? {
eprintln('${@METHOD} str: ${str}')
}
return s.write_ptr(str.str, str.len)
}
/*
This is basically a copy of Emily socket implementation of select.
This have to be consolidated into common net lib features
when merging this to V
*/
// Select waits for an io operation (specified by parameter `test`) to be available
fn @select(handle int, test Select, timeout time.Duration) !bool {
$if trace_ssl ? {
eprintln('${@METHOD} handle: ${handle}, timeout: ${timeout}')
}
set := C.fd_set{}
C.FD_ZERO(&set)
C.FD_SET(handle, &set)
seconds := timeout.milliseconds() / 1000
microseconds := timeout - (seconds * time.second)
mut tt := C.timeval{
tv_sec: u64(seconds)
tv_usec: u64(microseconds)
}
mut timeval_timeout := &tt
// infinite timeout is signaled by passing null as the timeout to
// select
if timeout == net.infinite_timeout {
timeval_timeout = &C.timeval(unsafe { nil })
}
match test {
.read {
net.socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))!
}
.write {
net.socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))!
}
.except {
net.socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))!
}
}
res := C.FD_ISSET(handle, &set)
$if trace_ssl ? {
eprintln('${@METHOD} ---> res: ${res}')
}
return res
}