#[path = "support/cc_cache.rs"]
mod cc_cache;
#[path = "support/toolchain.rs"]
mod toolchain;
use cverif::image::Image;
use cverif::verify::{FuncReport, Options, Report, Status, verify};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
#[derive(Clone, Copy)]
struct Cc {
name: &'static str,
bin: &'static str,
target: &'static [&'static str],
levels: &'static [&'static str],
}
const GCC: Cc = Cc {
name: "gcc",
bin: "arm-none-eabi-gcc",
target: &[],
levels: &["-O0", "-O1", "-O2", "-O3", "-Os"],
};
const CLANG: Cc = Cc {
name: "clang",
bin: "clang",
target: &["--target=arm-none-eabi"],
levels: &["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz"],
};
fn root() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
}
fn corpus() -> PathBuf {
root().join("tests/corpus/ct.c")
}
fn include() -> PathBuf {
root().join("include")
}
impl Cc {
fn try_compile(&self, src: &Path, cpu: &str, level: &str) -> Result<PathBuf, String> {
self.try_compile_with(src, cpu, level, &[])
}
fn try_compile_with(&self, src: &Path, cpu: &str, level: &str, defines: &[&str]) -> Result<PathBuf, String> {
static SERIAL: AtomicU32 = AtomicU32::new(0);
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
std::fs::create_dir_all(&dir).unwrap();
let stem = src.file_stem().unwrap().to_string_lossy();
let tag: String = defines.iter().map(|d| format!("-{d}")).collect();
let obj = dir.join(format!("{stem}{tag}-{}-{cpu}{level}.o", self.name));
let part = dir.join(format!(
"{stem}{tag}-{}-{cpu}{level}.{}.{}.part",
self.name,
std::process::id(),
SERIAL.fetch_add(1, Ordering::Relaxed)
));
let (core, hard) = match cpu.strip_suffix("+hard") {
Some(core) => (core, true),
None => (cpu, false),
};
let float: &[&str] = match (hard, core) {
(false, _) => &["-mfloat-abi=soft"],
(true, "cortex-m7") => &["-mfloat-abi=hard", "-mfpu=fpv5-d16"],
(true, _) => &["-mfloat-abi=hard", "-mfpu=fpv4-sp-d16"],
};
let out = cc_cache::output(
Command::new(self.bin)
.args(self.target)
.args(["-mthumb", &format!("-mcpu={core}"), level, "-g", "-ffreestanding"])
.args(float)
.args(defines.iter().map(|d| format!("-D{d}")))
.args(["-Wall", "-Wextra", "-Werror", "-c"])
.arg("-I")
.arg(include())
.arg(src)
.arg("-o")
.arg(&part),
)
.map_err(|e| e.to_string())?;
if !out.status.success() {
let _ = std::fs::remove_file(&part);
return Err(String::from_utf8_lossy(&out.stderr).into_owned());
}
std::fs::rename(&part, &obj).map_err(|e| e.to_string())?;
Ok(obj)
}
fn compile(&self, cpu: &str, level: &str) -> PathBuf {
self.try_compile(&corpus(), cpu, level)
.unwrap_or_else(|e| panic!("{} {cpu} {level} failed: {e}", self.bin))
}
fn available(&self) -> bool {
let flags = [self.target, &["-mthumb", "-mcpu=cortex-m3"]].concat();
toolchain::available(self.bin, &flags, self.name)
}
}
fn check_with(obj: &Path, cpu: &str, undefine: &[&str], opts: Options) -> Report {
check_source(obj, &corpus(), cpu, undefine, &[], opts)
}
fn check_source(obj: &Path, src: &Path, cpu: &str, undefine: &[&str], defines: &[&str], opts: Options) -> Report {
let src = src.to_path_buf();
let defines: Vec<(String, String)> = defines.iter().map(|d| (d.to_string(), "1".to_string())).collect();
let mut image = Image::from_elf(&std::fs::read(obj).unwrap()).expect("load ELF");
let core = cpu.strip_suffix("+hard").unwrap_or(cpu);
image.profile = image.profile.declared(Some(core), None).expect("a known core");
let undefines: Vec<String> = undefine.iter().map(|s| s.to_string()).collect();
std::thread::Builder::new()
.stack_size(32 << 20)
.spawn(move || {
let mut copts = cverif::c::Options::for_image(&image);
copts.include_dirs.push(include());
copts.undefines = undefines;
copts.defines.extend(defines);
let prog = cverif::c::parse_files(&[src], &copts).expect("parse C");
verify(&prog, &image, &opts)
})
.unwrap()
.join()
.unwrap()
}
fn options() -> Options {
{
let mut built = Options::default();
built.jobs = 2;
built.work_limit = 200_000;
built.time_limit = Duration::from_secs(600);
built
}
}
fn check(obj: &Path, cpu: &str) -> Report {
check_with(obj, cpu, &[], options())
}
fn build(cc: Cc, cpu: &str, level: &str) -> Report {
check(&cc.compile(cpu, level), cpu)
}
fn func<'a>(r: &'a Report, name: &str) -> &'a FuncReport {
r.funcs
.iter()
.find(|f| f.name == name)
.unwrap_or_else(|| panic!("{name} was not verified"))
}
fn claim(f: &FuncReport) -> &str {
f.constant_time.as_ref().map_or("none", |c| c.claim)
}
const COMPILER_LEAKS: &[(&str, &str, &[&str], &[&str])] = &[
("gcc", "cortex-m3", &["-O0"], &["cand_ternary"]),
("gcc", "cortex-m4", &["-O0"], &["cand_ternary"]),
("clang", "cortex-m3", &["-O0"], &["cand_ternary"]),
("clang", "cortex-m4", &["-O0"], &["cand_ternary"]),
("gcc", "cortex-m7", &["-O0"], &["cand_ternary"]),
("clang", "cortex-m7", &["-O0"], &["cand_ternary"]),
("gcc", "cortex-m3", &["-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
("gcc", "cortex-m4", &["-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
("gcc", "cortex-m7", &["-O1", "-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
(
"clang",
"cortex-m7",
&["-O1", "-O2", "-O3", "-Os", "-Oz"],
&["cand_mask_lt64"],
),
(
"clang",
"cortex-m3",
&["-O1", "-O2", "-O3", "-Os", "-Oz"],
&["cand_mask_lt64"],
),
(
"clang",
"cortex-m4",
&["-O1", "-O2", "-O3", "-Os", "-Oz"],
&["cand_mask_lt64"],
),
("clang", "cortex-m3", &["-Os", "-Oz"], &["cand_abs"]),
("clang", "cortex-m4", &["-Os", "-Oz"], &["cand_abs"]),
("clang", "cortex-m7", &["-Os", "-Oz"], &["cand_abs"]),
(
"gcc",
"cortex-m0",
&["-O0"],
&["cand_ternary", "cand_max_s", "cand_mask_lt64"],
),
(
"gcc",
"cortex-m0",
&["-O1", "-O2", "-Os"],
&[
"cand_mask_lt",
"cand_mask_lt64",
"cand_select_nz",
"cand_ternary",
"cand_min_lt",
"cand_lookup_eq",
"cand_max_s",
],
),
(
"gcc",
"cortex-m0",
&["-O3"],
&[
"cand_mask_lt",
"cand_mask_lt64",
"cand_select_nz",
"cand_ternary",
"cand_min_lt",
"cand_max_s",
],
),
(
"clang",
"cortex-m0",
&["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz"],
&[
"cand_mask_lt",
"cand_mask_lt64",
"cand_select_nz",
"cand_ternary",
"cand_min_lt",
"cand_eq_mask",
"cand_lookup_eq",
"cand_max_s",
],
),
(
"clang",
"cortex-m0",
&["-O1", "-O2", "-O3", "-Os", "-Oz"],
&["ct_lookup", "ct_min", "ct_max", "ct_calls_ct"],
),
("clang", "cortex-m0", &["-O1", "-Os", "-Oz"], &["cand_bool_acc"]),
];
const EQUIVALENCE_BOUNDED: &[(&str, &[&str], &str)] = &[("gcc", &["-O3"], "ct_cswap8")];
const FIXED_IN_CLANG: &[(&str, u32)] = &[("cand_abs", 22)];
const INTRODUCED_IN_GCC: &[(&str, u32)] = &[("cand_mask_lt", 16), ("cand_select_nz", 16)];
fn gcc_major() -> Option<u32> {
static MAJOR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
*MAJOR.get_or_init(|| {
let out = Command::new(GCC.bin).arg("-dumpversion").output().ok()?;
String::from_utf8_lossy(&out.stdout)
.trim()
.split('.')
.next()?
.parse()
.ok()
})
}
fn clang_major() -> Option<u32> {
static MAJOR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
*MAJOR.get_or_init(|| {
let out = Command::new(CLANG.bin).arg("--version").output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let first = text.lines().next()?;
let rest = first.strip_prefix("clang version ").or_else(|| {
(!first.starts_with("Apple")).then(|| first.split_once(" clang version ").map(|s| s.1))?
})?;
rest.split('.').next()?.trim().parse().ok()
})
}
fn compiler_leaks(cc: &str, cpu: &str, level: &str) -> Vec<&'static str> {
let core = cpu.strip_suffix("+hard").unwrap_or(cpu);
let fixed = |f: &str| {
(cc == "clang"
&& FIXED_IN_CLANG
.iter()
.any(|&(g, v)| g == f && clang_major().is_some_and(|m| m >= v)))
|| (cc == "gcc"
&& INTRODUCED_IN_GCC
.iter()
.any(|&(g, v)| g == f && gcc_major().is_some_and(|m| m < v)))
};
COMPILER_LEAKS
.iter()
.filter(|l| l.0 == cc && l.1 == core && l.2.contains(&level))
.flat_map(|l| l.3.iter().copied())
.filter(|f| !fixed(f))
.collect()
}
fn expect(cc: &str, cpu: &str, level: &str, r: &Report) -> Vec<String> {
let leaks = compiler_leaks(cc, cpu, level);
let mut bad = Vec::new();
for f in &r.funcs {
let n = f.name.as_str();
let is_violation = matches!(f.status, Status::CtViolation(_));
let ct_proved = f.status == Status::Proved && claim(f) == "proved";
let bounded = matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded";
let ok = if leaks.contains(&n) {
is_violation
} else if EQUIVALENCE_BOUNDED
.iter()
.any(|e| e.0 == cc && e.1.contains(&level) && e.2 == n)
{
ct_proved || bounded
} else if n == "ct_memcmp" {
(f.status == Status::Proved && claim(f) == "proved")
|| (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded")
} else if n == "leak_mul64" && cpu.starts_with("cortex-m4") {
ct_proved
} else if n.starts_with("fp_") {
if cpu == "cortex-m4+hard" {
ct_proved
} else {
is_violation
}
} else if n == "leak_delay" {
is_violation || (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded")
} else if n.starts_with("leak_") {
is_violation
} else if n.starts_with("ct_") || n.starts_with("cand_") {
ct_proved
} else if n == "key_byte_helper" || n == "key_test_helper" {
let checked = |c: &str| f.constant_time.as_ref().is_some_and(|ct| ct.checked_for == [c]);
(f.status == Status::Proved && f.constant_time.is_none())
|| if n == "key_byte_helper" {
ct_proved && checked("leak_key_result")
} else {
is_violation && checked("leak_key_callee")
}
} else if n == "plain_lookup_helper" {
is_violation && f.constant_time.as_ref().is_some_and(|c| !c.checked_for.is_empty())
} else if n == "plain_helper" {
ct_proved
&& f.constant_time
.as_ref()
.is_some_and(|c| c.checked_for == ["ct_calls_plain"])
} else {
f.status == Status::Proved && f.constant_time.is_none()
};
if !ok {
bad.push(format!(
" {cc} {cpu} {level}: {} {n} [{}]: {}",
f.status.label(),
claim(f),
f.status.detail()
));
}
if is_violation
&& f.constant_time
.as_ref()
.is_some_and(|c| c.violation.is_some() && c.source.is_none())
{
bad.push(format!(" {cc} {cpu} {level}: {n}: violation without a source line"));
}
}
for want in [
"ct_memcmp16",
"ct_lookup",
"leak_sbox",
"cand_abs",
"leak_delay",
"plain_mix",
"fp_scale",
"ct_calls_ct_ni",
] {
if !r.funcs.iter().any(|f| f.name == want) {
bad.push(format!(" {cc} {cpu} {level}: {want} was not verified"));
}
}
bad
}
fn matrix(cc: Cc, cpu: &str) {
if !cc.available() {
return;
}
let mut bad = Vec::new();
for level in cc.levels {
let r = build(cc, cpu, level);
let v = r
.funcs
.iter()
.filter(|f| matches!(f.status, Status::CtViolation(_)))
.count();
eprintln!(
"ct.c {} {cpu} {level}: {} functions, {v} not constant time",
cc.name,
r.funcs.len()
);
bad.extend(expect(cc.name, cpu, level, &r));
}
assert!(bad.is_empty(), "unexpected constant-time results:\n{}", bad.join("\n"));
}
#[test]
fn gcc_cortex_m0() {
matrix(GCC, "cortex-m0");
}
#[test]
fn gcc_cortex_m3() {
matrix(GCC, "cortex-m3");
}
#[test]
fn gcc_cortex_m4() {
matrix(GCC, "cortex-m4");
}
#[test]
fn clang_cortex_m0() {
matrix(CLANG, "cortex-m0");
}
#[test]
fn clang_cortex_m3() {
matrix(CLANG, "cortex-m3");
}
#[test]
fn clang_cortex_m4() {
matrix(CLANG, "cortex-m4");
}
#[test]
fn gcc_cortex_m4_hard_float() {
matrix(GCC, "cortex-m4+hard");
}
#[test]
fn clang_cortex_m4_hard_float() {
matrix(CLANG, "cortex-m4+hard");
}
#[test]
fn gcc_cortex_m7_hard_float() {
matrix(GCC, "cortex-m7+hard");
}
#[test]
fn clang_cortex_m7_hard_float() {
matrix(CLANG, "cortex-m7+hard");
}
#[test]
fn modular_calls() {
for cc in [GCC, CLANG] {
if !cc.available() {
continue;
}
for level in ["-O1", "-O2", "-Os"] {
let r = build(cc, "cortex-m3", level);
let ok = func(&r, "ct_calls_ct_ni");
let ct = ok.constant_time.as_ref().expect("marked");
assert_eq!(ct.claim, "proved", "{} {level}: {}", cc.name, ok.status.detail());
assert!(
ct.rests_on.iter().any(|c| c.0 == "ct_mix_ni" && c.1 == "proved"),
"{} {level}: {:?}",
cc.name,
ct.rests_on
);
let bad = func(&r, "leak_calls_leaky");
assert!(
matches!(&bad.status, Status::CtViolation(d) if d.contains("leak_sbox_ni")),
"{} {level}: {}",
cc.name,
bad.status.detail()
);
let plain = func(&r, "leak_calls_plain");
assert!(
matches!(&plain.status, Status::CtViolation(d) if d.starts_with("gives secrets to plain_lookup_helper, ")),
"{} {level}: {}",
cc.name,
plain.status.detail()
);
let ok = func(&r, "ct_calls_plain");
let ct = ok.constant_time.as_ref().expect("marked");
assert!(
ok.status == Status::Proved
&& ct.claim == "proved"
&& ct.rests_on.iter().any(|c| c.0 == "plain_helper" && c.1 == "proved"),
"{} {level}: {} {:?}",
cc.name,
ok.status.detail(),
ct.rests_on
);
let mut strict = options();
strict.ct.no_callees = true;
let obj = cc.compile("cortex-m3", level);
let r = check_with(&obj, "cortex-m3", &[], strict);
let plain = func(&r, "ct_calls_plain");
assert!(
matches!(&plain.status, Status::CtViolation(d) if d.contains("argument 1 of the call to plain_helper")),
"{} {level} --no-ct-callees: {}",
cc.name,
plain.status.detail()
);
assert!(func(&r, "plain_helper").constant_time.is_none());
}
}
}
fn line_of(text: &str) -> u32 {
let src = std::fs::read_to_string(corpus()).unwrap();
src.lines().position(|l| l.contains(text)).expect("text in the corpus") as u32 + 1
}
#[test]
fn reasons_and_witnesses() {
if GCC.available() {
let r = build(GCC, "cortex-m3", "-O2");
let d = |n: &str| func(&r, n).status.detail().to_string();
assert!(
d("leak_mod").contains("udiv") && d("leak_mod").contains("Cortex-M3"),
"{}",
d("leak_mod")
);
assert!(d("leak_mul64").contains("umull") && d("leak_mul64").contains("finish early"));
assert!(
d("leak_memcmp").contains("a[0]") && d("leak_memcmp").contains("b[0]"),
"{}",
d("leak_memcmp")
);
assert!(
d("leak_sbox").contains("address of a 1-byte load"),
"{}",
d("leak_sbox")
);
assert!(d("leak_call").contains("argument 1 of the call to ext_consume"));
assert!(
d("leak_calls_plain").contains("plain_lookup_helper"),
"{}",
d("leak_calls_plain")
);
assert!(d("leak_key_index").contains("device_key[3]"), "{}", d("leak_key_index"));
let sbox = func(&r, "leak_sbox").constant_time.clone().unwrap();
let v = sbox.violation.expect("a violation");
let line = sbox.source.map(|s| s.1).unwrap_or(0);
let want = line_of("return sbox[x & 0xff];");
assert!(line == want || line == want + 1, "line {line}, expected {want}");
assert!(v.witness.contains("with secret x = "), "{}", v.witness);
assert_eq!(claim(func(&r, "ct_calls_ct")), "proved");
assert_eq!(claim(func(&r, "ct_key_diff")), "proved");
let m0 = build(GCC, "cortex-m0", "-Os");
let d = func(&m0, "leak_mod").status.detail().to_string();
assert!(d.contains("__aeabi_uidivmod"), "{d}");
}
if CLANG.available() {
let r = build(CLANG, "cortex-m3", "-O2");
let d = func(&r, "leak_condload").status.detail().to_string();
assert!(d.contains("in an IT block") && d.contains("ldr"), "{d}");
assert_eq!(claim(func(&r, "cand_mask_lt")), "proved");
}
}
#[test]
fn loops_by_induction() {
if !GCC.available() {
return;
}
let r = build(GCC, "cortex-m3", "-O2");
let f = func(&r, "ct_memcmp");
assert_eq!(f.status, Status::Proved);
let note = &f.constant_time.as_ref().unwrap().note;
assert!(note.contains("every loop iteration"), "{note}");
let r = build(GCC, "cortex-m0", "-Os");
let f = func(&r, "leak_delay");
assert!(
matches!(&f.status, Status::Bounded(d) if d.contains("constant time only for the loop iterations explored")),
"{}: {}",
f.status.label(),
f.status.detail()
);
assert_eq!(claim(f), "bounded");
}
#[test]
fn equivalence_unchanged() {
for (cc, cpu) in [(GCC, "cortex-m3"), (CLANG, "cortex-m0")] {
if !cc.available() {
continue;
}
let obj = cc.compile(cpu, "-Os");
let with = check(&obj, cpu);
let without = check_with(&obj, cpu, &["__CVERIF__"], options());
assert!(without.funcs.iter().all(|f| f.constant_time.is_none()));
for f in &without.funcs {
let g = func(&with, &f.name);
let same = match (&f.status, &g.status) {
(Status::Mismatch(_), s) | (s, Status::Mismatch(_)) => {
matches!(s, Status::Mismatch(_))
}
(Status::Proved, s) => {
matches!(s, Status::Proved | Status::CtViolation(_))
|| matches!(s, Status::Bounded(_)) && claim(g) == "bounded"
}
(_, Status::CtViolation(_)) => true,
(Status::Bounded(_), Status::Proved) => g.constant_time.is_some(),
(a, b) => a.label() == b.label(),
};
if f.constant_time.is_none() && g.constant_time.is_none() {
assert_eq!(f.status, g.status, "{}: an unmarked function", f.name);
}
assert!(
same,
"{} {cpu}: {} is {} without the marks, {} with",
cc.name,
f.name,
f.status.label(),
g.status.label()
);
}
}
}
#[test]
fn annotations_parse() {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("annotations.c");
std::fs::write(
&src,
"#include \"cverif.h\"\n\
SECRET unsigned char key[16];\n\
unsigned char nonce[16];\n\
CT int f(const unsigned char *SECRET a, int n);\n\
int f(const unsigned char *a, SECRET int n) { return a[0] + n; }\n\
int g(int x) CT;\n\
int g(int x) { return x; }\n\
int h(int x) { return x; }\n",
)
.unwrap();
let copts = {
let mut built = cverif::c::Options::default();
built.include_dirs = vec![include()];
built
};
let p = cverif::c::parse_files(std::slice::from_ref(&src), &copts).expect("parse");
let ct: Vec<&str> = p.constant_time.iter().map(|s| &**s).collect();
assert!(ct.contains(&"f") && ct.contains(&"g") && !ct.contains(&"h"), "{ct:?}");
let f: Vec<usize> = p.secret_params.get("f").unwrap().iter().copied().collect();
assert_eq!(f, vec![0, 1]);
assert!(p.secret_globals.iter().any(|g| &**g == "key"));
assert!(!p.secret_globals.iter().any(|g| &**g == "nonce"));
let copts = {
let mut built = cverif::c::Options::default();
built.include_dirs = vec![include()];
built.undefines = vec!["__CVERIF__".into()];
built
};
let p = cverif::c::parse_files(&[src], &copts).expect("parse");
assert!(p.constant_time.is_empty() && p.secret_params.is_empty() && p.secret_globals.is_empty());
}
fn cli(obj: &Path, args: &[&str]) -> (i32, String) {
let out = Command::new(env!("CARGO_BIN_EXE_cverif"))
.args(args)
.arg("-I")
.arg(include())
.arg(obj)
.arg(corpus())
.output()
.unwrap();
(
out.status.code().unwrap_or(-1),
String::from_utf8_lossy(&out.stdout).into_owned(),
)
}
fn line_for<'a>(out: &'a str, name: &str) -> &'a str {
out.lines()
.find(|l| l.split_whitespace().nth(1) == Some(name))
.unwrap_or_else(|| panic!("no line for {name} in\n{out}"))
}
#[test]
fn command_line() {
if !GCC.available() {
return;
}
let obj = GCC.compile("cortex-m3", "-O2");
let json = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct").join("cli.json");
let (code, out) = cli(
&obj,
&[
"--constant-time",
"plain_lookup:k",
"--secret",
"session_nonce",
"--constant-time",
"plain_mix:*tbl",
"--only",
"plain_lookup",
"--only",
"plain_mix",
"--json",
json.to_str().unwrap(),
],
);
assert_eq!(code, 1, "{out}");
assert!(line_for(&out, "plain_lookup").starts_with("CT-VIOLATION"), "{out}");
assert!(
line_for(&out, "plain_lookup").contains("address of a 4-byte load"),
"{out}"
);
assert!(
line_for(&out, "plain_mix").starts_with("PROVED") && line_for(&out, "plain_mix").contains("[constant time]")
);
assert!(out.contains("verdict: CT-VIOLATION"), "{out}");
let j = std::fs::read_to_string(&json).unwrap();
assert!(j.contains("\"verdict\": \"ct-violation\""), "{j}");
assert!(j.contains("\"status\":\"ct-violation\""));
assert!(j.contains("\"constant_time\":{\"claim\":\"violation\""));
assert!(j.contains("\"witness\":"));
assert!(j.contains("\"constant_time\":{\"claim\":\"proved\",\"note\":\"constant time\""));
let (code, out) = cli(&obj, &["--constant-time", "plain_mix:0", "--only", "plain_mix"]);
assert_eq!(code, 0, "{out}");
assert!(line_for(&out, "plain_mix").contains("[constant time]"), "{out}");
let (code, out) = cli(&obj, &["--constant-time", "plain_lookup:1", "--only", "plain_lookup"]);
assert_eq!(code, 1, "{out}");
assert!(line_for(&out, "plain_lookup").contains("with secret tbl = "), "{out}");
let (code, out) = cli(&obj, &["--cpu", "cortex-m4", "--only", "leak_mul64"]);
assert_eq!(code, 0, "{out}");
assert!(line_for(&out, "leak_mul64").contains("[constant time]"), "{out}");
let (code, _) = cli(&obj, &["--constant-time", "no_such_function"]);
assert_eq!(code, 2);
let (code, _) = cli(&obj, &["--constant-time", "plain_lookup:zz"]);
assert_eq!(code, 2);
let (code, _) = cli(&obj, &["--secret", "no_such_object"]);
assert_eq!(code, 2);
}
fn run_cverif(args: &[&std::ffi::OsStr]) -> (i32, String) {
let out = Command::new(env!("CARGO_BIN_EXE_cverif")).args(args).output().unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
(out.status.code().unwrap_or(-1), text)
}
fn tool(bin: &str, args: &[&std::ffi::OsStr]) -> Vec<u8> {
let out = Command::new(bin).args(args).output().expect(bin);
assert!(out.status.success(), "{bin}: {}", String::from_utf8_lossy(&out.stderr));
out.stdout
}
fn mark_table(nm: &str, marks: &[(&str, &str)]) -> String {
let mut out = String::new();
for line in nm.lines() {
out.push_str(line);
let name = line.split_whitespace().last().unwrap_or("");
if let Some((_, m)) = marks.iter().find(|(n, _)| *n == name) {
out.push(' ');
out.push_str(m);
}
out.push('\n');
}
out
}
fn expect_tagged(out: &str, code: i32, what: &str) {
assert_eq!(code, 1, "{what}:\n{out}");
for f in ["tag_compare", "tag_key_mix"] {
let l = line_for(out, f);
assert!(
l.starts_with("PROVED") && l.contains("[constant time"),
"{what}: {f}\n{out}"
);
}
for f in ["tag_compare_leaky", "tag_key_lookup"] {
assert!(line_for(out, f).starts_with("CT-VIOLATION"), "{what}: {f}\n{out}");
}
}
#[test]
fn symbol_table_marks() {
if !GCC.available() {
return;
}
let src = root().join("tests/corpus/ct_tags.c");
let obj = GCC.try_compile(&src, "cortex-m3", "-O2").expect("compile");
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
let p = |name: &str| dir.join(format!("ct_tags-{}-{name}", std::process::id()));
let (elf, bin, table) = (p("linked.elf"), p("linked.bin"), p("table.sym"));
let os = |s: &Path| s.as_os_str().to_owned();
tool(
"arm-none-eabi-gcc",
&[
"-mthumb".as_ref(),
"-mcpu=cortex-m3".as_ref(),
"-nostdlib".as_ref(),
"-Wl,-Ttext=0x08000000".as_ref(),
"-Wl,-Tbss=0x20000000".as_ref(),
"-Wl,-e,tag_compare".as_ref(),
"-o".as_ref(),
&os(&elf),
&os(&obj),
],
);
tool(
"arm-none-eabi-objcopy",
&[
"-O".as_ref(),
"binary".as_ref(),
"-j".as_ref(),
".text".as_ref(),
&os(&elf),
&os(&bin),
],
);
let marks = [
("tag_compare", "ct=*a,*b"),
("tag_compare_leaky", "ct=*0,*1"),
("tag_key_mix", "ct"),
("tag_key_lookup", "ct"),
("round_keys", "secret"),
];
let nm = String::from_utf8(tool("arm-none-eabi-nm", &["-S".as_ref(), &os(&elf)])).unwrap();
std::fs::write(&table, mark_table(&nm, &marks)).unwrap();
let common = |extra: &[&std::ffi::OsStr]| -> Vec<std::ffi::OsString> {
let mut v: Vec<std::ffi::OsString> = vec!["--cpu".into(), "cortex-m3".into()];
v.extend(extra.iter().map(|s| s.to_os_string()));
v
};
let go = |extra: &[&std::ffi::OsStr], binary: &Path, table: &Path| {
let mut v = common(extra);
v.extend(["--symbols".into(), os(table), os(binary), os(&src)]);
let refs: Vec<&std::ffi::OsStr> = v.iter().map(|s| s.as_os_str()).collect();
run_cverif(&refs)
};
let (code, out) = go(&[], &elf, &table);
expect_tagged(&out, code, "ELF");
let plain = p("plain.sym");
std::fs::write(&plain, &nm).unwrap();
let (code, out) = go(&[], &elf, &plain);
assert_eq!(code, 0, "{out}");
assert!(!out.contains("constant time"), "{out}");
let (code, out) = go(&["--base".as_ref(), "08000000".as_ref()], &bin, &table);
expect_tagged(&out, code, "raw binary");
let otable = p("obj.sym");
let onm = String::from_utf8(tool("arm-none-eabi-nm", &["-S".as_ref(), &os(&obj)])).unwrap();
std::fs::write(&otable, mark_table(&onm, &marks)).unwrap();
let (code, out) = go(&[], &obj, &otable);
expect_tagged(&out, code, "object");
let (code, out) = go(
&[
"--constant-time".as_ref(),
"tag_compare:n".as_ref(),
"--constant-time".as_ref(),
"tag_key_mix".as_ref(),
"--secret".as_ref(),
"round_keys".as_ref(),
],
&elf,
&table,
);
assert_eq!(code, 1, "{out}");
assert!(line_for(&out, "tag_compare").starts_with("CT-VIOLATION"), "{out}");
assert!(line_for(&out, "tag_key_mix").contains("[constant time"), "{out}");
let nm_line = |name: &str| {
nm.lines()
.find(|l| l.ends_with(&format!(" {name}")))
.unwrap()
.to_string()
};
let compare = nm_line("tag_compare");
let moved = format!(
"{:08x}{}",
u32::from_str_radix(&compare[..8], 16).unwrap() + 0x40,
&compare[8..]
);
for (bad, why) in [
(
"08000001 T no_such_function ct\n".to_string(),
"no function no_such_function",
),
(format!("{moved} ct\n"), "the line says"),
(
format!("{compare} ct=*nope\n"),
"no parameter *nope (a mark of the symbol table)",
),
(format!("{} ct\n", nm_line("round_keys")), "marks a function"),
(format!("{compare} secret\n"), "marks a data object"),
] {
let t = p("bad.sym");
std::fs::write(&t, bad.as_bytes()).unwrap();
let (code, out) = go(&[], &elf, &t);
assert_eq!(code, 2, "{bad}{out}");
assert!(out.contains(why), "{bad}: {out}");
}
let emitted = p("emitted.sym");
let (code, out) = run_cverif(&[
"--discover".as_ref(),
"--cpu".as_ref(),
"cortex-m3".as_ref(),
"--base".as_ref(),
"08000000".as_ref(),
"--symbols".as_ref(),
&os(&table),
"--emit-symbols".as_ref(),
&os(&emitted),
&os(&bin),
]);
assert_eq!(code, 0, "{out}");
let text = std::fs::read_to_string(&emitted).unwrap();
for (name, mark) in marks {
assert!(
text.lines()
.any(|l| l.split(" #").next().unwrap().ends_with(&format!(" {name} {mark}"))),
"{name} {mark} not written back:\n{text}"
);
}
let (code, out) = go(&["--base".as_ref(), "08000000".as_ref()], &bin, &emitted);
expect_tagged(&out, code, "emitted table");
}
fn callees_corpus() -> PathBuf {
root().join("tests/corpus/ct_callees.c")
}
const CALLEE_LEAKS: &[(&str, &str)] = &[
("leak_calls_lookup", "gives secrets to h_lookup, "),
("leak_first_index", "gives secrets to h_first_index, "),
("leak_chain", "gives secrets to h_l1, "),
("leak_rec", "gives secrets to h_rec_leak, "),
("leak_ext", "argument 1 of the call to ext_mix depends on secrets"),
(
"leak_store_then_ext",
"the call to ext_log may read secrets from memory",
),
(
"leak_store_then_index",
"the address of a 1-byte load depends on secrets",
),
("leak_put_then_index", "the address of a 1-byte load depends on secrets"),
("leak_via_global", "gives secrets to h_read_index, "),
("leak_store_ext", "the call to ext_log may read secrets from memory"),
("leak_local_index", "gives secrets to h_first_index, "),
];
const LEAKY_HELPERS: &[&str] = &[
"h_lookup",
"h_first_index",
"h_l1",
"h_l2",
"h_rec_leak",
"h_read_index",
];
fn callees(cc: Cc) {
if !cc.available() {
return;
}
let src = callees_corpus();
let mut bad = Vec::new();
let mut note = |what: String| bad.push(what);
for level in ["-O0", "-O1", "-O2", "-Os"] {
let tag = format!("{} {level}", cc.name);
let obj = cc.try_compile_with(&src, "cortex-m3", level, &[]).unwrap();
let r = check_source(&obj, &src, "cortex-m3", &[], &[], options());
for f in &r.funcs {
let n = f.name.as_str();
let ct = f.constant_time.as_ref();
let line = format!("{tag}: {} {n} [{}]: {}", f.status.label(), claim(f), f.status.detail());
if let Some(&(_, why)) = CALLEE_LEAKS.iter().find(|l| l.0 == n) {
if !matches!(&f.status, Status::CtViolation(d) if d.starts_with(why)) {
note(format!(" expected a violation ({why}): {line}"));
}
} else if n == "ct_rec" || n == "h_rec" {
let ok = (f.status == Status::Proved && claim(f) == "proved")
|| (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded");
if !ok {
note(format!(" expected constant time (or bounded): {line}"));
}
} else if n.starts_with("ct_") {
if !(f.status == Status::Proved && claim(f) == "proved") {
note(format!(" expected proved constant time: {line}"));
}
} else if n.starts_with("h_") {
if ct.is_none_or(|c| c.checked_for.is_empty()) {
note(format!(" expected a helper checked for its callers: {line}"));
} else if LEAKY_HELPERS.contains(&n) != matches!(f.status, Status::CtViolation(_)) {
note(format!(" helper: {line}"));
}
}
}
for want in ["h_mix", "h_store", "h_c2", "ct_then_ext", "leak_store_then_ext"] {
if !r.funcs.iter().any(|f| f.name == want) {
note(format!(" {tag}: {want} was not verified"));
}
}
let checked_for = |n: &str| {
(r.funcs.iter().find(|f| f.name == n))
.and_then(|f| f.constant_time.as_ref())
.map(|c| c.checked_for.clone())
.unwrap_or_default()
};
if checked_for("h_mix") != ["ct_calls_mix", "ct_then_ext"] || checked_for("h_c2") != ["h_c1"] {
note(format!(
" {tag}: h_mix checked for {:?}, h_c2 for {:?}",
checked_for("h_mix"),
checked_for("h_c2")
));
}
let obj = cc
.try_compile_with(&src, "cortex-m3", level, &["CALLEES_MUTANT"])
.unwrap();
let r = check_source(&obj, &src, "cortex-m3", &[], &["CALLEES_MUTANT"], options());
for n in ["h_pat", "leak_pat_i", "ct_pat_a"] {
let f = func(&r, n);
if !matches!(f.status, Status::CtViolation(_)) {
note(format!(
" {tag} mutant: expected a violation: {} {n}: {}",
f.status.label(),
f.status.detail()
));
}
}
let mut strict = options();
strict.ct.no_callees = true;
let obj = cc.try_compile_with(&src, "cortex-m3", level, &[]).unwrap();
let r = check_source(&obj, &src, "cortex-m3", &[], &[], strict);
let f = func(&r, "ct_calls_mix");
if !matches!(&f.status, Status::CtViolation(d) if d.contains("call to h_mix")) {
note(format!(
" {tag} --no-ct-callees: {}: {}",
f.status.label(),
f.status.detail()
));
}
if r.funcs
.iter()
.any(|f| f.name.starts_with("h_") && f.constant_time.is_some())
{
note(format!(" {tag} --no-ct-callees: a helper was checked"));
}
}
assert!(bad.is_empty(), "unexpected results:\n{}", bad.join("\n"));
}
#[test]
fn callees_gcc() {
callees(GCC);
}
#[test]
fn callees_clang() {
callees(CLANG);
}