Data from outside
- The problem
- What another program prints, what a request carries or what a person types is not up to your program. When it is not what the code expected, that is not a bug in the code but a case the program has to handle.
- An example
- A program asks
gitfor the current commit and assumes the answer is 41 characters long. In a directory that is not a repository, the answer is an error message instead. - What Nikaia checks
- Everything the program reads while it runs comes from outside: the command line, the names of the environment a web server fills, standard input, files, other programs and the network. Only what the build chose, such as assets and data fixed at compile time, is trusted. The compiler knows which values come from outside. A claim about such a value, an
assertor a function's precondition, is refused until a guard handles the bad case where the data arrives; after that line the claim is proved, and the rest of the program can rely on it. The words on the command line can also be taken as parameters ofmain: they are checked againstmain's preconditions before the body runs, and a word that fails ends the program with status 2. A path from outside is opened under a directory the call names, and a name that leaves it, such as../../etc/passwd, is stopped at the call. A map keyed by data from outside gets a hash with a random seed, so whoever sends the keys cannot choose ones that collide. Text from outside written to the log, witheprint,eprintln, the message of apanicor a failedassert, or an uncaught error, is written with its control characters escaped, so it stays on its own line and cannot steer a terminal. - The limit
- The compiler cannot know what valid data is for your program; the guard says that, and the compiler checks that there is one. The rest of the environment is the operator's, such as
env::var("DEPTH"); a program meant to run setuid, or one whose environment a less trusted party sets, declaresenvironment = "untrusted"under[build], and a program started with more rights than its caller that does not declare it stops beforemain. A program that knows who chose its other data says so where it reads it, withtrusted: true:cli::args(trusted: true),fs::read_to_string(path, root; trusted: true). Where the program vouches for a path itself, withfs::Root::Anywhere, the compiler takes its word.nikaia build --trustlists every such marker and every such path, the hash each map got and every log call that escapes. Standard output is the program's data and is written as it is, also on a terminal. A program that writes its own log file escapes the text withtext::escape_control.
Show the program and what Nikaia says
use std::process
fn main() throws {
let out = process::run("git", ["rev-parse", "HEAD"])
let n: int = out.stdout.len()
assert(n == 41)
println(f"commit {out.stdout.trim()}")
}
$ nikaia build
error[NK1202]: `n == 41` is a claim about data from outside the program.
--> …/outa/src/main.nika:6:5
|
6 | assert(n == 41)
| ^^^^^^^^^^^^^^^
|
= note: `n` comes from outside the program, so nothing the compiler can see says what it holds.
= note: That it is wrong is a case the program has to handle, not a defect an `assert` catches.
= help: Check it where it arrives, with a guard the program handles: `throw BadInput(n) if !(n == 41)`, or `return … if !(n == 41)`. After that line, this `assert` is proved.
After an if that handles the bad case, the same assert is proved:
use std::process
fn main() throws {
let out = process::run("git", ["rev-parse", "HEAD"])
let n: int = out.stdout.len()
if n != 41 {
println("not a commit id")
return
}
assert(n == 41)
println(f"commit {out.stdout.trim()}")
}
A name from outside is opened under the directory the call names. The second name leaves it, and the call refuses it:
use std::fs
fn main() throws {
for name in ["a.txt", "../../etc/passwd"] {
let text = fs::read_to_string(name, fs::Root::Dir("store")) catch {
println(f"refused {name}: {error}")
continue
}
println(f"{name}: {text.len()} bytes")
}
}
$ nikaia run main.nika
a.txt: 3 bytes
refused ../../etc/passwd: the name leaves the root it was given: ../../etc/passwd
A variable a web server fills from the request comes from outside as well: a name that starts with HTTP_ or is one of CGI's, such as QUERY_STRING. Here the claim is about a number parsed from a request header:
use std::env
use std::text
fn main() throws {
let depth: i64 = text::parse_i64(env::var("HTTP_X_DEPTH") ?? "8") ?? 8
assert(depth > 0)
println(f"depth {depth}")
}
$ nikaia check main.nika
error[NK1202]: `depth > 0` is a claim about data from outside the program.
--> main.nika:6:5
|
6 | assert(depth > 0)
| ^^^^^^^^^^^^^^^^^
|
= note: `depth` comes from outside the program, so nothing the compiler can see says what it holds.
= note: That it is wrong is a case the program has to handle, not a defect an `assert` catches.
= help: Check it where it arrives, with a guard the program handles: `throw BadInput(depth) if !(depth > 0)`, or `return … if !(depth > 0)`. After that line, this `assert` is proved.
A name read from standard input goes to the log. The first line the program writes holds the name with its line feed escaped; its own usage text keeps its two lines; standard output gets the name as it came:
use std::io
fn main() throws {
let name = io::read_to_string().trim()
eprintln(f"login failed for {name}")
eprintln("usage:\n login NAME")
println(name)
}
$ printf 'x\nlogin ok for admin' | nikaia run main.nika
login failed for x\nlogin ok for admin
usage:
login NAME
x
login ok for admin
--trust names the source and every log call that escapes:
$ nikaia build --trust
input provenance: untrusted
io::read_to_string is untrusted
hash for a map keyed by the input: keyed, per-process random seed - key choice cannot be aimed at the table
file access with no root to check against:
none - every path here names a directory it may not leave
log sinks that write untrusted text escaped:
…/login/src/main.nika:5 eprintln escapes text from io::read_to_string
Go deeper
More under Safe, secure, reliable: Errors that go unhandledCalls that break a function's contractTwo tasks changing the same valueA deadline for every waitTasks that get stuckA memory budget for every task