Standard library · Security and cryptography

ssl

A familiar OpenSSL style interface for secure connections, on top of Salam's own TLS.

import ssl

This package gives an OpenSSL style context and connection interface (SSL_CTX, SSL_connect, SSL_read and friends, under Salam names), but underneath it is Salam's own tls and it needs no outside library. Use it when you port C code written against OpenSSL, or when you like that split between a shared context and many connections. For new code tls is shorter, and for web requests net.http does all of it for you.

The flow: make one context, hand each TCP socket to it with Wrap, for a client set the hostname and call Connect (a server calls Accept), then Read and Write. Things to know:

  • A client context checks certificates against the system roots from the start, with TLS 1.2 as the minimum. LoadVerifyLocationsFile replaces the system roots with your file; SetDefaultVerifyPaths switches back.
  • SetHostname is required before Connect while verification is on; without it the handshake is refused.
  • Shutdown and Close do not close the socket. As in OpenSSL, the TCP connection you wrapped is yours; close it with net.tcp afterwards.
  • SetMinVersion(ctx, TLS1_3) is checked after the handshake: a server that only offers 1.2 is connected and then refused. Read returns a str, which stops at a zero byte.

A complete client

The steps are always the same: one context for the whole program, then for each connection a TCP socket, Wrap, SetHostname and Connect. A context made with NewClientContext already trusts the system roots and stops the handshake when the check fails; the calls to SetDefaultVerifyPaths and SetVerify(ctx, VERIFY_PEER) in the program only make that explicit, the way OpenSSL code usually reads. Read returns an empty string when the server closes the connection, which is the end of a Connection: close response.

ssl-fetch-page.salam
import ssl
import net.tcp
import str

func fetch(ctx: ssl.Context, host: str, path: str): str:
    sock := tcp.Dial(host, 443)
    if not tcp.ConnOk(sock):
        ret "could not reach " + host
    end
    conn := ssl.Wrap(ctx, sock.fd)
    _ := ssl.SetHostname(conn, host)
    if not ssl.Connect(conn):
        msg := ssl.ConnErrorString(conn)
        ssl.Close(conn)
        tcp.Close(sock)
        ret "handshake failed: " + msg
    end
    _ := ssl.Write(conn, "GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n")
    mut response := ""
    until true:
        chunk := ssl.Read(conn, 16384)
        if chunk.Len() == 0:
            break
        end
        response += chunk
    end
    ssl.Shutdown(conn)
    ssl.Close(conn)
    tcp.Close(sock)
    ret str.Split(response, "\r\n").Get(0)
end

func main:
    ctx := ssl.NewClientContext()
    _ := ssl.SetDefaultVerifyPaths(ctx)
    _ := ssl.SetMinVersion(ctx, ssl.TLS1_2)
    ssl.SetVerify(ctx, ssl.VERIFY_PEER)
    println fetch(ctx, "example.com", "/")
    println fetch(ctx, "expired.badssl.com", "/")
    ssl.CloseContext(ctx)
end

It needs network access, so it is only checked here. Run against the real hosts, it printed:

HTTP/1.1 200 OK
handshake failed: certificate verification failed: certificate expired

Trusting only your own certificate authority

Services inside a company often use certificates from a private CA. Load that CA with LoadVerifyLocationsFile instead of the system roots: the client then accepts only servers whose certificate your CA signed, which is stricter than the public web. SetMinVersion(ctx, TLS1_3) refuses anything older than TLS 1.3, and after the handshake PeerVerified and VerifyResult tell you how the check went.

ssl-private-ca.salam
import ssl
import net.tcp

func main:
    ctx := ssl.NewClientContext()
    if not ssl.LoadVerifyLocationsFile(ctx, "/etc/company/ca.pem"):
        println "cannot read the company CA:", ssl.LastErrorString()
        ret 1
    end
    ssl.SetVerify(ctx, ssl.VERIFY_PEER)
    _ := ssl.SetMinVersion(ctx, ssl.TLS1_3)

    sock := tcp.Dial("billing.internal", 8443)
    conn := ssl.Wrap(ctx, sock.fd)
    _ := ssl.SetHostname(conn, "billing.internal")
    ok := ssl.Connect(conn)
    if not ok or not ssl.PeerVerified(conn):
        println "refusing the server, verify result", ssl.VerifyResult(conn), ssl.ConnErrorString(conn)
        ssl.Close(conn)
        tcp.Close(sock)
        ret 1
    end
    _ := ssl.Write(conn, "PING\n")
    println "server said:", ssl.Read(conn, 1024)
    ssl.Shutdown(conn)
    ssl.Close(conn)
    tcp.Close(sock)
    ssl.CloseContext(ctx)
    ret 0
end

VerifyResult is CERT_OK (zero) when the certificate was accepted. Keep the CA file readable by the program but not writable, since anyone who can replace it can impersonate your servers.

