use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use stegobench_core::registry::Entry;
pub enum Reach {
Container(String),
Local(Vec<String>),
}
impl Reach {
pub fn of(entry: &Entry) -> Result<Reach, String> {
match (entry.image.as_ref(), entry.binary.as_ref()) {
(Some(image), _) => Ok(Reach::Container(image.reference.clone())),
(None, Some(binary)) if !binary.command.is_empty() => {
Ok(Reach::Local(binary.command.clone()))
}
_ => Err("no image and no binary command to run it with".into()),
}
}
fn base(&self, work: &Path) -> String {
match self {
Reach::Container(_) => "/work".to_string(),
Reach::Local(_) => work.display().to_string(),
}
}
}
pub struct Session<'a> {
reach: Reach,
work: PathBuf,
base: String,
entrypoint: Option<&'a str>,
uid_gid: String,
timeout: Duration,
}
impl<'a> Session<'a> {
pub fn new(
reach: Reach,
work: &Path,
entrypoint: Option<&'a str>,
timeout: Duration,
) -> Session<'a> {
let base = reach.base(work);
Session {
reach,
work: work.to_path_buf(),
base,
entrypoint,
uid_gid: owner_of(work),
timeout,
}
}
pub fn base(&self) -> &str {
&self.base
}
pub fn phase(&self, argv: &[String], pairs: &[(&str, &str)]) -> Result<(), String> {
let subst = |a: &String| {
let mut s = a.clone();
for (from, to) in pairs {
s = s.replace(from, to);
}
s
};
match &self.reach {
Reach::Local(command) => {
let mut run = Command::new(subst(&command[0]));
run.args(command[1..].iter().map(&subst));
run.args(argv.iter().map(&subst));
run.current_dir(&self.work);
bounded(run, &command[0], self.timeout)
}
Reach::Container(image) => {
let mut args: Vec<String> = vec![
"run".into(),
"--rm".into(),
"--network=none".into(),
"--cap-drop=ALL".into(),
"--security-opt".into(),
"no-new-privileges".into(),
"--memory=2g".into(),
];
if !self.uid_gid.is_empty() {
args.push("--user".into());
args.push(self.uid_gid.clone());
}
args.push("-v".into());
args.push(format!("{}:/work", self.work.display()));
if let Some(ep) = self.entrypoint {
args.push("--entrypoint".into());
args.push(ep.to_string());
}
args.push(image.clone());
args.extend(argv.iter().map(&subst));
let mut run = Command::new("docker");
run.args(&args);
bounded(run, "the container", self.timeout)
}
}
}
}
fn owner_of(work: &Path) -> String {
std::fs::metadata(work)
.ok()
.map(|m| {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
format!("{}:{}", m.uid(), m.gid())
}
#[cfg(not(unix))]
{
let _ = m;
String::new()
}
})
.unwrap_or_default()
}
fn first_difference(want: &[u8], got: &[u8]) -> String {
match want.iter().zip(got).position(|(a, b)| a != b) {
None => String::new(),
Some(i) => format!(
", and byte {i} of {} differs: expected 0x{:02x}, got 0x{:02x} \
(xor 0x{:02x})",
want.len(),
want[i],
got[i],
want[i] ^ got[i]
),
}
}
pub fn bounded(command: Command, label: &str, timeout: Duration) -> Result<(), String> {
let out = crate::exec::captured(command, label, timeout)?;
if out.status.success() {
return Ok(());
}
let tail = String::from_utf8_lossy(&out.stderr)
.trim()
.chars()
.take(160)
.collect::<String>();
Err(format!("exit {}: {tail}", out.status.code().unwrap_or(-1)))
}
#[derive(Debug, Clone, PartialEq)]
pub struct Embedded {
pub stego: PathBuf,
pub bytes: u64,
pub recovered: Option<Result<(), String>>,
}
pub const PHASE_TIMEOUT: Duration = Duration::from_secs(300);
pub fn run(
entry: &Entry,
cover: &Path,
payload: &Path,
out: &Path,
passphrase: Option<&str>,
extract_check: bool,
) -> Result<Embedded, String> {
let rt = entry
.roundtrip
.as_ref()
.ok_or_else(|| format!("{} declares no way to embed with it", entry.name))?;
let reach = Reach::of(entry)?;
let dir = tempfile::tempdir().map_err(|e| format!("no scratch directory: {e}"))?;
let work = dir.path();
let ext = cover
.extension()
.and_then(|e| e.to_str())
.unwrap_or("bin")
.to_string();
let cover_name = format!("cover.{ext}");
std::fs::copy(cover, work.join(&cover_name))
.map_err(|e| format!("could not stage {}: {e}", cover.display()))?;
std::fs::copy(payload, work.join("payload.bin"))
.map_err(|e| format!("could not stage {}: {e}", payload.display()))?;
let session = Session::new(reach, work, rt.entrypoint.as_deref(), PHASE_TIMEOUT);
let base = session.base().to_string();
let pass = passphrase.unwrap_or(&rt.passphrase);
let stego_in = format!("{base}/stego.{ext}");
let cover_in = format!("{base}/{cover_name}");
let payload_in = format!("{base}/payload.bin");
let recovered_in = format!("{base}/recovered.bin");
let pairs: Vec<(&str, &str)> = vec![
("{cover}", cover_in.as_str()),
("{payload}", payload_in.as_str()),
("{stego}", stego_in.as_str()),
("{recovered}", recovered_in.as_str()),
("{passphrase}", pass),
];
session
.phase(&rt.embed_argv, &pairs)
.map_err(|e| format!("embed failed: {e}"))?;
let staged = work.join(format!("stego.{ext}"));
let bytes = match std::fs::metadata(&staged) {
Ok(m) if m.len() > 0 => m.len(),
_ => return Err("the embedder exited cleanly and wrote no stego file".into()),
};
let recovered = if extract_check && !rt.extract_argv.is_empty() {
Some(match session.phase(&rt.extract_argv, &pairs) {
Err(e) => Err(format!("extract failed: {e}")),
Ok(()) => match (
std::fs::read(work.join("recovered.bin")),
std::fs::read(payload),
) {
(Ok(got), Ok(want)) if got == want => Ok(()),
(Ok(got), Ok(want)) => Err(format!(
"the payload did not survive the round trip: {} bytes went \
in and {} came back{}",
want.len(),
got.len(),
first_difference(&want, &got)
)),
(Err(e), _) => Err(format!("extract wrote no payload: {e}")),
(_, Err(e)) => Err(format!("could not re-read the payload: {e}")),
},
})
} else {
None
};
if let Some(parent) = out.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("could not make {}: {e}", parent.display()))?;
}
}
std::fs::copy(&staged, out).map_err(|e| format!("could not write {}: {e}", out.display()))?;
Ok(Embedded {
stego: out.to_path_buf(),
bytes,
recovered,
})
}
#[cfg(test)]
mod message_tests {
use super::first_difference;
#[test]
fn identical_payloads_name_no_difference() {
assert_eq!(first_difference(b"abc", b"abc"), "");
}
#[test]
fn a_one_bit_change_in_the_last_byte_is_named_exactly() {
let said = first_difference(b"payload", b"payloa$");
assert!(said.contains("byte 6 of 7"), "the offset is named: {said}");
assert!(said.contains("expected 0x64"), "the wanted byte: {said}");
assert!(said.contains("got 0x24"), "the byte that came back: {said}");
assert!(said.contains("xor 0x40"), "the bit that moved: {said}");
}
#[test]
fn a_truncation_adds_nothing_because_the_lengths_already_say_it() {
assert_eq!(first_difference(b"payload", b"pay"), "");
assert_eq!(first_difference(b"payload", b""), "");
}
#[test]
fn a_truncation_that_also_differs_still_names_the_byte() {
let said = first_difference(b"payload", b"pby");
assert!(said.contains("byte 1 of 7"), "got {said}");
assert!(said.contains("xor 0x03"), "got {said}");
}
}
#[cfg(all(test, unix))]
mod tests {
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use stegobench_core::registry::Entry;
fn fake_tool(dir: &Path, body: &str) -> String {
let path = dir.join("tool.sh");
let mut f = std::fs::File::create(&path).expect("script");
write!(f, "#!/bin/sh\nset -e\n{body}\n").expect("written");
let mut perms = f.metadata().expect("metadata").permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&path, perms).expect("chmod");
path.display().to_string()
}
fn entry(command: &str) -> Entry {
toml::from_str(&format!(
"name = \"x\"\nkind = \"embedder\"\nlicence = \"MIT\"\n\
[binary]\ncommand = [\"{command}\"]\n\
[roundtrip]\ncover = \"fixtures/clean.png\"\n\
embed_argv = [\"embed\", \"{{cover}}\", \"{{payload}}\", \"{{stego}}\"]\n\
extract_argv = [\"extract\", \"{{stego}}\", \"{{recovered}}\"]\n\
[selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n"
))
.expect("parses")
}
fn staged(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
let cover = dir.join("cover.png");
let payload = dir.join("p.bin");
std::fs::write(&cover, b"\x89PNG\r\n\x1a\ncover bytes").expect("cover");
std::fs::write(&payload, b"the payload").expect("payload");
(cover, payload, dir.join("out.png"))
}
#[test]
fn a_working_embedder_writes_the_file_and_proves_the_payload_is_in_it() {
let dir = tempfile::tempdir().unwrap();
let tool = fake_tool(
dir.path(),
"case \"$1\" in\n embed) cat \"$2\" \"$3\" > \"$4\" ;;\n \
extract) tail -c 11 \"$2\" > \"$3\" ;;\nesac",
);
let (cover, payload, out) = staged(dir.path());
let done = super::run(&entry(&tool), &cover, &payload, &out, None, true).expect("embedded");
assert!(out.is_file(), "no stego file was written");
assert!(done.bytes > 0);
assert_eq!(done.recovered, Some(Ok(())));
}
#[test]
fn an_embedder_that_writes_nothing_is_caught_rather_than_reported_as_working() {
let dir = tempfile::tempdir().unwrap();
let tool = fake_tool(dir.path(), "exit 0");
let (cover, payload, out) = staged(dir.path());
let err = super::run(&entry(&tool), &cover, &payload, &out, None, true)
.expect_err("should have refused");
assert!(err.contains("wrote no stego file"), "got {err}");
assert!(!out.exists(), "a file was written anyway");
}
#[test]
fn a_payload_that_does_not_come_back_is_reported_against_the_written_file() {
let dir = tempfile::tempdir().unwrap();
let tool = fake_tool(
dir.path(),
"case \"$1\" in\n embed) cp \"$2\" \"$4\" ;;\n \
extract) printf 'something else' > \"$3\" ;;\nesac",
);
let (cover, payload, out) = staged(dir.path());
let done = super::run(&entry(&tool), &cover, &payload, &out, None, true).expect("ran");
match done.recovered {
Some(Err(e)) => {
assert!(e.contains("did not survive the round trip"), "got {e}");
assert!(e.contains("11 bytes went in"), "the payload size: {e}");
assert!(e.contains("14 came back"), "what came back: {e}");
assert!(e.contains("byte 0 of 11 differs"), "where they part: {e}");
}
other => panic!("the bad round trip was not reported: {other:?}"),
}
}
#[test]
fn no_verify_skips_the_check_and_says_nothing_about_the_payload() {
let dir = tempfile::tempdir().unwrap();
let tool = fake_tool(
dir.path(),
"case \"$1\" in\n embed) cp \"$2\" \"$4\" ;;\nesac",
);
let (cover, payload, out) = staged(dir.path());
let done = super::run(&entry(&tool), &cover, &payload, &out, None, false).expect("ran");
assert_eq!(done.recovered, None, "a check ran that was not asked for");
}
#[test]
fn an_entry_with_no_roundtrip_block_says_it_cannot_embed() {
let e: Entry = toml::from_str(
"name = \"x\"\nkind = \"embedder\"\nlicence = \"MIT\"\n\
[binary]\ncommand = [\"true\"]\n",
)
.expect("parses");
let dir = tempfile::tempdir().unwrap();
let (cover, payload, out) = staged(dir.path());
let err = super::run(&e, &cover, &payload, &out, None, true).expect_err("refused");
assert!(err.contains("declares no way to embed"), "got {err}");
}
#[test]
fn the_output_directory_is_made_rather_than_the_write_failing() {
let dir = tempfile::tempdir().unwrap();
let tool = fake_tool(
dir.path(),
"case \"$1\" in\n embed) cp \"$2\" \"$4\" ;;\nesac",
);
let (cover, payload, _) = staged(dir.path());
let out = dir.path().join("a/b/c/out.png");
super::run(&entry(&tool), &cover, &payload, &out, None, false).expect("embedded");
assert!(out.is_file(), "the nested path was not created");
}
}