SCUA

How-to

Handle secrets

A password, an API key or a session token is usually just a string, and a string ends up everywhere: in a print you added while debugging, in a log line that dumps the request, in a fault message, in a test's output. A secret is a value that holds those bytes and refuses to become text by accident. print shows it as <secret>, building a string from it stops with a message that says what to write instead, and the calls that need the bytes (crypto, HTTP, commands, files, sockets) take it as it is.

import secrets

let token = secrets.of("tok-3f9a1c")
print(token)
print(type(token), len(token))
print({ user = "ann", token = token })
$ scua token.scua
<secret>
secret 10
{user = ann, token = <secret>}

A secret guards against accidents: a log, a print, a fault, an error value or a save that shows it. It does not guard against code that holds it, which can always ask for the bytes, and it does not keep the bytes out of memory. What a secret does not protect lists exactly where the protection stops.

#Get the secret in without a string

A secret protects its bytes only from the moment it is made. secrets.of(v) turns an existing string or bytes value into a secret, but the original string is still there, an ordinary value, until it is collected. So read secrets straight into one. The calls that already read the bytes take { as_secret = true }:

Call Gives
crypto.random_bytes(n, { as_secret = true }) Ok(secret): a new random key or token
fs.read(path, { as_secret = true }) Ok(secret): the file's bytes exactly, trailing newline included
env.get(name, { as_secret = true }) a secret, or nil when the variable is unset or not granted
sys.readpassword({ as_secret = true }) one line as a secret, or nil at the end of input
exec.run(argv, { as_secret = true }), exec.run_any Ok({ status, stdout, stderr }) with stdout a secret
the decrypts (aes_gcm_decrypt, aes_cbc_hmac_decrypt, aes_ctr, rsa_decrypt) with { as_secret = true } Ok(secret)

A secret holds at most 64 KiB. A read with as_secret that would be longer returns Error({ kind = "too_large" }) and is never cut short, since half a key is a wrong key.

A key file usually holds hex or base64 text and ends in a newline. secrets.decode turns the text into the key's bytes, and secrets.trim drops a trailing newline from a password file. Both work from one secret to another, so the text never becomes a string:

import fs
import secrets

