997 lines
30 KiB
V
997 lines
30 KiB
V
module mbedtls
|
|
|
|
import io
|
|
import net
|
|
import time
|
|
|
|
const mbedtls_client_read_timeout_ms = $d('mbedtls_client_read_timeout_ms', 10_000)
|
|
const mbedtls_server_read_timeout_ms = $d('mbedtls_server_read_timeout_ms', 41_000)
|
|
const default_mbedtls_client_read_timeout = mbedtls_client_read_timeout_ms * time.millisecond
|
|
const default_mbedtls_server_read_timeout = mbedtls_server_read_timeout_ms * time.millisecond
|
|
|
|
fn init_rng(mut ctr_drbg C.mbedtls_ctr_drbg_context, mut entropy C.mbedtls_entropy_context) ! {
|
|
$if trace_ssl ? {
|
|
eprintln(@METHOD)
|
|
}
|
|
C.mbedtls_ctr_drbg_init(&ctr_drbg)
|
|
C.mbedtls_entropy_init(&entropy)
|
|
ret := C.mbedtls_ctr_drbg_seed(&ctr_drbg, C.mbedtls_entropy_func, &entropy, 0, 0)
|
|
if ret != 0 {
|
|
C.mbedtls_ctr_drbg_free(&ctr_drbg)
|
|
C.mbedtls_entropy_free(&entropy)
|
|
return error_with_code('net.mbedtls init_rng, failed to seed ssl context: ${ret}', ret)
|
|
}
|
|
// C.mbedtls_debug_set_threshold(5)
|
|
}
|
|
|
|
fn free_rng(mut ctr_drbg C.mbedtls_ctr_drbg_context, mut entropy C.mbedtls_entropy_context) {
|
|
C.mbedtls_ctr_drbg_free(&ctr_drbg)
|
|
C.mbedtls_entropy_free(&entropy)
|
|
}
|
|
|
|
// SSLCerts represents a pair of CA and client certificates + key
|
|
pub struct SSLCerts {
|
|
pub mut:
|
|
cacert C.mbedtls_x509_crt
|
|
client_cert C.mbedtls_x509_crt
|
|
client_key C.mbedtls_pk_context
|
|
}
|
|
|
|
// new_sslcerts initializes and returns a pair of SSL certificates and key
|
|
pub fn new_sslcerts() &SSLCerts {
|
|
mut certs := SSLCerts{}
|
|
C.mbedtls_x509_crt_init(&certs.cacert)
|
|
C.mbedtls_x509_crt_init(&certs.client_cert)
|
|
C.mbedtls_pk_init(&certs.client_key)
|
|
return &certs
|
|
}
|
|
|
|
// new_sslcerts_in_memory creates a pair of SSL certificates, given their contents (not paths).
|
|
pub fn new_sslcerts_in_memory(verify string, cert string, cert_key string) !&SSLCerts {
|
|
mut ctr_drbg := C.mbedtls_ctr_drbg_context{}
|
|
mut entropy := C.mbedtls_entropy_context{}
|
|
init_rng(mut ctr_drbg, mut entropy)!
|
|
defer {
|
|
free_rng(mut ctr_drbg, mut entropy)
|
|
}
|
|
return new_sslcerts_in_memory_with_rng(verify, cert, cert_key, &ctr_drbg)
|
|
}
|
|
|
|
fn new_sslcerts_in_memory_with_rng(verify string, cert string, cert_key string, rng &C.mbedtls_ctr_drbg_context) !&SSLCerts {
|
|
mut certs := new_sslcerts()
|
|
if verify != '' {
|
|
ret := C.mbedtls_x509_crt_parse(&certs.cacert, verify.str, verify.len + 1)
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_x509_crt_parse error 1 ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
if cert != '' {
|
|
ret := C.mbedtls_x509_crt_parse(&certs.client_cert, cert.str, cert.len + 1)
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_x509_crt_parse error 2 ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
if cert_key != '' {
|
|
unsafe {
|
|
ret := C.mbedtls_pk_parse_key(&certs.client_key, cert_key.str, cert_key.len + 1, 0, 0,
|
|
C.mbedtls_ctr_drbg_random, rng)
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_in_memory, mbedtls_pk_parse_key error ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
}
|
|
return certs
|
|
}
|
|
|
|
// new_sslcerts_from_file creates a new pair of SSL certificates, given their paths on the filesystem.
|
|
pub fn new_sslcerts_from_file(verify string, cert string, cert_key string) !&SSLCerts {
|
|
mut ctr_drbg := C.mbedtls_ctr_drbg_context{}
|
|
mut entropy := C.mbedtls_entropy_context{}
|
|
init_rng(mut ctr_drbg, mut entropy)!
|
|
defer {
|
|
free_rng(mut ctr_drbg, mut entropy)
|
|
}
|
|
return new_sslcerts_from_file_with_rng(verify, cert, cert_key, &ctr_drbg)
|
|
}
|
|
|
|
fn new_sslcerts_from_file_with_rng(verify string, cert string, cert_key string, rng &C.mbedtls_ctr_drbg_context) !&SSLCerts {
|
|
mut certs := new_sslcerts()
|
|
if verify != '' {
|
|
ret := C.mbedtls_x509_crt_parse_file(&certs.cacert, &char(verify.str))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_x509_crt_parse_file error 1 ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
if cert != '' {
|
|
ret := C.mbedtls_x509_crt_parse_file(&certs.client_cert, &char(cert.str))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_x509_crt_parse_file error 2 ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
if cert_key != '' {
|
|
unsafe {
|
|
ret := C.mbedtls_pk_parse_keyfile(&certs.client_key, &char(cert_key.str), 0,
|
|
C.mbedtls_ctr_drbg_random, rng)
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls new_sslcerts_from_file, mbedtls_pk_parse_keyfile error ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
}
|
|
return certs
|
|
}
|
|
|
|
// cleanup frees the SSL certificates
|
|
pub fn (mut c SSLCerts) cleanup() {
|
|
C.mbedtls_x509_crt_free(&c.cacert)
|
|
C.mbedtls_x509_crt_free(&c.client_cert)
|
|
C.mbedtls_pk_free(&c.client_key)
|
|
}
|
|
|
|
// SSLConn is the current connection
|
|
pub struct SSLConn {
|
|
pub:
|
|
config SSLConnectConfig
|
|
pub mut:
|
|
server_fd C.mbedtls_net_context
|
|
ssl C.mbedtls_ssl_context
|
|
conf C.mbedtls_ssl_config
|
|
certs &SSLCerts = unsafe { nil }
|
|
ctr_drbg C.mbedtls_ctr_drbg_context
|
|
entropy C.mbedtls_entropy_context
|
|
handle int
|
|
duration time.Duration
|
|
opened bool
|
|
ip string
|
|
read_timeout time.Duration
|
|
|
|
owns_socket bool
|
|
// alpn_list is a NUL-terminated C array of pointers to the protocol
|
|
// strings in config.alpn_protocols. mbedtls stores this pointer without
|
|
// copying, so it must outlive the SSL config; it is freed in shutdown().
|
|
alpn_list &&char = unsafe { nil }
|
|
// last_write_sent reports the most recent write_ptr's progress for retry
|
|
// decisions: 0 = provably nothing was sent (safe to replay), or -1 = the
|
|
// count is indeterminate because a failed/retryable write may have already
|
|
// flushed a record to the peer (TLS cannot prove zero). On full success it
|
|
// equals the bytes written.
|
|
last_write_sent int
|
|
}
|
|
|
|
// 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 }
|
|
ctr_drbg C.mbedtls_ctr_drbg_context
|
|
entropy C.mbedtls_entropy_context
|
|
opened bool
|
|
// alpn_list is a NUL-terminated C array of pointers to the protocol
|
|
// strings in config.alpn_protocols, advertised by accepted connections.
|
|
// It must outlive the SSL config and is freed in shutdown().
|
|
alpn_list &&char = unsafe { nil }
|
|
// 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 } {
|
|
l.certs.cleanup()
|
|
}
|
|
C.mbedtls_ssl_free(&l.ssl)
|
|
C.mbedtls_ssl_config_free(&l.conf)
|
|
free_rng(mut l.ctr_drbg, mut l.entropy)
|
|
if l.alpn_list != unsafe { nil } {
|
|
unsafe {
|
|
C.free(l.alpn_list)
|
|
l.alpn_list = nil
|
|
}
|
|
}
|
|
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('net.mbedtls SSLListener.init, no certificate or key provided')
|
|
}
|
|
if l.config.validate && l.config.verify == '' {
|
|
return error('net.mbedtls SSLListener.init, no root CA provided')
|
|
}
|
|
C.mbedtls_net_init(&l.server_fd)
|
|
C.mbedtls_ssl_init(&l.ssl)
|
|
C.mbedtls_ssl_config_init(&l.conf)
|
|
init_rng(mut l.ctr_drbg, mut l.entropy)!
|
|
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, &l.ctr_drbg)
|
|
}
|
|
|
|
mut ret := 0
|
|
|
|
if l.config.in_memory_verification {
|
|
l.certs = new_sslcerts_in_memory_with_rng(l.config.verify, l.config.cert,
|
|
l.config.cert_key, &l.ctr_drbg) or {
|
|
return error('net.mbedtls SSLListener.init, cert failure 1, err: ${err}')
|
|
}
|
|
} else {
|
|
l.certs = new_sslcerts_from_file_with_rng(l.config.verify, l.config.cert,
|
|
l.config.cert_key, &l.ctr_drbg) or {
|
|
return error('net.mbedtls SSLListener.init, cert failure 2, err: ${err}')
|
|
}
|
|
}
|
|
|
|
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("net.mbedtls SSLListener.init, mbedtls_net_bind can't bind to ${l.saddr} error ret: ${ret}",
|
|
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("net.mbedtls SSLListener.init, mbedtls_ssl_config_defaults can't set config defaults ret: ${ret}",
|
|
ret)
|
|
}
|
|
listener_read_timeout := ssl_listener_read_timeout(l.config)
|
|
$if trace_mbedtls_timeouts ? {
|
|
dump(listener_read_timeout)
|
|
}
|
|
C.mbedtls_ssl_conf_read_timeout(&l.conf, ssl_read_timeout_ms(listener_read_timeout))
|
|
|
|
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("net.mbedtls SSLListener.init, mbedtls_ssl_conf_own_cert can't load certificate ret: ${ret}",
|
|
ret)
|
|
}
|
|
|
|
// Advertise ALPN protocols for accepted connections to select from.
|
|
// See the matching client-side logic in SSLConn.init for lifetime notes.
|
|
if l.config.alpn_protocols.len > 0 {
|
|
n := l.config.alpn_protocols.len
|
|
l.alpn_list = unsafe { &&char(C.malloc(isize((n + 1) * int(sizeof(voidptr))))) }
|
|
if l.alpn_list == unsafe { nil } {
|
|
return error('net.mbedtls SSLListener.init, failed to allocate ALPN list')
|
|
}
|
|
unsafe {
|
|
for i, proto in l.config.alpn_protocols {
|
|
l.alpn_list[i] = &char(proto.str)
|
|
}
|
|
l.alpn_list[n] = &char(0)
|
|
}
|
|
ret = C.mbedtls_ssl_conf_alpn_protocols(&l.conf, voidptr(l.alpn_list))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls SSLListener.init, mbedtls_ssl_conf_alpn_protocols failed ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
|
|
ret = C.mbedtls_ssl_setup(&l.ssl, &l.conf)
|
|
if ret != 0 {
|
|
return error_with_code("net.mbedtls SSLListener.init, mbedtls_ssl_setup can't setup ssl ret: ${ret}",
|
|
ret)
|
|
}
|
|
|
|
if get_cert_callback := l.config.get_certificate {
|
|
l.init_sni(get_cert_callback)
|
|
}
|
|
}
|
|
|
|
// setup SNI callback
|
|
fn (mut l SSLListener) init_sni(get_cert_callback fn (mut SSLListener, string) !&SSLCerts) {
|
|
$if trace_ssl ? {
|
|
eprintln(@METHOD)
|
|
}
|
|
C.mbedtls_ssl_conf_sni(&l.conf, fn [get_cert_callback, mut l] (p_info voidptr, ssl &C.mbedtls_ssl_context, name &char, lng int) int {
|
|
host := unsafe { name.vstring_literal_with_len(lng) }
|
|
if certs := get_cert_callback(mut l, host) {
|
|
return C.mbedtls_ssl_set_hs_own_cert(ssl, &certs.client_cert, &certs.client_key)
|
|
} else {
|
|
return -1
|
|
}
|
|
}, &l.conf)
|
|
}
|
|
|
|
// accepts a new connection and returns a SSLConn of the connected client
|
|
pub fn (mut l SSLListener) accept() !&SSLConn {
|
|
mut conn := l.accept_tcp_connection()!
|
|
|
|
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 {
|
|
conn.shutdown() or {}
|
|
return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_setup SSL setup failed ret: ${ret}',
|
|
ret)
|
|
}
|
|
|
|
C.mbedtls_ssl_set_bio(&conn.ssl, &conn.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
|
|
C.mbedtls_net_recv_timeout)
|
|
conn.server_handshake(net.infinite_timeout)!
|
|
return conn
|
|
}
|
|
|
|
fn (mut l SSLListener) accept_tcp_connection() !&SSLConn {
|
|
mut conn := &SSLConn{
|
|
config: l.config
|
|
duration: ssl_listener_read_timeout(l.config)
|
|
read_timeout: ssl_listener_read_timeout(l.config)
|
|
opened: true
|
|
}
|
|
ip := [16]u8{}
|
|
iplen := usize(0)
|
|
|
|
ret := C.mbedtls_net_accept(&l.server_fd, &conn.server_fd, &ip, 16, &iplen)
|
|
if ret != 0 {
|
|
return error_with_code("net.mbedtls SSLListener.accept, mbedtls_net_accept can't accept connection ret: ${ret}",
|
|
ret)
|
|
}
|
|
conn.handle = conn.server_fd.fd
|
|
conn.owns_socket = true
|
|
if iplen == 4 {
|
|
conn.ip = '${ip[0]}.${ip[1]}.${ip[2]}.${ip[3]}'
|
|
}
|
|
return conn
|
|
}
|
|
|
|
fn (mut conn SSLConn) server_handshake(timeout time.Duration) ! {
|
|
deadline := ssl_timeout_deadline(timeout)
|
|
mut ret := C.mbedtls_ssl_handshake(&conn.ssl)
|
|
for ret != 0 {
|
|
match ret {
|
|
C.MBEDTLS_ERR_SSL_WANT_READ {
|
|
conn.wait_for_read(ssl_remaining_timeout(deadline)) or {
|
|
conn.shutdown() or {}
|
|
return err
|
|
}
|
|
}
|
|
C.MBEDTLS_ERR_SSL_WANT_WRITE {
|
|
conn.wait_for_write(ssl_remaining_timeout(deadline)) or {
|
|
conn.shutdown() or {}
|
|
return err
|
|
}
|
|
}
|
|
else {
|
|
conn.shutdown() or {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} shutdown ---> res: ${err}')
|
|
}
|
|
}
|
|
return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_handshake failed 1; handshake ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
|
|
ret = C.mbedtls_ssl_handshake(&conn.ssl)
|
|
}
|
|
}
|
|
|
|
// accept_with_timeout waits up to `timeout` for a new client before accepting it.
|
|
pub fn (mut l SSLListener) accept_with_timeout(timeout time.Duration) !&SSLConn {
|
|
return l.accept_with_timeouts(timeout, timeout)
|
|
}
|
|
|
|
// accept_with_timeouts waits up to `accept_timeout` for a new client, then
|
|
// waits up to `handshake_timeout` for the TLS server handshake to complete.
|
|
pub fn (mut l SSLListener) accept_with_timeouts(accept_timeout time.Duration, handshake_timeout time.Duration) !&SSLConn {
|
|
wait_for(l.server_fd.fd, .read, accept_timeout)!
|
|
mut conn := l.accept_tcp_connection()!
|
|
|
|
C.mbedtls_ssl_init(&conn.ssl)
|
|
C.mbedtls_ssl_config_init(&conn.conf)
|
|
net.set_blocking(conn.handle, false) or {
|
|
conn.shutdown() or {}
|
|
return err
|
|
}
|
|
ret := C.mbedtls_ssl_setup(&conn.ssl, &l.conf)
|
|
if ret != 0 {
|
|
conn.shutdown() or {}
|
|
return error_with_code('net.mbedtls SSLListener.accept, mbedtls_ssl_setup SSL setup failed ret: ${ret}',
|
|
ret)
|
|
}
|
|
|
|
C.v_mbedtls_ssl_set_bio_nonblocking(&conn.ssl, &conn.server_fd)
|
|
conn.server_handshake(handshake_timeout)!
|
|
net.set_blocking(conn.handle, true) or {
|
|
conn.shutdown() or {}
|
|
return err
|
|
}
|
|
C.mbedtls_ssl_set_bio(&conn.ssl, &conn.server_fd, C.mbedtls_net_send, C.mbedtls_net_recv,
|
|
C.mbedtls_net_recv_timeout)
|
|
return conn
|
|
}
|
|
|
|
@[params]
|
|
pub struct SSLConnectConfig {
|
|
pub:
|
|
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
|
|
|
|
get_certificate ?fn (mut SSLListener, string) !&SSLCerts
|
|
|
|
read_timeout time.Duration = default_mbedtls_client_read_timeout // the SSL client read timeout
|
|
|
|
alpn_protocols []string // the list of ALPN protocols to advertise, e.g. ['h2', 'http/1.1']; empty means no ALPN extension is sent
|
|
}
|
|
|
|
fn ssl_read_timeout_ms(timeout time.Duration) u32 {
|
|
if timeout <= 0 || timeout == net.infinite_timeout {
|
|
return 0
|
|
}
|
|
timeout_ms := timeout.milliseconds()
|
|
if timeout_ms > i64(max_u32) {
|
|
return max_u32
|
|
}
|
|
return u32(timeout_ms)
|
|
}
|
|
|
|
fn ssl_listener_read_timeout(config SSLConnectConfig) time.Duration {
|
|
if config.read_timeout == default_mbedtls_client_read_timeout {
|
|
return default_mbedtls_server_read_timeout
|
|
}
|
|
return config.read_timeout
|
|
}
|
|
|
|
fn ssl_timeout_deadline(timeout time.Duration) time.Time {
|
|
if timeout <= 0 || timeout == net.infinite_timeout {
|
|
return time.unix(0)
|
|
}
|
|
return time.now().add(timeout)
|
|
}
|
|
|
|
fn ssl_remaining_timeout(deadline time.Time) time.Duration {
|
|
if deadline.unix() == 0 {
|
|
return net.infinite_timeout
|
|
}
|
|
remaining := deadline - time.now()
|
|
if remaining <= 0 {
|
|
return time.nanosecond
|
|
}
|
|
return remaining
|
|
}
|
|
|
|
// read_timeout returns the current SSL read timeout.
|
|
pub fn (s &SSLConn) read_timeout() time.Duration {
|
|
return s.read_timeout
|
|
}
|
|
|
|
// set_read_timeout sets the SSL read timeout for subsequent operations.
|
|
pub fn (mut s SSLConn) set_read_timeout(timeout time.Duration) {
|
|
s.read_timeout = timeout
|
|
s.duration = timeout
|
|
C.mbedtls_ssl_conf_read_timeout(&s.conf, ssl_read_timeout_ms(timeout))
|
|
}
|
|
|
|
// 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
|
|
duration: config.read_timeout
|
|
read_timeout: config.read_timeout
|
|
}
|
|
conn.init()!
|
|
return conn
|
|
}
|
|
|
|
// Select operation
|
|
enum Select {
|
|
read
|
|
write
|
|
except
|
|
}
|
|
|
|
// close terminates the ssl connection and does cleanup
|
|
pub fn (mut s SSLConn) close() ! {
|
|
s.shutdown()!
|
|
}
|
|
|
|
// shutdown terminates the ssl connection and does cleanup
|
|
pub fn (mut s SSLConn) shutdown() ! {
|
|
$if trace_ssl ? {
|
|
eprintln(@METHOD)
|
|
}
|
|
if !s.opened {
|
|
return error('net.mbedtls SSLConn.shutdown, connection was 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)
|
|
free_rng(mut s.ctr_drbg, mut s.entropy)
|
|
if s.alpn_list != unsafe { nil } {
|
|
unsafe {
|
|
C.free(s.alpn_list)
|
|
s.alpn_list = nil
|
|
}
|
|
}
|
|
if s.owns_socket {
|
|
net.shutdown(s.handle)
|
|
net.close(s.handle)!
|
|
}
|
|
}
|
|
|
|
// negotiated_alpn returns the ALPN protocol selected during the TLS
|
|
// handshake (e.g. 'h2' or 'http/1.1'), or an empty string if no protocol
|
|
// was negotiated.
|
|
pub fn (s &SSLConn) negotiated_alpn() string {
|
|
// mbedtls_ssl_get_alpn_protocol returns a `const char *`; cast away const
|
|
// for V, since we only read from it (and copy it below).
|
|
p := &char(C.mbedtls_ssl_get_alpn_protocol(&s.ssl))
|
|
if p == unsafe { nil } {
|
|
return ''
|
|
}
|
|
return unsafe { cstring_to_vstring(p) }
|
|
}
|
|
|
|
// 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)
|
|
init_rng(mut s.ctr_drbg, mut s.entropy)!
|
|
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('net.mbedtls SSLConn.init, mbedtls_ssl_config_defaults failed to set SSL configuration ret: ${ret}',
|
|
ret)
|
|
}
|
|
$if trace_mbedtls_timeouts ? {
|
|
dump(s.read_timeout)
|
|
}
|
|
s.set_read_timeout(s.read_timeout)
|
|
|
|
unsafe {
|
|
C.mbedtls_ssl_conf_rng(&s.conf, C.mbedtls_ctr_drbg_random, &s.ctr_drbg)
|
|
}
|
|
|
|
// Advertise ALPN protocols (e.g. ['h2', 'http/1.1']) when requested.
|
|
// mbedtls expects a NUL-terminated array of NUL-terminated C strings, and
|
|
// keeps the pointer without copying, so both the array and the backing
|
|
// strings must outlive the config. The strings live in s.config; the array
|
|
// is allocated here and freed in shutdown().
|
|
if s.config.alpn_protocols.len > 0 {
|
|
n := s.config.alpn_protocols.len
|
|
s.alpn_list = unsafe { &&char(C.malloc(isize((n + 1) * int(sizeof(voidptr))))) }
|
|
if s.alpn_list == unsafe { nil } {
|
|
return error('net.mbedtls SSLConn.init, failed to allocate ALPN list')
|
|
}
|
|
unsafe {
|
|
for i, proto in s.config.alpn_protocols {
|
|
s.alpn_list[i] = &char(proto.str)
|
|
}
|
|
s.alpn_list[n] = &char(0)
|
|
}
|
|
ret = C.mbedtls_ssl_conf_alpn_protocols(&s.conf, voidptr(s.alpn_list))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls SSLConn.init, mbedtls_ssl_conf_alpn_protocols failed ret: ${ret}',
|
|
ret)
|
|
}
|
|
}
|
|
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, &s.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, &s.ctr_drbg)
|
|
}
|
|
}
|
|
}
|
|
if ret < 0 {
|
|
return error_with_code('net.mbedtls SSLConn.init, failed to set certificates, ret: ${ret}',
|
|
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('net.mbedtls SSLConn.init, mbedtls_ssl_setup failed to setup SSL connection ret: ${ret}',
|
|
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('net.mbedtls SSLConn.connect, ssl connection was already open')
|
|
}
|
|
s.handle = tcp_conn.sock.handle
|
|
s.set_read_timeout(tcp_conn.read_timeout())
|
|
mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls SSLConn.connect, mbedtls_ssl_set_hostname 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('net.mbedtls SSLConn.connect, mbedtls_ssl_handshake failed 2; ret: ${ret}',
|
|
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}')
|
|
}
|
|
if s.opened {
|
|
return error('net.mbedtls SSLConn.dial, the ssl connection was already open')
|
|
}
|
|
mut connected := false
|
|
defer {
|
|
if !connected {
|
|
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)
|
|
s.certs = unsafe { nil }
|
|
}
|
|
C.mbedtls_net_free(&s.server_fd)
|
|
C.mbedtls_ssl_free(&s.ssl)
|
|
C.mbedtls_ssl_config_free(&s.conf)
|
|
free_rng(mut s.ctr_drbg, mut s.entropy)
|
|
s.handle = 0
|
|
s.owns_socket = false
|
|
}
|
|
}
|
|
s.owns_socket = true
|
|
|
|
mut ret := C.mbedtls_ssl_set_hostname(&s.ssl, &char(hostname.str))
|
|
if ret != 0 {
|
|
return error_with_code('net.mbedtls SSLConn.dial, 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('net.mbedtls SSLConn.dial, 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('net.mbedtls SSLConn.dial, mbedtls_ssl_handshake failed 3; ret: ${ret}',
|
|
ret)
|
|
}
|
|
s.opened = true
|
|
connected = true
|
|
}
|
|
|
|
// addr retrieves the local ip address and port number for this connection
|
|
pub fn (s &SSLConn) addr() !net.Addr {
|
|
return net.addr_from_socket_handle(s.handle)
|
|
}
|
|
|
|
// 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(fn) {
|
|
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) }}`')
|
|
}
|
|
}
|
|
}
|
|
|
|
deadline := ssl_timeout_deadline(s.duration)
|
|
// s.wait_for_read(deadline - time.now())!
|
|
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 {
|
|
s.wait_for_read(ssl_remaining_timeout(deadline)) or {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: ${err}, C.MBEDTLS_ERR_SSL_WANT_READ')
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
C.MBEDTLS_ERR_SSL_WANT_WRITE {
|
|
s.wait_for_write(ssl_remaining_timeout(deadline)) or {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: ${err}, C.MBEDTLS_ERR_SSL_WANT_WRITE')
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
C.MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET {
|
|
// TLS 1.3 servers can deliver tickets asynchronously while the
|
|
// connection is otherwise healthy. Keep reading application data.
|
|
continue
|
|
}
|
|
C.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: 0 C.MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY')
|
|
}
|
|
return 0
|
|
}
|
|
C.MBEDTLS_ERR_SSL_TIMEOUT {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: C.MBEDTLS_ERR_SSL_TIMEOUT')
|
|
}
|
|
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',
|
|
res)
|
|
}
|
|
else {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: could not read using SSL')
|
|
}
|
|
return error_with_code('net.mbedtls SSLConn.socket_read_into_ptr, could not read using SSL',
|
|
res)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Dead code, just to satisfy the compiler:
|
|
return error('net.mbedtls SSLConn.socket_read_into_ptr, unknown error')
|
|
}
|
|
|
|
// 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(fn) {
|
|
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-=-=-=-')
|
|
}
|
|
}
|
|
|
|
s.last_write_sent = 0
|
|
deadline := ssl_timeout_deadline(s.duration)
|
|
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 {
|
|
// The write did not fully complete; a retryable error can leave a
|
|
// record partially flushed, so the sent count is no longer
|
|
// provable. Mark it indeterminate (a later full success below
|
|
// resets it to the exact length).
|
|
s.last_write_sent = -1
|
|
match sent {
|
|
C.MBEDTLS_ERR_SSL_WANT_READ {
|
|
s.wait_for_read(ssl_remaining_timeout(deadline))!
|
|
continue
|
|
}
|
|
C.MBEDTLS_ERR_SSL_WANT_WRITE {
|
|
s.wait_for_write(ssl_remaining_timeout(deadline))!
|
|
continue
|
|
}
|
|
else {
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: could not write SSL, sent: ${sent}')
|
|
}
|
|
return error_with_code('net.mbedtls SSLConn.write_ptr, could not write using SSL',
|
|
sent)
|
|
}
|
|
}
|
|
}
|
|
total_sent += sent
|
|
s.last_write_sent = total_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)
|
|
}
|
|
|
|
// 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)
|
|
|
|
is_infinite := timeout <= 0 || timeout == net.infinite_timeout
|
|
deadline := ssl_timeout_deadline(timeout)
|
|
mut remaining_time := if is_infinite { i64(0) } else { timeout.milliseconds() }
|
|
for is_infinite || remaining_time > 0 {
|
|
seconds := remaining_time / 1000
|
|
microseconds := (remaining_time % 1000) * 1000
|
|
|
|
tt := C.timeval{
|
|
tv_sec: u64(seconds)
|
|
tv_usec: u64(microseconds)
|
|
}
|
|
timeval_timeout := if is_infinite { &C.timeval(unsafe { nil }) } else { &tt }
|
|
|
|
mut res := -1
|
|
match test {
|
|
.read {
|
|
res = net.socket_error(C.select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))!
|
|
}
|
|
.write {
|
|
res = net.socket_error(C.select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))!
|
|
}
|
|
.except {
|
|
res = net.socket_error(C.select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))!
|
|
}
|
|
}
|
|
|
|
if res < 0 {
|
|
if C.errno == C.EINTR {
|
|
// errno is 4, Spurious wakeup from signal, keep waiting
|
|
if !is_infinite {
|
|
remaining_time = ssl_remaining_timeout(deadline).milliseconds()
|
|
}
|
|
continue
|
|
}
|
|
cerr := C.errno
|
|
return error_with_code('net.mbedtls select, failed, res: ${res}', cerr)
|
|
} else if res == 0 {
|
|
return net.err_timed_out
|
|
}
|
|
|
|
res = C.FD_ISSET(handle, &set)
|
|
$if trace_ssl ? {
|
|
eprintln('${@METHOD} ---> res: ${res}')
|
|
}
|
|
return res != 0
|
|
}
|
|
|
|
return net.err_timed_out
|
|
}
|
|
|
|
// wait_for wraps the common wait code
|
|
fn wait_for(handle int, what Select, timeout time.Duration) ! {
|
|
ready := select(handle, what, timeout)!
|
|
if ready {
|
|
return
|
|
}
|
|
|
|
return net.err_timed_out
|
|
}
|
|
|
|
// wait_for_write waits for a write io operation to be available
|
|
fn (mut s SSLConn) wait_for_write(timeout time.Duration) ! {
|
|
return wait_for(s.handle, .write, timeout)
|
|
}
|
|
|
|
// wait_for_read waits for a read io operation to be available
|
|
fn (mut s SSLConn) wait_for_read(timeout time.Duration) ! {
|
|
return wait_for(s.handle, .read, timeout)
|
|
}
|