TLS
import "std/net" (not included in import "std") · namespace std.net
TLS is the encryption behind https:// and wss://: it keeps a connection private and proves the server is who it claims to be. Grav uses the system's OpenSSL, loaded the first time TLS is needed, so a program that never uses TLS does not depend on it. A TLS connection is an ordinary TcpStream: readLine, write and the rest work the same, and isTls() / tlsVersion() tell it apart.
import "std"
import "std/net"
fn main() {
if (!Tls.available()) { print("no TLS here: " + Tls.unavailableReason()); return }
// A server with a throwaway certificate (for development and tests).
let ctx = TlsContext.selfSigned("localhost")
let listener = TcpListener.bind("127.0.0.1", 0)
let server = Thread.spawn(fn() {
let conn = listener.accept()
Tls.startServer(conn, ctx)
conn.writeLine("hello over " + conn.tlsVersion())
conn.close()
})
// A client that trusts exactly that certificate.
let trust = TlsContext.client().trustPem(ctx.certificatePem())
let c = Tls.connect("localhost", listener.port(), trust, 5000)
print(Str.startsWith(c.readLine(), "hello over TLSv1."))
c.close()
server.join()
}true- Clients:
Tls.connect(host, port)connects and checks the server's certificate against the system's trusted authorities and the host name, the way a browser does. A certificate that does not check out throwsNetErrorwith the reason (self-signed certificate,hostname mismatch, ...). Pass aTlsContextto change what is trusted:TlsContext.client().trustPem(pem)or.trustFile(path)adds a private authority or a self-signed server;TlsContext.insecureClient()accepts anything (encrypted, but with no protection against an impostor). - Servers:
TlsContext.server(certFile, keyFile)loads a certificate chain and key in PEM files (serverPemtakes the text).TlsContext.selfSigned(host)makes a new key and certificate for development;certificatePem()andprivateKeyPem()give them out to save or to trust.Tls.startServer(conn, ctx)answers the handshake on an accepted connection;Tls.acceptStep(conn, ctx)does it without waiting for the client, for servers that poll their connections (true once done, false while more must arrive). - Session resumption: a client context remembers the sessions of servers it connected to recently, so the next connection to the same host and port resumes instead of running a full handshake (
conn.tlsResumed()says whether it did). The key exchange still runs, so each connection keeps its own keys.withSessionResumption(false)turns it off. - Switching part way:
Tls.startClient(conn, host, ctx)starts TLS on a connection that is already open, as SMTP's STARTTLS does. - Higher levels:
HttpServer.startTls/listenTls,HttpClientwithhttps://URLs,WebSocket.connect("wss://...")andSmtpClient(STARTTLS) all use this module. - Protocols: TLS 1.2 and 1.3; older versions are refused. Timeouts set with
setTimeoutMsapply to the handshake and to every read and write. - Without OpenSSL (libssl 3 or 1.1),
Tls.available()is false,Tls.unavailableReason()says why, and TLS calls throwNetError.
ALPN
Tls.connect(host, port, ["h2", "http/1.1"]) offers application protocols in the handshake (ALPN), and Tls.protocol(conn) says which one the server chose ("" if none): how a client agrees on HTTP/2 (Http2Client does it for you). Tls.offer(conn, protocols) sets the offer before startClient.
API
class TlsContext
What TLS connections made with it trust and present: a client context checks servers, a server context holds the certificate and key it shows clients. One context can be shared by any number of connections and threads.
Constructors
new TlsContext(server: bool, verify: bool)— Use the static constructors (client, server, selfSigned, ...).
Static members
static fn client() -> TlsContext— A client context that checks servers against the system's trusted certificate authorities and their host names (what browsers do).static fn insecureClient() -> TlsContext— A client context that accepts any server certificate. Encrypted, but with no protection against an impostor: for tests and machines you control.static fn server(certFile: string, keyFile: string) -> TlsContext— A server context with the certificate chain and private key in PEM files.static fn serverPem(certPem: string, keyPem: string) -> TlsContext— A server context from PEM text: the certificate (then any chain certificates) and its private key.static fn selfSigned(host: string) -> TlsContext— A server context with a new self-signed certificate forhost(a name or an address; "localhost" also covers 127.0.0.1 and ::1), valid for a year. Browsers warn about it; clients trust it with trustPem(certificatePem()).static fn selfSigned(host: string, days: int) -> TlsContext— A self-signed server context valid fordaysdays.
Methods
fn trustPem(pem: string) -> TlsContext— Also trusts the certificate(s) in PEM text (a private CA, or a self-signed server); returns this context.fn trustFile(path: string) -> TlsContext— Also trusts the certificate(s) in a PEM file; returns this context.fn certificatePem() -> string— The certificate a server context presents, as PEM ("" for a client context).fn privateKeyPem() -> string— The private key of a server context, as PEM ("" for a client context).fn withSessionResumption(on: bool) -> TlsContext— Whether new connections to a server this client context has talked to recently resume that session, skipping most of the handshake (on by default); returns this context.fn resumesSessions() -> bool— Whether client sessions are resumed.fn isServer() -> bool— Whether this is a server context.fn verifies() -> bool— Whether a client context checks the server's certificate.fn handle() -> byte*— The OpenSSL context, for lib/net code.
class Tls
TLS connections.
Static members
static fn available() -> bool— Whether OpenSSL could be loaded (TLS works).static fn unavailableReason() -> string— Why TLS is unavailable ("" when it works).static fn libraryVersion() -> string— The OpenSSL version in use ("OpenSSL 3.0.13 30 Jan 2024"); "" without TLS.static fn connect(host: string, port: int) -> TcpStream— Connects to host:port and completes a TLS handshake, verifying the server against the system's trusted certificates. NetError when the certificate is not accepted.static fn connect(host: string, port: int, ctx: TlsContext, timeoutMs: int) -> TcpStream— Connects with the given client context (null: the system default) and timeout for connecting and the handshake.static fn connect(host: string, port: int, protocols: Array<string>, timeoutMs: int = 30000, ctx: TlsContext = null) -> TcpStream— Connects offering application protocols by ALPN ("h2", "http/1.1"); the one the server chose is Tls.protocol(conn) ("" if it chose none).static fn offer(conn: TcpStream, protocols: Array<string>)— The protocols the next client handshake onconnoffers (ALPN).static fn protocol(conn: TcpStream) -> string— The application protocol the TLS handshake settled on ("h2"; "" for none).static fn startClient(conn: TcpStream, host: string, ctx: TlsContext)— Starts TLS as a client on a connected stream (for protocols that switch to TLS part way, like SMTP's STARTTLS).hostis checked against the server's certificate; ctx null means the system default.static fn startServer(conn: TcpStream, ctx: TlsContext)— Answers a client's TLS handshake on an accepted stream with the server context's certificate.static fn acceptStep(conn: TcpStream, ctx: TlsContext) -> bool— One step of answering a client's handshake without waiting for the client: true once it is done, false while the client has more to send (step again when the connection is readable). NetError when it fails.