Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-tls

Source of release 0.7.1

0.7.1 / tests / stream / main.lucb

## Loopback tests for tls_stream.Stream: TLS on connect through Reader/Writer
## views, fragmentation, pending plaintext and readiness, a deadline timeout
## that resumes, cancellation from another thread, a plain exchange followed by
## an in-place STARTTLS upgrade (answering a CertificateRequest), close_notify
## and a wrong pin.
import io
from luce_std import net
import c
import sync
import thread
from luce_crypto import native as crypto_native
import stream as tls_stream
import record
import server
import x509

var g_d: u8[32]
var g_qx: u8[32]
var g_qy: u8[32]
var g_cert: u8[2048]
var g_cert_n: usize
var g_port: @u64
var g_ready: @u64
var g_step: @u64
var g_result: @u64
var g_cancel: sync.Cancellation

## Wait, at most five seconds, until `flag` reaches `value`.
func wait_for(flag: (@u64)*, value: u64):
    var i: usize = 0
    while flag.load(.acquire) < value and i < 500:
        thread.sleep(10)
        i += 1

## Serve one TLS client on `conn`: echo, then the scripted cases.
func serve(conn: net.Connection*) -> !:
    var channel = record.Channel()
    try server.accept(&channel, conn, conn, g_cert[..<g_cert_n], g_d)
    # Echo one 40000-byte message back.
    var big: u8[40000]
    var got: usize = 0
    while got < big.length:
        let n = try channel.read_application(conn, big[got..])
        if n == 0:
            error(record.invalid, "early close")
        got += n
    try channel.write_application(conn, big)
    # One record carrying six bytes, for pending().
    try channel.write_application(conn, b"abcdef")
    # After the client's timed-out read, cancel its next blocked read.
    wait_for(&g_step, 1)
    thread.sleep(50)
    g_cancel.request()
    wait_for(&g_step, 2)
    try channel.write_application(conn, b"late")
    # Expect close_notify.
    var tail: u8[16]
    let n = try channel.read_application(conn, tail)
    if n != 0 or not channel.closed_by_peer():
        error(record.invalid, "expected close_notify")

## STARTTLS: a plaintext greeting and command, then TLS on the same socket.
func serve_starttls(conn: net.Connection*) -> !:
    try io.write_all(conn, b"* OK ready\r\n")
    var line: u8[64]
    var used: usize = 0
    while used < 12:
        let n = try conn.read(line[used..])
        if n == 0:
            error(record.invalid, "early close")
        used += n
    if used != 12 or line[0] != 'a':
        error(record.invalid, "expected a1 STARTTLS")
    try io.write_all(conn, b"a1 OK go\r\n")
    # Also ask for a client certificate, which the client answers empty.
    var channel = record.Channel()
    try server.accept(&channel, conn, conn, g_cert[..<g_cert_n], g_d, request_certificate = true)
    var buffer: u8[64]
    let n = try channel.read_application(conn, buffer)
    try channel.write_application(conn, buffer[..<n])

func server_main(raw: void*?):
    _ = raw
    let bind_addr = net.resolve((c.str)"localhost", 0) catch failure:
        return
    var listener = net.Listener.bind(bind_addr) catch failure:
        return
    let addr = listener.address() catch failure:
        return
    g_port.store((u64)addr.port, .release)
    g_ready.store(1, .release)
    var conn = listener.accept() catch failure:
        return
    serve(&conn) catch failure:
        print(f"server: {failure.message}")
        return
    _ = conn.close() catch: recover ()
    var plain = listener.accept() catch failure:
        return
    serve_starttls(&plain) catch failure:
        print(f"starttls server: {failure.message}")
        return
    _ = plain.close() catch: recover ()
    g_result.store(1, .release)
    # The third client pins the wrong key; its handshake must fail.
    var rejected = listener.accept() catch failure:
        return
    var channel = record.Channel()
    server.accept(&channel, &rejected, &rejected, g_cert[..<g_cert_n], g_d) catch failure:
        _ = failure
        recover ()
    _ = rejected.close() catch: recover ()