-- For this example, write the key file an operator would have put there.
fs.write("home.key", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\n")?

let raw = fs.read("home.key", { as_secret = true })?
let home_key = secrets.decode(raw, "hex")?    -- the newline around the hex is ignored
raw.release()                                  -- the hex form is no longer needed
print(home_key, len(home_key))
$ scua --allow-fs key.scua
<secret> 32

secrets.decode reads "hex", "base64", "base64url" and "base32". Base32 is the A-Z 2-7 alphabet that a TOTP seed is usually given in; upper and lower case both work, and the = padding is optional:

import secrets

let seed = secrets.decode(secrets.of("JBSWY3DPEHPK3PXP"), "base32")?
print(seed, len(seed))
$ scua seed.scua
<secret> 10

Whitespace around the text is ignored, but not inside it: a seed shown in groups, such as JBSW Y3DP, is refused, so take the spaces out first. To go the other way, such as to put a new seed in an otpauth:// link, secrets.encode(seed, "base32") writes upper-case base32 without the padding. Its bad_encoding error never quotes the text, and neither does any other call that makes a secret. fs.read_text does not take as_secret: it refuses, and its message points you to fs.read and secrets.trim.

From the environment and the terminal:

import env
import sys

let api_token = env.get("API_TOKEN", { as_secret = true })
if api_token == nil then
  error("API_TOKEN is not set")
end

print("Backup passphrase: ")
let passphrase = sys.readpassword({ as_secret = true })

env.get needs --allow-env=API_TOKEN and sys.readpassword needs --allow-tty, as they do without the option. On a pipe sys.readpassword reads the line normally, so a scheduled job can be fed its passphrase.

#What a secret refuses

Anything that would turn a secret into text or bytes stops the program with a fault that says what to do instead: .., a template, tostring, format, json.encode, the str functions, base64 and hex, sys.write and sys.write_err, and any other call that takes a string and isn't listed under Use a secret where the bytes are needed.

import secrets
import json

let token = secrets.of("tok-3f9a1c")
print(pcall(fn() return "Bearer " .. token end))
print(pcall(fn() return json.encode({ token = token }) end))
$ scua refuse.scua
Error(can't build a string from a secret. To put it in a header, URL or body, build a secret: secrets.format("Bearer {}", s). http.request, exec.run, fs.write, crypto and http.serve responses take a secret as it is. (s.reveal() makes a plain copy and gives up the protection.))
Error(json.encode can't encode a secret. Use secrets.json({ value = s }), which escapes it and returns a secret that http.serve responses, http.request and exec.run take. secrets.format does not escape, so don't build JSON with it. (s.reveal() makes a plain copy and gives up the protection.))

These calls fault on purpose. If they wrote the text <secret> instead, a header or body holding it would go out, and the program would run on with the wrong credential and no error.

Where the type checker can see that a value is a secret, such as a parameter annotated k: secret, the same mistakes are compile errors with the same text.

#Comparing, and finding something by a token

== and != on a secret fault, against anything but nil. Comparing with == would not take constant time, so it could leak the secret through timing. secrets.equal(a, b) compares the contents in constant time and takes a secret, bytes or a string on either side. To test for an empty secret, use len:

import secrets

let pw = secrets.of("hunter22")
print(secrets.equal(pw, "hunter22"), secrets.equal(pw, "hunter23"), secrets.equal(pw, nil))
print(len(pw) == 0, pw == nil)
print(pcall(fn() return pw == "hunter22" end))
$ scua compare.scua
true false false
false false
Error(== can't compare a secret: it would compare handles, not contents. To test for an empty secret use len(s) == 0. To compare contents use secrets.equal(a, b), which takes constant time.)

secrets.equal answers false when either side is nil or empty, a released or wiped secret included, so a request with an empty token never matches a configured one. Writing secrets.equal(pw, "") is a compile error, because it can only answer false. hash.equal takes secrets too, with the same answers.

A secret can't be a table key either. To look something up by a token, key the table by the token's digest, which is safe to keep in memory, in a log or in a save for a random token:

import secrets
import hash
import hex

let tok = secrets.of("s-81b2c4d9e0f1")
let sessions = {}
sessions[hex.encode(hash.sha256(tok))] = "ann"
print(sessions[hex.encode(hash.sha256(tok))])
print(pcall(fn() sessions[tok] = "ann" end))
$ scua sessions.scua
ann
Error(a secret can't be a table key. To find something by a token, key the table by hex.encode(hash.sha256(token)), which is safe to keep for a random token)

Keep a digest only of a random token. A digest of a password can be reversed by guessing passwords, so a password is stored with crypto.argon2id_hash, which takes a secret.

#Use a secret where the bytes are needed

These take a secret wherever they take the protected bytes, and send exactly its bytes:

  • crypto: every key, password, seed and plaintext. A key made from a secret is a secret (a keypair's secret field, ecdh's shared secret, pbkdf2 and argon2id output, aes_key_unwrap's key). Digests, MACs, signatures, ciphertexts, public keys and argon2id_hash's stored string are bytes or a string, since they are made to be kept. An RSA private key can be a JWK table whose d is a secret.
  • hash: the digests, hmac's key and data, and equal.
  • http.request, http.get and http.post: the URL's path and query, header values and the body.
  • http.serve responses: the body, header values (a set-cookie list included) and a stream's writes.
  • exec.run and exec.run_any: an argument after the program's name, env values and stdin.
  • fs.write, fs.write_chunk, net.write and the udp sends: the data.

Each one checks what it checks on a string, on the secret's contents, and its errors name the header or the argument, never the value: a header value holding a line break is still refused, and an exec template's rules still apply. In an exec template a secret fills only a {string} hole. It never names the program and never stands where the template has a literal or an {int}, because matching it against those would tell the script whether it equals them. Pass a secret to a command in env or on stdin where you can: other programs on the machine can read a command's arguments.

sys.write and sys.write_err refuse a secret. They write where print goes, so writing the bytes there would put them beside a <secret> from a print with no sign in the code of where they came from. A command that shows a stored value to its owner writes sys.write(value.reveal()), which says so.

When a secret has to sit inside other text, build a new secret. secrets.format fills {} holes, secrets.concat joins values, secrets.encode encodes, and secrets.json writes JSON. None of them makes a string.

#A token in a URL path

import secrets

let token = secrets.of("a/b+c=")
let url = secrets.format("https://api.example.com/v1/hooks/{}/send", secrets.encode(token, "percent"))
print(url)
print(url.reveal())   -- shown here only to see what it holds
$ scua url.scua
<secret>
https://api.example.com/v1/hooks/a%2Fb%2Bc%3D/send

A token that may hold /, + or = is percent-encoded first, with secrets.encode(token, "percent"), since secrets.format escapes nothing. Pass the result to http.request as the URL:

let res = http.request(url, { method = "POST", body = secrets.json({ text = "deployed" }) })?

The scheme and host of a URL are never secret, because the net grant checks the host. So a secret URL must come from secrets.format, with the template's own text reaching past the host before the first {}.

#A password in a form body

A login form posted as application/x-www-form-urlencoded, or a query string read the same way, writes a space as +. Encode the value with "form", which is "percent" except for that:

import secrets

let pw = secrets.of("correct horse+battery")
let body = secrets.format("user=ann&password={}", secrets.encode(pw, "form"))
print(body.reveal())   -- shown here only to see what it holds
$ scua form.scua
user=ann&password=correct+horse%2Bbattery

A + in the value is written %2B, so the server can't mistake it for a space. Anything else is refused:

the scheme and host of a URL can't be secret. Build it as secrets.format("https://api.example.com/v1/items/{}", token).

No error from an http call shows the secret part of a URL. Put tokens in headers rather than URLs where the service allows it: a server's logs keep the URLs it was sent.

#Basic auth

import secrets

let user = "ann"
let pw = secrets.of("hunter22")
let basic = secrets.encode(secrets.format("{}:{}", user, pw), "base64")
let authorization = secrets.format("Basic {}", basic)
print(authorization)
print(secrets.equal(authorization, "Basic YW5uOmh1bnRlcjIy"))
$ scua basic.scua
<secret>
true

Send it as headers = { authorization = authorization }.

#SMTP AUTH PLAIN

AUTH PLAIN is the base64 of \0user\0password:

import secrets

let pw = secrets.of("hunter22")
let plain = secrets.encode(secrets.concat("\0", "ann", "\0", pw), "base64")
print(secrets.equal(plain, "AGFubgBodW50ZXIyMg=="))
$ scua smtp.scua
true

On the connection, after the server's greeting and EHLO:

net.write(conn, secrets.format("AUTH PLAIN {}\r\n", plain))?

#A server that takes a token

A server's session cookies and bearer tokens arrive on every request, and by default every header reaches the handler as a string, so print(req) or warn("denied", req) would put the token in a log. Name those headers in secret_headers, and their values arrive as secrets, made as the request is read, so they never exist as strings in your program:

import http
import env
import hash
import hex
import secrets

let api_token = env.get("API_TOKEN", { as_secret = true })
if api_token == nil then
  error("API_TOKEN is not set, so every request would be refused")
end

fn handle(req, ctx)
  let tok = secrets.strip_prefix(req.headers.authorization, "Bearer ")   -- a secret, or nil
  if tok == nil or not secrets.equal(tok, ctx.api_token) then
    return { status = 401, body = b"" }
  end
  let sid = secrets.cookie(req.headers.cookie, "session")                -- a secret, or nil
  if sid != nil then
    let session_id = hex.encode(hash.sha256(sid))   -- safe to keep, log or use as a table key
    print(`request from session {session_id}`)
  end
  return { status = 200, body = b"ok" }
end

http.serve(handle, {
  bind = "127.0.0.1:8080",
  context = { api_token = api_token },
  secret_headers = ["authorization", "cookie"],
})?
  • secret_headers names request headers, matched without regard to case. A header sent more than once arrives as one secret, its values joined with , , as a string header's are. Every other header, the path and the query stay strings.
  • secrets.strip_prefix(s, prefix) returns a new secret without the prefix, or nil when s is nil or doesn't start with it. The prefix is compared without regard to ASCII case, as authorization schemes are, so "Bearer " matches bearer.
  • secrets.cookie(s, name) returns one cookie's value from a cookie header as a new secret, or nil when the header is missing, the cookie isn't there or the header is malformed. It never quotes the header.
  • Pass secrets to handlers in context. Each request gets its own copy. A handler that reaches a top-level secret is refused before the server starts, with a message that says to pass it in context.
  • Check for nil at start. With API_TOKEN unset, env.get returns nil, and every request would be answered 401 with nothing at startup to say why.

Both helpers take nil without complaint, since a header that wasn't sent is nil, but refuse a string: their message names secret_headers, the usual cause.

--serve-log never writes a header value. It does write each request's path, query string included.

#JSON with secret fields

A request body or a document on stdin often holds a password among ordinary fields. Declare the field as secret in a record, and a typed json.decode makes it a secret as it reads:

import json
import secrets

record Login { username: string, password: secret }

let text = "{\"username\": \"ann\", \"password\": \"hunter22\"}"
let login = json.decode(text, Login)?
print(login)
print(secrets.equal(login.password, "hunter22"))
$ scua login.scua
{username = ann, password = <secret>}
true

Without a record, name the fields in the secrets option: top-level names, or dotted paths through objects. A [] step goes through a list, as in "keys[].token":

import json

let doc = "{\"smtp\": {\"host\": \"mx.example.com\", \"password\": \"s3cret!\"}}"
let cfg = json.decode(doc, { secrets = ["smtp.password"] })?
print(cfg)
$ scua config.scua
{smtp = {host = mx.example.com, password = <secret>}}

With a record, the option goes after it, and the two lists add up: json.decode(text, Config, { secrets = ["extra.key"] }). Fields are matched on their decoded names. A named field that is present but not a JSON string is Error({ kind = "secret_field" }), and a null one is absent. While any field is secret, a decode error never quotes the document and a typed decode's error never shows a value.

The text you decoded is still there as an ordinary value until it is collected, so this keeps the password out of the decoded table, not out of memory. For a request body, bytes.wipe(req.body) zeroes the copy the handler holds once you have decoded it.

parse refuses a string in a secret field, because the string already exists. Its message names json.decode(text, T), which makes the secret as it reads, and secrets.of(v), which converts a value on purpose.

To hand a child process a whole request as JSON on its stdin, build it with secrets.json, which escapes every string and writes each secret as a JSON string of its bytes:

let res = exec.run(["vault-helper", "store"], { stdin = secrets.json({ user = "ann", password = pw }) })?

#Scrub what comes back

A server or a command given a credential sometimes sends it back: in an error message, an echo of the request, a debug field. Before you log or forward such an answer, scrub it with secrets.redact:

import secrets

let api = secrets.of("tok-3f9a1c")
let smtp = secrets.of("hunter22")
let answer = "upstream said: bad token tok-3f9a1c; auth aHVudGVyMjI= refused"
print(secrets.redact(answer, api, smtp))
print(secrets.redact(answer, [[api, "[secret API]"], [smtp, "[secret SMTP]"]]))
$ scua redact.scua
upstream said: bad token [secret]; auth [secret] refused
upstream said: bad token [secret API]; auth [secret SMTP] refused

secrets.redact(text, s, ...) replaces each secret with [secret]; given a list of [secret, label] pairs, it uses each label instead. It takes a string or bytes and gives back the same kind. Each secret is matched as its bytes, as lower- and upper-case hex, as base64 and base64url with and without padding, as upper-case base32 with and without padding, percent-encoded (a space as %20 or as +), and as a JSON string escapes it. All the secrets are matched in one pass, longest first, so a secret that is part of another never leaves the rest of the longer one showing.

It is best effort:

  • Pass what went out, not only its parts. Base64 doesn't keep substrings, so the base64 of ann:hunter22 doesn't contain the base64 of hunter22. A server that echoes your Authorization header is scrubbed only if you pass the composed header, or the basic secret it was built from, as well as the password.
  • It doesn't match base64 split across lines, other encodings, part of a secret, or anything compressed.
  • A secret under 6 bytes is refused: it would match all over the text, and the labels around it would give it away.
  • How long it takes depends on the text and the secrets.

A command's stderr comes back as it is. A program given a bad credential often prints it in its error message, and exec.run returns that stderr as ordinary bytes, unscrubbed. Scrub it before you log it:

let res = exec.run_any(["git", "push", remote], { env = { GIT_TOKEN = token } })?
if res.status != 0 then
  warn("push failed", { stderr = secrets.redact(res.stderr, token) })
end

#Keep a key in a key-cache actor

A key that many parts of a program use can live in one partition, which hands each caller a copy. A secret crosses a partition boundary as bytes does: in a message or an ask reply, the receiver gets its own copy.

import bytes
import crypto
import secrets

-- Holds the data key while the vault is open.
partition KeyCache
  state key = nil

  on Load(k)
    key = k
  end

  ask Key()
    return key
  end

  on Lock()
    key.release()
    key = nil
  end
end

let cache = KeyCache()
tell cache.Load(crypto.random_bytes(32, { as_secret = true })?)

let k = ask cache.Key() timeout 1s        -- this partition's own copy
let nonce = crypto.random_bytes(12)?
let sealed = crypto.aes_gcm_encrypt(k, nonce, "hello")?
print(k, len(sealed))

k.release()                               -- stops this copy, not the cache's
let again = ask cache.Key() timeout 1s
print(len(again))
print(bytes.to_string(crypto.aes_gcm_decrypt(again, nonce, sealed)?)?)

tell cache.Lock()
let after = ask cache.Key() timeout 1s
print(after, len(again))
$ scua keycache.scua
<secret> 21
32
hello
nil 32

In the last line, the cache has released its own copy, and the copy the main script took earlier still works. Each copy is released by the partition that holds it. A request, an actor or a handler that took a copy keeps it until it releases it or its memory is reused, so a Lock action doesn't erase anything another partition holds.

http.serve's context works the same way: each request gets its own copy of each secret in it, and releasing it stops that request's copy only.

#Release a secret when you are done

s.release() stops a secret at once, for every reference to it in this partition: it zeroes the bytes and sets the length to 0. Any later use faults, naming the line that released it, and a call that returns a Result gives Error({ kind = "released" }) instead:

import secrets

let pw = secrets.of("hunter22")
let same = pw
pw.release()
print(same)
print(pcall(fn() return len(same) end))
$ scua release.scua
<secret>
Error(this secret was released at line 5.)

Releasing twice is fine. Releasing zeroes this one copy, so treat it as hygiene: it doesn't erase every copy of the bytes. Copies sent to other partitions, copies the memory manager left behind as it moved values, and secrets built from this one (a secrets.format result, say) are not reached.

Code you hand a secret to can release it, which stops yours too. To hand a package a secret without that power, pass secrets.copy(s), a new secret with the same bytes.

bytes.wipe(b) zeroes a bytes value or a { u8 } buffer in place, for a copy you couldn't avoid, such as a request body that held a password. It clears only the current copy of the value.

#Where a secret can't go

  • Constants. A top-level const and freeze refuse a secret, since a constant is shared, read-only data that nothing releases: "a constant can't hold a secret, and C.k is one. Pass it to handlers through http.serve's context, or to an actor in a message."
  • Sandboxes. A sandbox can't hold or make one, and the secrets module isn't there. Resolve a secret outside the sandbox and pass the sandbox only its name.
  • Saves. durable.encode refuses a secret, naming where it sits. Save where it comes from instead (a file name, a variable's name, its ciphertext) and read it again after loading.
  • Snapshots. Snapshotting a partition never fails because of a secret, but the snapshot doesn't keep it: after a revive each secret is wiped, and the program reads it again. Hibernate a session shows the pattern.

#Reveal on purpose

s.reveal() returns the bytes as a string and s.reveal_bytes() as bytes. From there on that copy is ordinary data: it prints, logs and compares like any string. Call them where the plain value really is the point, such as showing a stored password to its owner. reveal() faults when the bytes are not UTF-8 text; use reveal_bytes() for those.

#Review where secrets go

scua check --secrets reads the program and every module it loads, vendored packages included, runs nothing, and lists every place a secret's protection is handed on: every call of a method named reveal or reveal_bytes, and every call that could write out of the process.

import env
import http
import secrets

let token = env.get("API_TOKEN", { as_secret = true })
let res = http.request("https://api.example.com/v1/me", {
  headers = { authorization = secrets.format("Bearer {}", token) },
})
print(token.reveal())
fn forward(conn, data) return conn.write(data) end
$ scua check --secrets app.scua
the program:
  app.scua:6: http.request writes out of the process, and may carry a secret
  app.scua:9: token.reveal() reveals a secret: from here it is a plain copy
  app.scua:10: conn.write may write out of the process (a handle's method, or a module passed as a value), and may carry a secret
1 reveal, 2 writes out of the process, in 1 module. Not seen: code loaded at run time.

A write is marked "may carry a secret" unless every argument is written as plain text in the source: a literal, a .. or a template, none of which can hold one. http.serve is always marked, since its handler's responses aren't at the call. A package's findings are listed under its name and version, so a reviewer sees what a dependency does with a secret it is given. Taking reveal as a value (let f = s.reveal) is listed too.

The list errs on the side of listing too much. Besides a write called through its module's name (net.write(conn, data)), it lists a call of a write's name on any other value, since a handle's methods are its module's writes (conn.write(data)) and a module passed around as a value has them too (ctx.http.request(url)). It also lists a call by a computed name (t[name](x)), a write taken as a value (let w = net.write), and a module that writes used as a value (setup(http), import("http")), through which a later call may write. So a method of your own named write, send or start is listed as well. Only code loaded while the program runs is out of its sight.

#Logs, faults and the debugger

print, logging, fault messages and the value of an Error show <secret>, with no length or prefix. So do scua test's values, the debugger's variable view, and --debug-values, which shows the values faults otherwise hide but still shows a secret as <secret>. A host's log sink gets the fields already rendered, and gets no structured fields at all for a line that held a secret. The debugger's evaluate can call reveal(), as any code can.

#What a secret does not protect

This version protects against accidental disclosure. It does not protect the bytes in memory, and it can't stop code that holds a secret from reading it.

  • Memory. A secret's bytes live on the heap. They can be swapped to disk or appear in a crash dump. The memory manager copies values as it runs and may leave an old copy behind until that memory is reused. release() zeroes only the copy it is called on.
  • Code you hand a secret to. Any code holding a secret can call reveal(), or read the bytes back through something it controls: write them to a file and read the file, encrypt them and decrypt without as_secret, pipe them through a command. A package you call runs with your program's authority, so it can do the same. Only a sandbox is kept from secrets, because it can't hold one. scua check --secrets is how you review what your code and its packages do with them.
  • What a child process or a server sends back. A command or a server given a credential can echo it. exec's stderr is returned unscrubbed. secrets.redact is the filter, and it is best effort.
  • Copies made before the secret existed. A password in a request body, a token in a header not named in secret_headers, a key decoded with bytes.from_hex, the text json.decode read: those copies are already ordinary values. secrets.of(v) protects only from then on.
  • URLs. --serve-log writes each request's path and query string, and other servers log the URLs they are sent. Put tokens in headers.
  • Secrets built from one another. Releasing pw doesn't release a secrets.format or secrets.encode result built from it.
  • Revealed values. After reveal(), a string is a string.
  • The environment. env.get with as_secret keeps the value out of your program's strings, but the process's environment still holds it as text.
  • Anything outside SCUA's memory. TLS buffers, the operating system's socket buffers, a child process's memory, a terminal's scrollback, and anything native code reads from the process.
  • Lengths and timing. len(s) is available, so a secret built from several parts shows their total length. secrets.equal takes the same time for the same lengths, so it shows only the lengths. secrets.redact's time and secrets.json's escaping depend on the data.

Holding a secret costs a little. A partition that holds a live secret zeroes the memory it frees, which makes very small messages sent from it a few percent slower, and its == does a little more work when the answer is no. A partition that holds no secret pays nothing, and the cost stops at the first collection after its last secret is gone.

#See also