STARTTLS: encrypt a connection that is already open

Mail, IMAP, XMPP and some database protocols start in plain text and switch to TLS on the same connection when the client asks. This is why Wrap takes a socket descriptor rather than a host: talk to the server with net.tcp until it agrees, then wrap the very same fd and carry on through ssl.Read and ssl.Write.

ssl-starttls.salam
import ssl
import net.tcp
import str

func say(sock: tcp.Conn, line: str): str:
    _ := tcp.Write(sock, line + "\r\n")
    ret tcp.Read(sock, 4096)
end

func main:
    sock := tcp.Dial("smtp.gmail.com", 587)
    greeting := tcp.Read(sock, 4096)
    println "plain:", str.Split(greeting, "\r\n").Get(0)
    _ := say(sock, "EHLO client.example.com")
    reply := say(sock, "STARTTLS")
    if not str.StartsWith(reply, "220"):
        println "no STARTTLS:", reply
        tcp.Close(sock)
        ret 1
    end

    ctx := ssl.NewClientContext()
    _ := ssl.SetDefaultVerifyPaths(ctx)
    ssl.SetVerify(ctx, ssl.VERIFY_PEER)
    conn := ssl.Wrap(ctx, sock.fd)
    _ := ssl.SetHostname(conn, "smtp.gmail.com")
    if not ssl.Connect(conn):
        println "handshake failed:", ssl.ConnErrorString(conn)
        ret 1
    end
    _ := ssl.Write(conn, "EHLO client.example.com\r\n")
    println "encrypted:", str.Split(ssl.Read(conn, 4096), "\r\n").Get(0)
    _ := ssl.Write(conn, "QUIT\r\n")
    ssl.Shutdown(conn)
    ssl.Close(conn)
    tcp.Close(sock)
    ssl.CloseContext(ctx)
    ret 0
end

Against Gmail's submission port it printed the server's greeting in plain text and then its first encrypted reply; the ids at the end of each line change with every run:

plain: 220 smtp.gmail.com ESMTP ... - gsmtp
encrypted: 250-smtp.gmail.com at your service, [...]

A real mail client should check every reply code, not only the one for STARTTLS, and should send EHLO again after the switch, as the program does, because the server forgets everything it was told in plain text.

When something fails

There are three places to look. LastErrorString describes the last failure that has no connection yet, such as a context that could not read its certificate. ConnErrorString describes what went wrong on one connection, for example a failed certificate check. And when Read or Write returns zero or less, ErrorCode(conn, n) tells a clean close by the other side apart from a protocol or socket error, the same split OpenSSL's SSL_get_error makes.

Types

Context

struct Context
A TLS context, shared between connections.
NameTypeDescription
handlevoid*The pointer to the context state.
ssl-Client.salam
import ssl
import net.tcp