func implicit_tls(port: u16, pinned: tls_stream.Trust) -> !:
    var stream = try tls_stream.Stream.connect("localhost", port, true, policy = pinned)
    assert(stream.is_secure())
    # Reader/Writer views: a 40000-byte echo crosses several records.
    var big: u8[40000]
    for i in 0..<big.length:
        big[i] = (u8)(i * 7)
    try io.write_all(&stream, big)
    var back: u8[40000]
    try io.read_exact(&stream, back)
    assert(back == big)
    # Pending plaintext is visible to wait() without touching the socket.
    var two: u8[2]
    try io.read_exact(&stream, two)
    assert(two == b"ab")
    assert(stream.pending() == 4)
    let ready = try stream.wait()
    assert(ready.readable)
    var four: u8[4]
    try io.read_exact(&stream, four)
    assert(four == b"cdef")
    assert(stream.pending() == 0)
    # A deadline that expires leaves the stream usable.
    stream.set_deadline(try net.Deadline.after(50000000))
    var late: u8[4]
    var timed_out = false
    _ = stream.read(late) catch failure:
        assert(failure.code == net.timed_out)
        timed_out = true
        recover 0
    assert(timed_out)
    stream.set_deadline(net.Deadline())
    # Another thread cancels a read that would block indefinitely.
    g_step.store(1, .release)
    var cancelled = false
    _ = stream.read_within(late, net.Deadline(), &g_cancel) catch failure:
        assert(failure.code == net.cancelled)
        cancelled = true
        recover 0
    assert(cancelled)
    g_step.store(2, .release)
    try io.read_exact(&stream, late)
    assert(late == b"late")
    try stream.close()
    try stream.close()

func starttls(port: u16, pinned: tls_stream.Trust) -> !:
    let address = try net.resolve((c.str)"localhost", port)
    var stream = tls_stream.Stream.plain(try net.Connection.connect(address))
    assert(not stream.is_secure())
    var greeting: u8[12]
    try io.read_exact(&stream, greeting)
    assert(greeting == b"* OK ready\r\n")
    try io.write_all(&stream, b"a1 STARTTLS\n")
    var reply: u8[10]
    try io.read_exact(&stream, reply)
    assert(reply == b"a1 OK go\r\n")
    try stream.start_tls("localhost", pinned)
    assert(stream.is_secure())
    try io.write_all(&stream, b"a2 NOOP\r\n")
    var echo: u8[9]
    try io.read_exact(&stream, echo)
    assert(echo == b"a2 NOOP\r\n")
    try stream.close()

pub func main(arguments: str[]) -> i32!:
    _ = arguments
    try crypto_native.ecdsa_p256_keygen(g_d, g_qx, g_qy)
    g_cert_n = try x509.mint_self_signed("localhost", g_d, g_qx, g_qy, g_cert)
    var worker = try thread.spawn(server_main, none, name = "tls-stream-server")
    defer worker.join() catch failure:
        _ = failure
    wait_for(&g_ready, 1)
    assert(g_ready.load(.acquire) == 1)
    let port = (u16)g_port.load(.acquire)
    let pinned = try tls_stream.Trust.pinned_issuer(g_qx, g_qy)
    try implicit_tls(port, pinned)
    try starttls(port, pinned)
    wait_for(&g_result, 1)
    assert(g_result.load(.acquire) == 1)
    # A wrong pin must fail the handshake.
    let wrong = try tls_stream.Trust.pinned_issuer(g_qy, g_qx)
    var refused = false
    var bad = tls_stream.Stream.connect("localhost", port, true, policy = wrong) catch failure:
        _ = failure
        refused = true
        recover tls_stream.Stream()
    assert(refused)
    try bad.close()
    print("PASS Stream TLS and plain I/O, pending, deadlines, cancellation, STARTTLS and close_notify")
    return 0