1// TLS 1.2 and 1.3 over a TCP connection (std::net), client or server:2// Mbed TLS behind the compiler's src/support/tls.c, which a native program3// links only when it reaches this module (lib/<target>/tls.a; Mbed TLS is4// Apache-2.0, its notice in lib/<target>/mbedtls-LICENSE). ECDHE over5// X25519, P-256 and P-384, AES-GCM and ChaCha20-Poly1305, RSA and ECDSA6// certificates.7//8// A client trusts the certificate authorities in the PEM file9// `ALLOY_CA_FILE` names, when it is set; else the system's: on Linux its10// bundle (`SSL_CERT_FILE`, else the distributions' usual places), on11// Windows its chain engine and SSL policy, which fetch roots not yet12// needed and check revocation, on macOS its trust evaluation, which13// follows the Keychain. WebAssembly has none: on WASI every connect fails14// with Unsupported, and the web's requests go through the browser.1516import std::option;17import std::result;18import std::string;19import std::vector;20import std::dispose;21import std::process;22import std::time;23import std::net;2425extern al_tls_client(socket: i64, host: c_string) -> u64;26extern al_tls_server(27 socket: i64,28 chain: &[u8],29 chain_length: u64,30 key: &[u8],31 key_length: u6432) -> u64;33extern al_tls_handshake(session: u64) -> i32;34extern al_tls_problem(session: u64, buffer: &var [u8], capacity: u64) -> u64;35extern al_tls_read(session: u64, buffer: &var [u8], length: u64) -> i64;36extern al_tls_write(session: u64, bytes: &[u8], length: u64) -> i64;37extern al_tls_close(session: u64);3839// A session over a connection, which it owns: disposing it ends the40// session (telling the peer) and closes the connection.41exp type Tls : Disposable = struct {42 connection: Connection,43 session: u6444};4546// Why a session did not start.47exp type TlsError = enum {48 Certificate: String, // the server's certificate is not trusted for the host: why49 Handshake: String, // the handshake failed otherwise: why, when known50 Unsupported // no TLS here: WebAssembly51};5253// A server's certificate chain, its own certificate first, and its54// private key, as PEM text.55exp type Certificate = struct {56 exp chain: Vector<u8>,57 exp key: Vector<u8>58};5960exp fn Certificate::from_pem(chain: &[u8], key: &[u8]) -> Certificate {61 return Certificate { .chain = Vector<u8>::from(&chain), .key = Vector<u8>::from(&key) };62}6364// The handshake over the connection as its client, the server's65// certificate checked for the host.66exp fn Tls::connect(connection: Connection, host: &[u8]) -> Result<Tls, TlsError> {67 var tls = Tls::client(move connection, &host);68 if (tls.handshake() is ::Some |move error|) {69 tls.dispose();70 return ::Err(move error);71 }72 return ::Ok(move tls);73}7475// The handshake over the connection as its server, with the certificate:76// for tests and services. The client's certificate is not asked for.77exp fn Tls::accept(connection: Connection, certificate: &Certificate) -> Result<Tls, TlsError> {78 var tls = Tls { .connection = move connection, .session = 0 };79 if (target() != "wasi-wasm32" && target() != "web-wasm32") {80 const chain = &certificate.chain.view();81 const key = &certificate.key.view();82 tls.session = al_tls_server(83 tls.connection.handle(),84 &chain,85 chain.length(),86 &key,87 key.length()88 );89 }90 if (tls.handshake() is ::Some |move error|) {91 tls.dispose();92 return ::Err(move error);93 }94 return ::Ok(move tls);95}9697// A client's session over the connection, for the host, before its98// handshake: std::http keeps the connection where another task may shut99// it down until the session is disposed.100pub fn Tls::client(connection: Connection, host: &[u8]) -> Tls {101 var tls = Tls { .connection = move connection, .session = 0 };102 if (target() != "wasi-wasm32" && target() != "web-wasm32") {103 if (host.length() < 256) {104 var name: [u8 : 256] = [0 : 256];105 name[..host.length()] = host;106 tls.session = al_tls_client(tls.connection.handle(), &name[..host.length() + 1]);107 }108 }109 return move tls;110}111112// The handshake: None once done, else why it failed.113pub fn handshake(self tls: &var Tls) -> Option<TlsError> {114 if (target() == "wasi-wasm32" || target() == "web-wasm32") {115 return ::Some(::Unsupported);116 } else {117 if (tls.session == 0) {118 return ::Some(::Handshake(String::from(&"TLS cannot start")));119 }120 const outcome = al_tls_handshake(tls.session);121 if (outcome == 0) {122 return ::None;123 }124 var buffer: [u8 : 200] = [0 : 200];125 const length = al_tls_problem(tls.session, &var buffer[..], 200);126 var why = String::from(&buffer[..length]);127 if (outcome == 1) {128 return ::Some(::Certificate(move why));129 }130 return ::Some(::Handshake(move why));131 }132}133134// Reads what has arrived into the buffer, waiting for some; how many135// bytes, 0 when the peer ended the session or closed the connection, or136// after an error or a timeout.137exp fn read(self tls: &var Tls, buffer: &var [u8]) -> u64 {138 if (target() == "wasi-wasm32" || target() == "web-wasm32") {139 return 0;140 } else {141 const count = al_tls_read(tls.session, &var buffer, buffer.length());142 return if (count > 0) count to u64 else 0;143 }144}145146// As `read`, but 0 only when the peer ended the session or closed the147// connection, -1 after an error or a timeout.148pub fn read_or_fail(self tls: &var Tls, buffer: &var [u8]) -> i64 {149 if (target() == "wasi-wasm32" || target() == "web-wasm32") {150 return -1;151 } else {152 return al_tls_read(tls.session, &var buffer, buffer.length());153 }154}155156// Writes all the bytes; false when the session failed.157exp fn write(self tls: &var Tls, bytes: &[u8]) -> bool {158 if (target() == "wasi-wasm32" || target() == "web-wasm32") {159 return false;160 } else {161 var at: u64 = 0;162 while (at < bytes.length()) {163 const count = al_tls_write(tls.session, &bytes[at..], bytes.length() - at);164 if (count <= 0) {165 return false;166 }167 at += count to u64;168 }169 return true;170 }171}172173// The connection under the session: for its handle, or to shut it down174// from another task.175exp fn connection(self tls: &Tls) -> &Connection {176 return &tls.connection;177}178179// Makes reads and writes waiting longer than the limit fail, as the180// connection's `set_timeout` does.181exp fn set_timeout(self tls: &var Tls, limit: Duration) {182 tls.connection.set_timeout(limit);183}184185exp fn dispose(self tls: &var Tls) {186 if (target() == "wasi-wasm32" || target() == "web-wasm32") {187 tls.connection.dispose();188 } else {189 if (tls.session != 0) {190 al_tls_close(tls.session);191 tls.session = 0;192 }193 tls.connection.dispose();194 }195}