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.
LoadVerifyLocationsFilereplaces the system roots with your file;SetDefaultVerifyPathsswitches back. SetHostnameis required beforeConnectwhile verification is on; without it the handshake is refused.ShutdownandClosedo 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.Readreturns astr, 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.
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)
endIt 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.
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
endVerifyResult 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.
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
endAgainst 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| Name | Type | Description |
|---|---|---|
handle | void* | The pointer to the context state. |
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)
endConn
struct Conn| Name | Type | Description |
|---|---|---|
handle | void* | 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 = 0import 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
endVERIFY_PEER
const VERIFY_PEER: i32 = 1The example for this item is shown with the ones above: ssl-Server.salam
FILETYPE_PEM
const FILETYPE_PEM: i32 = 1The example for this item is shown with the ones above: ssl-Server.salam
TLS1_2
const TLS1_2: i32 = 771The example for this item is shown with the ones above: ssl-Server.salam
TLS1_3
const TLS1_3: i32 = 772The example for this item is shown with the ones above: ssl-Client.salam
CERT_OK
const CERT_OK: i64 = 0The example for this item is shown with the ones above: ssl-Client.salam
Functions
Wrap
func Wrap(ctx: Context, fd: i64): ConnThe example for this item is shown with the ones above: ssl-Client.salam
ConnOk
func ConnOk(c: Conn): boolThe example for this item is shown with the ones above: ssl-Client.salam
Connect
func Connect(c: Conn): boolThe example for this item is shown with the ones above: ssl-Client.salam
Accept
func Accept(c: Conn): boolThe example for this item is shown with the ones above: ssl-Server.salam
Read
func Read(c: Conn, max: int): strThe example for this item is shown with the ones above: ssl-Client.salam
Write
func Write(c: Conn, data: str): intThe example for this item is shown with the ones above: ssl-Client.salam
Shutdown
func Shutdown(c: Conn)The example for this item is shown with the ones above: ssl-Client.salam
Close
func Close(c: Conn)The example for this item is shown with the ones above: ssl-Client.salam
ErrorCode
func ErrorCode(c: Conn, rc: int): intThe example for this item is shown with the ones above: ssl-Client.salam
ConnErrorString
func ConnErrorString(c: Conn): strLastErrorString it is not shared between threads.The example for this item is shown with the ones above: ssl-Client.salam
LastErrorString
func LastErrorString(): strThe example for this item is shown with the ones above: ssl-Client.salam
SetHostname
func SetHostname(c: Conn, host: str): boolThe example for this item is shown with the ones above: ssl-Client.salam
VerifyResult
func VerifyResult(c: Conn): i64The example for this item is shown with the ones above: ssl-Client.salam
PeerVerified
func PeerVerified(c: Conn): boolThe example for this item is shown with the ones above: ssl-Client.salam
NewClientContext
func NewClientContext(): ContextThe example for this item is shown with the ones above: ssl-Client.salam
NewServerContext
func NewServerContext(cert_file: str, key_file: str): ContextThe example for this item is shown with the ones above: ssl-Server.salam
CtxOk
func CtxOk(ctx: Context): boolThe example for this item is shown with the ones above: ssl-Client.salam
SetVerify
func SetVerify(ctx: Context, mode: int)The example for this item is shown with the ones above: ssl-Server.salam
LoadVerifyLocationsFile
func LoadVerifyLocationsFile(ctx: Context, path: str): boolThe example for this item is shown with the ones above: ssl-Server.salam
SetDefaultVerifyPaths
func SetDefaultVerifyPaths(ctx: Context): boolThe example for this item is shown with the ones above: ssl-Client.salam
SetMinVersion
func SetMinVersion(ctx: Context, version: i64): boolTLS1_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)The example for this item is shown with the ones above: ssl-Client.salam