vq / vlib / net / mbedtls / ssl_connection.c.v
1035 lines · 939 sloc · 32.04 KB · a07c977c5bfc53b0776bb08aecc351b1bb35f154
Raw
1module mbedtls
2
3import io
4import net
5import sync
6import time
7
8const mbedtls_client_read_timeout_ms = $d('mbedtls_client_read_timeout_ms', 10_000)
9const mbedtls_server_read_timeout_ms = $d('mbedtls_server_read_timeout_ms', 41_000)
10const default_mbedtls_client_read_timeout = mbedtls_client_read_timeout_ms * time.millisecond
11const default_mbedtls_server_read_timeout = mbedtls_server_read_timeout_ms * time.millisecond
12
13fn init_rng(mut ctr_drbg C.mbedtls_ctr_drbg_context, mut entropy C.mbedtls_entropy_context) ! {
14 $if trace_ssl ? {
15 eprintln(@METHOD)
16 }
17 C.mbedtls_ctr_drbg_init(&ctr_drbg)
18 C.mbedtls_entropy_init(&entropy)
19 ret := C.mbedtls_ctr_drbg_seed(&ctr_drbg, C.mbedtls_entropy_func, &entropy, 0, 0)
20 if ret != 0 {
21 C.mbedtls_ctr_drbg_free(&ctr_drbg)
22 C.mbedtls_entropy_free(&entropy)
23 return error_with_code('net.mbedtls init_rng, failed to seed ssl context: ${ret}', ret)
24 }
25 // C.mbedtls_debug_set_threshold(5)
26}
27
28fn free_rng(mut ctr_drbg C.mbedtls_ctr_drbg_context, mut entropy C.mbedtls_entropy_context) {
29 C.mbedtls_ctr_drbg_free(&ctr_drbg)
30 C.mbedtls_entropy_free(&entropy)
31}
32
33// SSLCerts represents a pair of CA and client certificates + key
34pub struct SSLCerts {
35pub mut:
36 cacert C.mbedtls_x509_crt
37 client_cert C.mbedtls_x509_crt
38 client_key C.mbedtls_pk_context
39}
40
41// new_sslcerts initializes and returns a pair of SSL certificates and key
42pub fn new_sslcerts() &SSLCerts {
43 mut certs := SSLCerts{}
44 C.mbedtls_x509_crt_init(&certs.cacert)
45 C.mbedtls_x509_crt_init(&certs.client_cert)
46 C.mbedtls_pk_init(&certs.client_key)
47 return &certs
48}
49
50// new_sslcerts_in_memory creates a pair of SSL certificates, given their contents (not paths).
51pub fn new_sslcerts_in_memory(verify string, cert string, cert_key string) !&SSLCerts {
52 mut ctr_drbg := C.mbedtls_ctr_drbg_context{}
53 mut entropy := C.mbedtls_entropy_context{}
54 init_rng(mut ctr_drbg, mut entropy)!
55 defer {
56 free_rng(mut ctr_drbg, mut entropy)
57 }
58 return new_sslcerts_in_memory_with_rng(verify, cert, cert_key, &ctr_drbg)
59}
60
61fn new_sslcerts_in_memory_with_rng(verify string, cert string, cert_key string, rng &C.mbedtls_ctr_drbg_context) !&SSLCerts {
62 mut certs := new_sslcerts()
63 if verify != '' {
64 ret := C.mbedtls_x509_crt_parse(&certs.cacert, verify.str, verify.len + 1)
65 if ret != 0 {
66 return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_x509_crt_parse error 1 ret: ${ret}',
67 ret)
68 }
69 }
70 if cert != '' {
71 ret := C.mbedtls_x509_crt_parse(&certs.client_cert, cert.str, cert.len + 1)
72 if ret != 0 {
73 return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_x509_crt_parse error 2 ret: ${ret}',
74 ret)
75 }
76 }
77 if cert_key != '' {
78 unsafe {
79 ret := C.mbedtls_pk_parse_key(&certs.client_key, cert_key.str, cert_key.len + 1, 0, 0,
80 C.mbedtls_ctr_drbg_random, rng)
81 if ret != 0 {
82 return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_pk_parse_key error ret: ${ret}',
83 ret)
84 }
85 }
86 }
87 return certs
88}
89
90// new_sslcerts_from_file creates a new pair of SSL certificates, given their paths on the filesystem.
91pub fn new_sslcerts_from_file(verify string, cert string, cert_key string) !&SSLCerts {
92 mut ctr_drbg := C.mbedtls_ctr_drbg_context{}
93 mut entropy := C.mbedtls_entropy_context{}
94 init_rng(mut ctr_drbg, mut entropy)!
95 defer {
96 free_rng(mut ctr_drbg, mut entropy)
97 }
98 return new_sslcerts_from_file_with_rng(verify, cert, cert_key, &ctr_drbg)
99}
100
101fn new_sslcerts_from_file_with_rng(verify string, cert string, cert_key string, rng &C.mbedtls_ctr_drbg_context) !&SSLCerts {
102 mut certs := new_sslcerts()
103 if verify != '' {
104 ret := C.mbedtls_x509_crt_parse_file(&certs.cacert, &char(verify.str))
105 if ret != 0 {
106 return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_x509_crt_parse_file error 1 ret: ${ret}',
107 ret)
108 }
109 }
110 if cert != '' {
111 ret := C.mbedtls_x509_crt_parse_file(&certs.client_cert, &char(cert.str))
112 if ret != 0 {
113 return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_x509_crt_parse_file error 2 ret: ${ret}',
114 ret)
115 }
116 }
117 if cert_key != '' {
118 unsafe {
119 ret := C.mbedtls_pk_parse_keyfile(&certs.client_key, &char(cert_key.str), 0,
120 C.mbedtls_ctr_drbg_random, rng)
121 if ret != 0 {
122 return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_pk_parse_keyfile error ret: ${ret}',
123 ret)
124 }
125 }
126 }
127 return certs
128}
129
130// cleanup frees the SSL certificates
131pub fn (mut c SSLCerts) cleanup() {
132 C.mbedtls_x509_crt_free(&c.cacert)
133 C.mbedtls_x509_crt_free(&c.client_cert)
134 C.mbedtls_pk_free(&c.client_key)
135}
136
137// SSLConn is the current connection
138pub struct SSLConn {
139pub:
140 config SSLConnectConfig
141pub mut:
142 server_fd C.mbedtls_net_context
143 ssl C.mbedtls_ssl_context
144 conf C.mbedtls_ssl_config
145 certs &SSLCerts = unsafe { nil }
146 ctr_drbg C.mbedtls_ctr_drbg_context
147 entropy C.mbedtls_entropy_context
148 handle int
149 duration time.Duration
150 opened bool
151 ip string
152 read_timeout time.Duration
153
154 owns_socket bool
155 // alpn_list is a NUL-terminated C array of pointers to the protocol
156 // strings in config.alpn_protocols. mbedtls stores this pointer without
157 // copying, so it must outlive the SSL config; it is freed in shutdown().
158 alpn_list &&char = unsafe { nil }
159 // last_write_sent reports the most recent write_ptr's progress for retry
160 // decisions: 0 = provably nothing was sent (safe to replay), or -1 = the
161 // count is indeterminate because a failed/retryable write may have already
162 // flushed a record to the peer (TLS cannot prove zero). On full success it
163 // equals the bytes written.
164 last_write_sent int
165}
166
167// SSLListener listens on a TCP port and accepts connection secured with TLS
168pub struct SSLListener {
169 saddr string
170 config SSLConnectConfig
171mut:
172 server_fd C.mbedtls_net_context
173 ssl C.mbedtls_ssl_context
174 conf C.mbedtls_ssl_config
175 certs &SSLCerts = unsafe { nil }
176 ctr_drbg C.mbedtls_ctr_drbg_context
177 entropy C.mbedtls_entropy_context
178 rng_mutex &sync.Mutex = sync.new_mutex()
179 opened bool
180 // alpn_list is a NUL-terminated C array of pointers to the protocol
181 // strings in config.alpn_protocols, advertised by accepted connections.
182 // It must outlive the SSL config and is freed in shutdown().
183 alpn_list &&char = unsafe { nil }
184 // handle int
185 // duration time.Duration
186}
187
188// create a new SSLListener binding to `saddr`
189pub fn new_ssl_listener(saddr string, config SSLConnectConfig) !&SSLListener {
190 mut listener := &SSLListener{
191 saddr: saddr
192 config: config
193 }
194 listener.init()!
195 listener.opened = true
196 return listener
197}
198
199// finish the listener and clean up resources
200pub fn (mut l SSLListener) shutdown() ! {
201 $if trace_ssl ? {
202 eprintln(@METHOD)
203 }
204 if unsafe { l.certs != nil } {
205 l.certs.cleanup()
206 }
207 C.mbedtls_ssl_free(&l.ssl)
208 C.mbedtls_ssl_config_free(&l.conf)
209 free_rng(mut l.ctr_drbg, mut l.entropy)
210 if l.alpn_list != unsafe { nil } {
211 unsafe {
212 C.free(l.alpn_list)
213 l.alpn_list = nil
214 }
215 }
216 if l.opened {
217 C.mbedtls_net_free(&l.server_fd)
218 }
219}
220
221// internal function to init and bind the listener
222fn (mut l SSLListener) init() ! {
223 $if trace_ssl ? {
224 eprintln(@METHOD)
225 }
226
227 lhost, lport := net.split_address(l.saddr)!
228 if l.config.cert == '' || l.config.cert_key == '' {
229 return error('net.mbedtls SSLListener.init, no certificate or key provided')
230 }
231 if l.config.validate && l.config.verify == '' {
232 return error('net.mbedtls SSLListener.init, no root CA provided')
233 }
234 C.mbedtls_net_init(&l.server_fd)
235 C.mbedtls_ssl_init(&l.ssl)
236 C.mbedtls_ssl_config_init(&l.conf)
237 init_rng(mut l.ctr_drbg, mut l.entropy)!
238 l.certs = &SSLCerts{}
239 C.mbedtls_x509_crt_init(&l.certs.client_cert)
240 C.mbedtls_pk_init(&l.certs.client_key)
241
242 unsafe {
243 C.mbedtls_ssl_conf_rng(&l.conf, tls_listener_rng, l)
244 }
245
246 mut ret := 0
247
248 if l.config.in_memory_verification {
249 l.certs = new_sslcerts_in_memory_with_rng(l.config.verify, l.config.cert,
250 l.config.cert_key, &l.ctr_drbg) or {
251 return error('net.mbedtls SSLListener.init, cert failure 1, err: ${err}')
252 }
253 } else {
254 l.certs = new_sslcerts_from_file_with_rng(l.config.verify, l.config.cert,
255 l.config.cert_key, &l.ctr_drbg) or {
256 return error('net.mbedtls SSLListener.init, cert failure 2, err: ${err}')
257 }
258 }
259
260 if l.config.validate {
261 C.mbedtls_ssl_conf_authmode(&l.conf, C.MBEDTLS_SSL_VERIFY_REQUIRED)
262 }
263
264 mut bind_ip := unsafe { nil }
265 if lhost != '' {
266 bind_ip = voidptr(lhost.str)
267 }
268 bind_port := lport.str()
269
270 ret = C.mbedtls_net_bind(&l.server_fd, bind_ip, voidptr(bind_port.str), C.MBEDTLS_NET_PROTO_TCP)
271
272 if ret != 0 {
273 return error_with_code("net.mbedtls SSLListener.init, mbedtls_net_bind can't bind to ${l.saddr} error ret: ${ret}",
274 ret)
275 }
276
277 ret = C.mbedtls_ssl_config_defaults(&l.conf, C.MBEDTLS_SSL_IS_SERVER,
278 C.MBEDTLS_SSL_TRANSPORT_STREAM, C.MBEDTLS_SSL_PRESET_DEFAULT)
279 if ret != 0 {
280 return error_with_code("net.mbedtls SSLListener.init, mbedtls_ssl_config_defaults can't set config defaults ret: ${ret}",
281 ret)
282 }
283 listener_read_timeout := ssl_listener_read_timeout(l.config)
284 $if trace_mbedtls_timeouts ? {
285 dump(listener_read_timeout)
286 }
287 C.mbedtls_ssl_conf_read_timeout(&l.conf, ssl_read_timeout_ms(listener_read_timeout))
288
289 C.mbedtls_ssl_conf_ca_chain(&l.conf, &l.certs.cacert, unsafe { nil })
290 ret = C.mbedtls_ssl_conf_own_cert(&l.conf, &l.certs.client_cert, &l.certs.client_key)
291 if ret != 0 {
292 return error_with_code("net.mbedtls SSLListener.init, mbedtls_ssl_conf_own_cert can't load certificate ret: ${ret}",
293 ret)
294 }
295
296 // Advertise ALPN protocols for accepted connections to select from.
297 // See the matching client-side logic in SSLConn.init for lifetime notes.
298 if l.config.alpn_protocols.len > 0 {
299 n := l.config.alpn_protocols.len
300 l.alpn_list = unsafe { &&char(C.malloc(isize((n + 1) * int(sizeof(voidptr))))) }
301 if l.alpn_list == unsafe { nil } {
302 return error('net.mbedtls SSLListener.init, failed to allocate ALPN list')
303 }
304 unsafe {
305 for i, proto in l.config.alpn_protocols {
306 l.alpn_list[i] = &char(proto.str)
307 }
308 l.alpn_list[n] = &char(0)
309 }
310 ret = C.mbedtls_ssl_conf_alpn_protocols(&l.conf, voidptr(l.alpn_list))
311 if ret != 0 {
312 return error_with_code('net.mbedtls SSLListener.init, mbedtls_ssl_conf_alpn_protocols failed ret: ${ret}',
313 ret)
314 }
315 }
316
317 ret = C.mbedtls_ssl_setup(&l.ssl, &l.conf)
318 if ret != 0 {
319 return error_with_code("net.mbedtls SSLListener.init, mbedtls_ssl_setup can't setup ssl ret: ${ret}",
320 ret)
321 }
322
323 if get_cert_callback := l.config.get_certificate {
324 l.init_sni(get_cert_callback)
325 }
326}
327
328fn tls_listener_rng(p_rng voidptr, output &u8, output_len usize) int {
329 mut listener := unsafe { &SSLListener(p_rng) }
330 listener.rng_mutex.lock()
331 defer {
332 listener.rng_mutex.unlock()
333 }
334 return C.mbedtls_ctr_drbg_random(&listener.ctr_drbg, output, output_len)
335}
336
337// setup SNI callback
338fn (mut l SSLListener) init_sni(get_cert_callback fn (mut SSLListener, string) !&SSLCerts) {
339 $if trace_ssl ? {
340 eprintln(@METHOD)
341 }
342 C.mbedtls_ssl_conf_sni(&l.conf, fn [get_cert_callback, mut l] (p_info voidptr, ssl &C.mbedtls_ssl_context, name &u8, lng usize) int {
343 host := unsafe { name.vstring_literal_with_len(int(lng)) }
344 if certs := get_cert_callback(mut l, host) {
345 return C.mbedtls_ssl_set_hs_own_cert(ssl, &certs.client_cert, &certs.client_key)
346 } else {
347 return -1
348 }
349 }, &l.conf)
350}
351
352// accepts a new connection and returns a SSLConn of the connected client
353pub fn (mut l SSLListener) accept() !&SSLConn {
354 mut conn := l.accept_tcp_connection()!
355
356 C.mbedtls_ssl_init(&conn.ssl)
357 C.mbedtls_ssl_config_init(&conn.conf)
358 ret := C.mbedtls_ssl_setup(&conn.ssl, &l.conf)
359 if ret != 0 {
360 conn.shutdown() or {}
361 return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_setup SSL setup failed ret: ${ret}',
362 ret)
363 }
364
365 C.mbedtls_ssl_set_bio(&conn.ssl, &conn.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
366 C.mbedtls_net_recv_timeout)
367 conn.server_handshake(net.infinite_timeout)!
368 return conn
369}
370
371fn (mut l SSLListener) accept_tcp_connection() !&SSLConn {
372 mut conn := &SSLConn{
373 config: l.config
374 duration: ssl_listener_read_timeout(l.config)
375 read_timeout: ssl_listener_read_timeout(l.config)
376 opened: true
377 }
378 ip := [16]u8{}
379 iplen := usize(0)
380
381 ret := C.mbedtls_net_accept(&l.server_fd, &conn.server_fd, &ip, 16, &iplen)
382 if ret != 0 {
383 return error_with_code("net.mbedtls SSLListener.accept, mbedtls_net_accept can't accept connection ret: ${ret}",
384 ret)
385 }
386 conn.handle = conn.server_fd.fd
387 conn.owns_socket = true
388 if iplen == 4 {
389 conn.ip = '${ip[0]}.${ip[1]}.${ip[2]}.${ip[3]}'
390 }
391 return conn
392}
393
394// do_handshake_loop drives the non-blocking TLS server handshake to completion
395// (or `deadline`). It never calls shutdown: on any error it just returns, leaving
396// cleanup to the caller. server_handshake wraps it for the synchronous accept
397// path (self-shutdown on error); the threaded server path (complete_handshake)
398// lets its worker defer own the single shutdown instead.
399fn (mut conn SSLConn) do_handshake_loop(deadline time.Time) ! {
400 mut ret := C.mbedtls_ssl_handshake(&conn.ssl)
401 for ret != 0 {
402 match ret {
403 C.MBEDTLS_ERR_SSL_WANT_READ {
404 conn.wait_for_read(ssl_remaining_timeout(deadline))!
405 }
406 C.MBEDTLS_ERR_SSL_WANT_WRITE {
407 conn.wait_for_write(ssl_remaining_timeout(deadline))!
408 }
409 else {
410 return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_handshake failed 1; handshake ret: ${ret}',
411 ret)
412 }
413 }
414
415 ret = C.mbedtls_ssl_handshake(&conn.ssl)
416 }
417}
418
419fn (mut conn SSLConn) server_handshake(timeout time.Duration) ! {
420 deadline := ssl_timeout_deadline(timeout)
421 conn.do_handshake_loop(deadline) or {
422 conn.shutdown() or {
423 $if trace_ssl ? {
424 eprintln('${@METHOD} shutdown ---> res: ${err}')
425 }
426 }
427 return err
428 }
429}
430
431// accept_with_timeout waits up to `timeout` for a new client before accepting it.
432pub fn (mut l SSLListener) accept_with_timeout(timeout time.Duration) !&SSLConn {
433 return l.accept_with_timeouts(timeout, timeout)
434}
435
436// accept_raw_with_timeout waits up to `accept_timeout` for a new client, accepts
437// the raw TCP connection and sets up its (non-blocking) SSL context, but does NOT
438// perform the TLS handshake. The returned conn is non-blocking with a non-blocking
439// bio; the caller must run conn.complete_handshake to finish negotiation. This lets
440// the threaded server accept on one thread and handshake on a worker thread.
441pub fn (mut l SSLListener) accept_raw_with_timeout(accept_timeout time.Duration) !&SSLConn {
442 wait_for(l.server_fd.fd, .read, accept_timeout)!
443 mut conn := l.accept_tcp_connection()!
444
445 C.mbedtls_ssl_init(&conn.ssl)
446 C.mbedtls_ssl_config_init(&conn.conf)
447 net.set_blocking(conn.handle, false) or {
448 conn.shutdown() or {}
449 return err
450 }
451 ret := C.mbedtls_ssl_setup(&conn.ssl, &l.conf)
452 if ret != 0 {
453 conn.shutdown() or {}
454 return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_setup SSL setup failed ret: ${ret}',
455 ret)
456 }
457
458 C.v_mbedtls_ssl_set_bio_nonblocking(&conn.ssl, &conn.server_fd)
459 return conn
460}
461
462// complete_handshake finishes the TLS server handshake on a conn returned by
463// accept_raw_with_timeout, waiting up to `timeout`, then restores blocking mode
464// and the blocking bio. It never calls shutdown: on any error it returns and the
465// caller owns cleanup (so the conn is shut down exactly once, by the caller).
466pub fn (mut conn SSLConn) complete_handshake(timeout time.Duration) ! {
467 deadline := ssl_timeout_deadline(timeout)
468 conn.do_handshake_loop(deadline)!
469 net.set_blocking(conn.handle, true)!
470 C.mbedtls_ssl_set_bio(&conn.ssl, &conn.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
471 C.mbedtls_net_recv_timeout)
472}
473
474// accept_with_timeouts waits up to `accept_timeout` for a new client, then
475// waits up to `handshake_timeout` for the TLS server handshake to complete.
476pub fn (mut l SSLListener) accept_with_timeouts(accept_timeout time.Duration, handshake_timeout time.Duration) !&SSLConn {
477 mut conn := l.accept_raw_with_timeout(accept_timeout)!
478 conn.complete_handshake(handshake_timeout) or {
479 conn.shutdown() or {}
480 return err
481 }
482 return conn
483}
484
485@[params]
486pub struct SSLConnectConfig {
487pub:
488 verify string // the path to a rootca.pem file, containing trusted CA certificate(s)
489 cert string // the path to a cert.pem file, containing client certificate(s) for the request
490 cert_key string // the path to a key.pem file, containing private keys for the client certificate(s)
491 validate bool // set this to true, if you want to stop requests, when their certificates are found to be invalid
492
493 in_memory_verification bool // if true, verify, cert, and cert_key are read from memory, not from a file
494
495 get_certificate ?fn (mut SSLListener, string) !&SSLCerts
496
497 read_timeout time.Duration = default_mbedtls_client_read_timeout // the SSL client read timeout
498
499 alpn_protocols []string // the list of ALPN protocols to advertise, e.g. ['h2', 'http/1.1']; empty means no ALPN extension is sent
500}
501
502fn ssl_read_timeout_ms(timeout time.Duration) u32 {
503 if timeout <= 0 || timeout == net.infinite_timeout {
504 return 0
505 }
506 timeout_ms := timeout.milliseconds()
507 if timeout_ms > i64(max_u32) {
508 return max_u32
509 }
510 return u32(timeout_ms)
511}
512
513fn ssl_listener_read_timeout(config SSLConnectConfig) time.Duration {
514 if config.read_timeout == default_mbedtls_client_read_timeout {
515 return default_mbedtls_server_read_timeout
516 }
517 return config.read_timeout
518}
519
520fn ssl_timeout_deadline(timeout time.Duration) time.Time {
521 if timeout <= 0 || timeout == net.infinite_timeout {
522 return time.unix(0)
523 }
524 return time.now().add(timeout)
525}
526
527fn ssl_remaining_timeout(deadline time.Time) time.Duration {
528 if deadline.unix() == 0 {
529 return net.infinite_timeout
530 }
531 remaining := deadline - time.now()
532 if remaining <= 0 {
533 return time.nanosecond
534 }
535 return remaining
536}
537
538// read_timeout returns the current SSL read timeout.
539pub fn (s &SSLConn) read_timeout() time.Duration {
540 return s.read_timeout
541}
542
543// set_read_timeout sets the SSL read timeout for subsequent operations.
544pub fn (mut s SSLConn) set_read_timeout(timeout time.Duration) {
545 s.read_timeout = timeout
546 s.duration = timeout
547 C.mbedtls_ssl_conf_read_timeout(&s.conf, ssl_read_timeout_ms(timeout))
548}
549
550// new_ssl_conn returns a new SSLConn with the given config.
551pub fn new_ssl_conn(config SSLConnectConfig) !&SSLConn {
552 $if trace_ssl ? {
553 eprintln(@METHOD)
554 }
555 mut conn := &SSLConn{
556 config: config
557 duration: config.read_timeout
558 read_timeout: config.read_timeout
559 }
560 conn.init()!
561 return conn
562}
563
564// Select operation
565enum Select {
566 read
567 write
568 except
569}
570
571// close terminates the ssl connection and does cleanup
572pub fn (mut s SSLConn) close() ! {
573 s.shutdown()!
574}
575
576// shutdown terminates the ssl connection and does cleanup
577pub fn (mut s SSLConn) shutdown() ! {
578 $if trace_ssl ? {
579 eprintln(@METHOD)
580 }
581 if !s.opened {
582 return error('net.mbedtls SSLConn.shutdown, connection was not open')
583 }
584 // Mark closed before freeing so a second shutdown (e.g. a worker defer racing
585 // close_idle) is a harmless no-op rather than a double-free of the mbedtls
586 // contexts below.
587 s.opened = false
588 if unsafe { s.certs != nil } {
589 C.mbedtls_x509_crt_free(&s.certs.cacert)
590 C.mbedtls_x509_crt_free(&s.certs.client_cert)
591 C.mbedtls_pk_free(&s.certs.client_key)
592 }
593 C.mbedtls_ssl_free(&s.ssl)
594 C.mbedtls_ssl_config_free(&s.conf)
595 free_rng(mut s.ctr_drbg, mut s.entropy)
596 if s.alpn_list != unsafe { nil } {
597 unsafe {
598 C.free(s.alpn_list)
599 s.alpn_list = nil
600 }
601 }
602 if s.owns_socket {
603 net.shutdown(s.handle)
604 net.close(s.handle)!
605 }
606}
607
608// negotiated_alpn returns the ALPN protocol selected during the TLS
609// handshake (e.g. 'h2' or 'http/1.1'), or an empty string if no protocol
610// was negotiated.
611pub fn (s &SSLConn) negotiated_alpn() string {
612 // mbedtls_ssl_get_alpn_protocol returns a `const char *`; cast away const
613 // for V, since we only read from it (and copy it below).
614 p := &char(C.mbedtls_ssl_get_alpn_protocol(&s.ssl))
615 if p == unsafe { nil } {
616 return ''
617 }
618 return unsafe { cstring_to_vstring(p) }
619}
620
621// connect to server using mbedtls
622fn (mut s SSLConn) init() ! {
623 $if trace_ssl ? {
624 eprintln(@METHOD)
625 }
626 C.mbedtls_net_init(&s.server_fd)
627 C.mbedtls_ssl_init(&s.ssl)
628 C.mbedtls_ssl_config_init(&s.conf)
629 init_rng(mut s.ctr_drbg, mut s.entropy)!
630 mut ret := 0
631 ret = C.mbedtls_ssl_config_defaults(&s.conf, C.MBEDTLS_SSL_IS_CLIENT,
632 C.MBEDTLS_SSL_TRANSPORT_STREAM, C.MBEDTLS_SSL_PRESET_DEFAULT)
633 if ret != 0 {
634 return error_with_code('net.mbedtls SSLConn.init, mbedtls_ssl_config_defaults failed to set SSL configuration ret: ${ret}',
635 ret)
636 }
637 $if trace_mbedtls_timeouts ? {
638 dump(s.read_timeout)
639 }
640 s.set_read_timeout(s.read_timeout)
641
642 unsafe {
643 C.mbedtls_ssl_conf_rng(&s.conf, C.mbedtls_ctr_drbg_random, &s.ctr_drbg)
644 }
645
646 // Advertise ALPN protocols (e.g. ['h2', 'http/1.1']) when requested.
647 // mbedtls expects a NUL-terminated array of NUL-terminated C strings, and
648 // keeps the pointer without copying, so both the array and the backing
649 // strings must outlive the config. The strings live in s.config; the array
650 // is allocated here and freed in shutdown().
651 if s.config.alpn_protocols.len > 0 {
652 n := s.config.alpn_protocols.len
653 s.alpn_list = unsafe { &&char(C.malloc(isize((n + 1) * int(sizeof(voidptr))))) }
654 if s.alpn_list == unsafe { nil } {
655 return error('net.mbedtls SSLConn.init, failed to allocate ALPN list')
656 }
657 unsafe {
658 for i, proto in s.config.alpn_protocols {
659 s.alpn_list[i] = &char(proto.str)
660 }
661 s.alpn_list[n] = &char(0)
662 }
663 ret = C.mbedtls_ssl_conf_alpn_protocols(&s.conf, voidptr(s.alpn_list))
664 if ret != 0 {
665 return error_with_code('net.mbedtls SSLConn.init, mbedtls_ssl_conf_alpn_protocols failed ret: ${ret}',
666 ret)
667 }
668 }
669 if s.config.verify != '' || s.config.cert != '' || s.config.cert_key != '' {
670 s.certs = &SSLCerts{}
671 C.mbedtls_x509_crt_init(&s.certs.cacert)
672 C.mbedtls_x509_crt_init(&s.certs.client_cert)
673 C.mbedtls_pk_init(&s.certs.client_key)
674 }
675
676 if s.config.in_memory_verification {
677 if s.config.verify != '' {
678 ret = C.mbedtls_x509_crt_parse(&s.certs.cacert, s.config.verify.str,
679
680 s.config.verify.len + 1)
681 }
682 if s.config.cert != '' {
683 ret = C.mbedtls_x509_crt_parse(&s.certs.client_cert, s.config.cert.str,
684
685 s.config.cert.len + 1)
686 }
687 if s.config.cert_key != '' {
688 unsafe {
689 ret = C.mbedtls_pk_parse_key(&s.certs.client_key, s.config.cert_key.str,
690
691 s.config.cert_key.len + 1, 0, 0, C.mbedtls_ctr_drbg_random, &s.ctr_drbg)
692 }
693 }
694 } else {
695 if s.config.verify != '' {
696 ret = C.mbedtls_x509_crt_parse_file(&s.certs.cacert, &char(s.config.verify.str))
697 }
698 if s.config.cert != '' {
699 ret = C.mbedtls_x509_crt_parse_file(&s.certs.client_cert, &char(s.config.cert.str))
700 }
701 if s.config.cert_key != '' {
702 unsafe {
703 ret = C.mbedtls_pk_parse_keyfile(&s.certs.client_key, &char(s.config.cert_key.str),
704 0, C.mbedtls_ctr_drbg_random, &s.ctr_drbg)
705 }
706 }
707 }
708 if ret < 0 {
709 return error_with_code('net.mbedtls SSLConn.init, failed to set certificates, ret: ${ret}',
710 ret)
711 }
712
713 if unsafe { s.certs != nil } {
714 C.mbedtls_ssl_conf_ca_chain(&s.conf, &s.certs.cacert, 0)
715 C.mbedtls_ssl_conf_own_cert(&s.conf, &s.certs.client_cert, &s.certs.client_key)
716 }
717
718 if s.config.validate {
719 C.mbedtls_ssl_conf_authmode(&s.conf, C.MBEDTLS_SSL_VERIFY_REQUIRED)
720 } else {
721 C.mbedtls_ssl_conf_authmode(&s.conf, C.MBEDTLS_SSL_VERIFY_OPTIONAL)
722 }
723
724 ret = C.mbedtls_ssl_setup(&s.ssl, &s.conf)
725 if ret != 0 {
726 return error_with_code('net.mbedtls SSLConn.init, mbedtls_ssl_setup failed to setup SSL connection ret: ${ret}',
727 ret)
728 }
729}
730
731// connect sets up an ssl connection on an existing TCP connection
732pub fn (mut s SSLConn) connect(mut tcp_conn net.TcpConn, hostname string) ! {
733 $if trace_ssl ? {
734 eprintln('${@METHOD} hostname: ${hostname}')
735 }
736 if s.opened {
737 return error('net.mbedtls SSLConn.connect, ssl connection was already open')
738 }
739 s.handle = tcp_conn.sock.handle
740 s.set_read_timeout(tcp_conn.read_timeout())
741 mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
742 if ret != 0 {
743 return error_with_code('net.mbedtls SSLConn.connect, mbedtls_ssl_set_hostname failed to set hostname',
744 ret)
745 }
746 s.server_fd.fd = s.handle
747 C.mbedtls_ssl_set_bio(&s.ssl, &s.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
748 C.mbedtls_net_recv_timeout)
749 ret = C.mbedtls_ssl_handshake(&s.ssl)
750 if ret != 0 {
751 return error_with_code('net.mbedtls SSLConn.connect, mbedtls_ssl_handshake failed 2; ret: ${ret}',
752 ret)
753 }
754 s.opened = true
755}
756
757// dial opens an ssl connection on hostname:port
758pub fn (mut s SSLConn) dial(hostname string, port int) ! {
759 $if trace_ssl ? {
760 eprintln('${@METHOD} hostname: ${hostname} | port: ${port}')
761 }
762 if s.opened {
763 return error('net.mbedtls SSLConn.dial, the ssl connection was already open')
764 }
765 mut connected := false
766 defer {
767 if !connected {
768 if unsafe { s.certs != nil } {
769 C.mbedtls_x509_crt_free(&s.certs.cacert)
770 C.mbedtls_x509_crt_free(&s.certs.client_cert)
771 C.mbedtls_pk_free(&s.certs.client_key)
772 s.certs = unsafe { nil }
773 }
774 C.mbedtls_net_free(&s.server_fd)
775 C.mbedtls_ssl_free(&s.ssl)
776 C.mbedtls_ssl_config_free(&s.conf)
777 free_rng(mut s.ctr_drbg, mut s.entropy)
778 s.handle = 0
779 s.owns_socket = false
780 }
781 }
782 s.owns_socket = true
783
784 mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
785 if ret != 0 {
786 return error_with_code('net.mbedtls SSLConn.dial, failed to set hostname', ret)
787 }
788
789 port_str := port.str()
790 ret = C.mbedtls_net_connect(&s.server_fd, &char(hostname.str), &char(port_str.str),
791 C.MBEDTLS_NET_PROTO_TCP)
792 if ret != 0 {
793 return error_with_code('net.mbedtls SSLConn.dial, failed to connect to host', ret)
794 }
795 C.mbedtls_ssl_set_bio(&s.ssl, &s.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
796 C.mbedtls_net_recv_timeout)
797 s.handle = s.server_fd.fd
798 ret = C.mbedtls_ssl_handshake(&s.ssl)
799 if ret != 0 {
800 return error_with_code('net.mbedtls SSLConn.dial, mbedtls_ssl_handshake failed 3; ret: ${ret}',
801 ret)
802 }
803 s.opened = true
804 connected = true
805}
806
807// addr retrieves the local ip address and port number for this connection
808pub fn (s &SSLConn) addr() !net.Addr {
809 return net.addr_from_socket_handle(s.handle)
810}
811
812// peer_addr retrieves the ip address and port number used by the peer
813pub fn (s &SSLConn) peer_addr() !net.Addr {
814 return net.peer_addr_from_socket_handle(s.handle)
815}
816
817// socket_read_into_ptr reads `len` bytes into `buf`
818pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) !int {
819 mut res := 0
820 $if trace_ssl ? {
821 defer(fn) {
822 if len > 0 {
823 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) }}`')
824 }
825 }
826 }
827
828 deadline := ssl_timeout_deadline(s.duration)
829 // s.wait_for_read(deadline - time.now())!
830 for {
831 res = C.mbedtls_ssl_read(&s.ssl, buf_ptr, len)
832 if res > 0 {
833 return res
834 } else if res == 0 {
835 $if trace_ssl ? {
836 eprintln('${@METHOD} ---> res: io.Eof')
837 }
838 return io.Eof{}
839 } else {
840 match res {
841 C.MBEDTLS_ERR_SSL_WANT_READ {
842 s.wait_for_read(ssl_remaining_timeout(deadline)) or {
843 $if trace_ssl ? {
844 eprintln('${@METHOD} ---> res: ${err}, C.MBEDTLS_ERR_SSL_WANT_READ')
845 }
846 return err
847 }
848 }
849 C.MBEDTLS_ERR_SSL_WANT_WRITE {
850 s.wait_for_write(ssl_remaining_timeout(deadline)) or {
851 $if trace_ssl ? {
852 eprintln('${@METHOD} ---> res: ${err}, C.MBEDTLS_ERR_SSL_WANT_WRITE')
853 }
854 return err
855 }
856 }
857 C.MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET {
858 // TLS 1.3 servers can deliver tickets asynchronously while the
859 // connection is otherwise healthy. Keep reading application data.
860 continue
861 }
862 C.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY {
863 $if trace_ssl ? {
864 eprintln('${@METHOD} ---> res: 0 C.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY')
865 }
866 return 0
867 }
868 C.MBEDTLS_ERR_SSL_TIMEOUT {
869 $if trace_ssl ? {
870 eprintln('${@METHOD} ---> res: C.MBEDTLS_ERR_SSL_TIMEOUT')
871 }
872 return error_with_code('net.mbedtls SSLConn.socket_read_into_ptr, did not receive any data within ${s.read_timeout.milliseconds()}ms. Use conn.set_read_timeout(...) to increase the timeout',
873 res)
874 }
875 else {
876 $if trace_ssl ? {
877 eprintln('${@METHOD} ---> res: could not read using SSL')
878 }
879 return error_with_code('net.mbedtls SSLConn.socket_read_into_ptr, could not read using SSL',
880 res)
881 }
882 }
883 }
884 }
885 // Dead code, just to satisfy the compiler:
886 return error('net.mbedtls SSLConn.socket_read_into_ptr, unknown error')
887}
888
889// read reads data from the ssl connection into `buffer`
890pub fn (mut s SSLConn) read(mut buffer []u8) !int {
891 $if trace_ssl ? {
892 eprintln('${@METHOD} buffer.len: ${buffer.len}')
893 }
894 return s.socket_read_into_ptr(&u8(buffer.data), buffer.len)
895}
896
897// write_ptr writes `len` bytes from `bytes` to the ssl connection
898pub fn (mut s SSLConn) write_ptr(bytes &u8, len int) !int {
899 mut total_sent := 0
900 $if trace_ssl ? {
901 defer(fn) {
902 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-=-=-=-')
903 }
904 }
905
906 s.last_write_sent = 0
907 deadline := ssl_timeout_deadline(s.duration)
908 unsafe {
909 mut ptr_base := bytes
910 for total_sent < len {
911 ptr := ptr_base + total_sent
912 remaining := len - total_sent
913 mut sent := C.mbedtls_ssl_write(&s.ssl, ptr, remaining)
914 if sent <= 0 {
915 // The write did not fully complete; a retryable error can leave a
916 // record partially flushed, so the sent count is no longer
917 // provable. Mark it indeterminate (a later full success below
918 // resets it to the exact length).
919 s.last_write_sent = -1
920 match sent {
921 C.MBEDTLS_ERR_SSL_WANT_READ {
922 s.wait_for_read(ssl_remaining_timeout(deadline))!
923 continue
924 }
925 C.MBEDTLS_ERR_SSL_WANT_WRITE {
926 s.wait_for_write(ssl_remaining_timeout(deadline))!
927 continue
928 }
929 else {
930 $if trace_ssl ? {
931 eprintln('${@METHOD} ---> res: could not write SSL, sent: ${sent}')
932 }
933 return error_with_code('net.mbedtls SSLConn.write_ptr, could not write using SSL',
934 sent)
935 }
936 }
937 }
938 total_sent += sent
939 s.last_write_sent = total_sent
940 }
941 }
942 return total_sent
943}
944
945// write writes data from `bytes` to the ssl connection
946pub fn (mut s SSLConn) write(bytes []u8) !int {
947 return s.write_ptr(&u8(bytes.data), bytes.len)
948}
949
950// write_string writes a string to the ssl connection
951pub fn (mut s SSLConn) write_string(str string) !int {
952 $if trace_ssl ? {
953 eprintln('${@METHOD} str: ${str}')
954 }
955 return s.write_ptr(str.str, str.len)
956}
957
958// Select waits for an io operation (specified by parameter `test`) to be available
959fn select(handle int, test Select, timeout time.Duration) !bool {
960 $if trace_ssl ? {
961 eprintln('${@METHOD} handle: ${handle}, timeout: ${timeout}')
962 }
963 set := C.fd_set{}
964 C.FD_ZERO(&set)
965 C.FD_SET(handle, &set)
966
967 is_infinite := timeout <= 0 || timeout == net.infinite_timeout
968 deadline := ssl_timeout_deadline(timeout)
969 mut remaining_time := if is_infinite { i64(0) } else { timeout.milliseconds() }
970 for is_infinite || remaining_time > 0 {
971 seconds := remaining_time / 1000
972 microseconds := (remaining_time % 1000) * 1000
973
974 tt := C.timeval{
975 tv_sec: u64(seconds)
976 tv_usec: u64(microseconds)
977 }
978 timeval_timeout := if is_infinite { &C.timeval(unsafe { nil }) } else { &tt }
979
980 mut res := -1
981 match test {
982 .read {
983 res = net.socket_error(C.select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))!
984 }
985 .write {
986 res = net.socket_error(C.select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))!
987 }
988 .except {
989 res = net.socket_error(C.select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))!
990 }
991 }
992
993 if res < 0 {
994 if C.errno == C.EINTR {
995 // errno is 4, Spurious wakeup from signal, keep waiting
996 if !is_infinite {
997 remaining_time = ssl_remaining_timeout(deadline).milliseconds()
998 }
999 continue
1000 }
1001 cerr := C.errno
1002 return error_with_code('net.mbedtls select, failed, res: ${res}', cerr)
1003 } else if res == 0 {
1004 return net.err_timed_out
1005 }
1006
1007 res = C.FD_ISSET(handle, &set)
1008 $if trace_ssl ? {
1009 eprintln('${@METHOD} ---> res: ${res}')
1010 }
1011 return res != 0
1012 }
1013
1014 return net.err_timed_out
1015}
1016
1017// wait_for wraps the common wait code
1018fn wait_for(handle int, what Select, timeout time.Duration) ! {
1019 ready := select(handle, what, timeout)!
1020 if ready {
1021 return
1022 }
1023
1024 return net.err_timed_out
1025}
1026
1027// wait_for_write waits for a write io operation to be available
1028fn (mut s SSLConn) wait_for_write(timeout time.Duration) ! {
1029 return wait_for(s.handle, .write, timeout)
1030}
1031
1032// wait_for_read waits for a read io operation to be available
1033fn (mut s SSLConn) wait_for_read(timeout time.Duration) ! {
1034 return wait_for(s.handle, .read, timeout)
1035}
1036