func main:
    ctx := ssl.NewClientContext()
    if not ssl.CtxOk(ctx):
        println ssl.LastErrorString()
        ret
    end
    _ := ssl.SetMinVersion(ctx, ssl.TLS1_3)
    _ := ssl.SetDefaultVerifyPaths(ctx)
    sock := tcp.Dial("example.com", 443)
    conn := ssl.Wrap(ctx, sock.fd)
    _ := ssl.SetHostname(conn, "example.com")
    if not ssl.ConnOk(conn) or not ssl.Connect(conn):
        println "the handshake failed:", ssl.ConnErrorString(conn)
        ret
    end
    println ssl.PeerVerified(conn), ssl.VerifyResult(conn) == ssl.CERT_OK
    n := ssl.Write(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
    if n <= 0:
        println "error code:", ssl.ErrorCode(conn, n)
    end
    println ssl.Read(conn, 4096).Len() > 0
    ssl.Shutdown(conn)
    ssl.Close(conn)
    ssl.CloseContext(ctx)
    tcp.Close(sock)
end

Conn

struct Conn
One TLS connection.
NameTypeDescription
handlevoid*The pointer to the connection state.

The example for this item is shown with the ones above: ssl-Client.salam

Constants and variables

VERIFY_NONE

const VERIFY_NONE: i32 = 0
Verification mode: no verification.
ssl-Server.salam
import ssl
import net.tcp

func main:
    ctx := ssl.NewServerContext("cert.pem", "key.pem")
    if not ssl.CtxOk(ctx):
        println ssl.LastErrorString()
        ret
    end
    ssl.SetVerify(ctx, ssl.VERIFY_NONE)
    _ := ssl.LoadVerifyLocationsFile(ctx, "clients-ca.pem")
    ssl.SetVerify(ctx, ssl.VERIFY_PEER)
    println ssl.FILETYPE_PEM, ssl.TLS1_2
    server := tcp.Bind(8443)
    until true:
        sock := tcp.Accept(server)
        conn := ssl.Wrap(ctx, sock.fd)
        if ssl.Accept(conn):
            request := ssl.Read(conn, 4096)
            _ := ssl.Write(conn, "HTTP/1.1 200 OK\r\nContent-Length: " + request.Len() + "\r\n\r\n" + request)
        end
        ssl.Close(conn)
    end
end

VERIFY_PEER

const VERIFY_PEER: i32 = 1
Verification mode: verify the certificate of the other side.

The example for this item is shown with the ones above: ssl-Server.salam

FILETYPE_PEM

const FILETYPE_PEM: i32 = 1
The PEM file type.

The example for this item is shown with the ones above: ssl-Server.salam

TLS1_2

const TLS1_2: i32 = 771
The version number of TLS 1.2.

The example for this item is shown with the ones above: ssl-Server.salam

TLS1_3

const TLS1_3: i32 = 772
The version number of TLS 1.3.

The example for this item is shown with the ones above: ssl-Client.salam

CERT_OK

const CERT_OK: i64 = 0
Verification result: the certificate is valid.

The example for this item is shown with the ones above: ssl-Client.salam

Functions

Wrap

func Wrap(ctx: Context, fd: i64): Conn
Makes a new SSL connection over an open socket.

The example for this item is shown with the ones above: ssl-Client.salam

ConnOk

func ConnOk(c: Conn): bool
The connection was created.

The example for this item is shown with the ones above: ssl-Client.salam

Connect

func Connect(c: Conn): bool
Does the client handshake.

The example for this item is shown with the ones above: ssl-Client.salam

Accept

func Accept(c: Conn): bool
Does the server handshake.

The example for this item is shown with the ones above: ssl-Server.salam

Read

func Read(c: Conn, max: int): str
Reads up to this many bytes as a string; empty when the other side closed. The text stops at a zero byte.

The example for this item is shown with the ones above: ssl-Client.salam

Write

func Write(c: Conn, data: str): int
Sends data and returns the number of bytes, or a negative number on an error.

The example for this item is shown with the ones above: ssl-Client.salam

Shutdown

func Shutdown(c: Conn)
Sends the close alert and ends the TLS session; the socket stays open.

The example for this item is shown with the ones above: ssl-Client.salam

Close

func Close(c: Conn)
Sends the close alert if needed and frees the connection; the socket stays open, so close it yourself.

The example for this item is shown with the ones above: ssl-Client.salam

ErrorCode

func ErrorCode(c: Conn, rc: int): int
The OpenSSL style error code for the result of one read or write.

The example for this item is shown with the ones above: ssl-Client.salam

ConnErrorString

func ConnErrorString(c: Conn): str
The error text of this connection; unlike LastErrorString it is not shared between threads.

The example for this item is shown with the ones above: ssl-Client.salam

LastErrorString

func LastErrorString(): str
The text of the last error, and clears it.

The example for this item is shown with the ones above: ssl-Client.salam

SetHostname

func SetHostname(c: Conn, host: str): bool
Sets the hostname for SNI and for certificate verification.

The example for this item is shown with the ones above: ssl-Client.salam

VerifyResult

func VerifyResult(c: Conn): i64
The result of verifying the certificate of the other side.

The example for this item is shown with the ones above: ssl-Client.salam

PeerVerified

func PeerVerified(c: Conn): bool
The certificate of the other side was verified and accepted.

The example for this item is shown with the ones above: ssl-Client.salam

NewClientContext

func NewClientContext(): Context
A client context with TLS 1.2 as the minimum, certificate verification and the system roots.

The example for this item is shown with the ones above: ssl-Client.salam

NewServerContext

func NewServerContext(cert_file: str, key_file: str): Context
A server context with a certificate and key from files.

The example for this item is shown with the ones above: ssl-Server.salam

CtxOk

func CtxOk(ctx: Context): bool
The context was created.

The example for this item is shown with the ones above: ssl-Client.salam

SetVerify

func SetVerify(ctx: Context, mode: int)
The certificate verification mode.

The example for this item is shown with the ones above: ssl-Server.salam

LoadVerifyLocationsFile

func LoadVerifyLocationsFile(ctx: Context, path: str): bool
Trusts the root certificates in this PEM file instead of the system roots; false when the file holds none.

The example for this item is shown with the ones above: ssl-Server.salam

SetDefaultVerifyPaths

func SetDefaultVerifyPaths(ctx: Context): bool
Goes back to the system roots, the default for a new context.

The example for this item is shown with the ones above: ssl-Client.salam

SetMinVersion

func SetMinVersion(ctx: Context, version: i64): bool
The minimum TLS version, TLS1_2 or TLS1_3; checked once the handshake is done.

The example for this item is shown with the ones above: ssl-Client.salam

CloseContext

func CloseContext(ctx: Context)
Frees the context.

The example for this item is shown with the ones above: ssl-Client.salam