mod ledger;
mod secret;
mod state;
mod totp;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use anyhow::{Context as _, Result, bail};
use zeroize::Zeroizing;
use crate::home::Home;
pub use ledger::SESSION;
pub use state::{MAX_FAILURES, WINDOW_MS};
pub const KEY_FILE: &str = "audit.key.gate";
const STATE_FILE: &str = "gate.json";
#[cfg(debug_assertions)]
const NOW_VARIABLE: &str = "MOAT_GATE_NOW";
static PASSED: OnceLock<u64> = OnceLock::new();
pub fn path(home: &Home) -> PathBuf {
home.root().join(KEY_FILE)
}
fn state_path(home: &Home) -> PathBuf {
home.root().join(STATE_FILE)
}
pub fn enrolled(home: &Home) -> bool {
std::fs::symlink_metadata(path(home)).is_ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Factor {
NotEnrolled,
Totp(u64),
}
impl Factor {
fn describe(self) -> String {
match self {
Self::NotEnrolled => "possession factor: not enrolled (terminal check only)".to_owned(),
Self::Totp(step) => format!("possession factor: authenticator code (step {step})"),
}
}
}
#[derive(Debug)]
#[must_use = "record the change in the policy-change ledger once it is made"]
pub struct Pass {
command: String,
factor: Factor,
}
impl Pass {
#[cfg(test)]
pub fn factor(&self) -> Factor {
self.factor
}
pub fn record(self, home: &Home, what: &str, details: &[String]) {
ledger::change(home, &self.command, self.factor, what, details);
}
}
pub fn pass(home: &Home, command: &str) -> Result<Pass> {
let pass = |factor| Pass {
command: command.to_owned(),
factor,
};
if !enrolled(home) {
return Ok(pass(Factor::NotEnrolled));
}
if let Some(step) = PASSED.get() {
return Ok(pass(Factor::Totp(*step)));
}
let secret = secret::read(&path(home)).inspect_err(|_| {
ledger::refused(home, command, "the gate's secret cannot be read");
})?;
let step = take(home, command, &secret, now_secs(), || read_code(command))?;
let _ = PASSED.set(step);
Ok(pass(Factor::Totp(step)))
}
fn take(
home: &Home,
command: &str,
secret: &[u8],
now_secs: u64,
typed: impl FnOnce() -> Result<Zeroizing<String>>,
) -> Result<u64> {
let state_path = state_path(home);
let mut state = state::State::load(&state_path)?;
let now_ms = i64::try_from(now_secs.saturating_mul(1000)).unwrap_or(i64::MAX);
if let Some(until) = state.locked_until(now_ms) {
ledger::refused(home, command, "too many wrong codes");
bail!(
"refusing `{command}`: {MAX_FAILURES} wrong codes in the last {} minutes. Try again \
after {} UTC",
WINDOW_MS / 60_000,
crate::time::clock(until)
);
}
let typed = typed()?;
match totp::check(secret, &typed, now_secs, state.last_step) {
Ok(step) => {
state.passed(step);
state.save(&state_path)?;
Ok(step)
}
Err(refusal) => {
state.failed(now_ms);
state.save(&state_path)?;
ledger::refused(home, command, refusal.as_str());
let hint = match refusal {
totp::Refusal::Replayed => "wait for the next code and run it again",
totp::Refusal::Missing | totp::Refusal::Malformed | totp::Refusal::Wrong => {
"type the six digits your authenticator app shows for OpenMoat now; if the app \
no longer has that entry, docs/USAGE.md \"If you can no longer get a code\" \
says how to turn the gate off"
}
};
bail!(
"refusing `{command}`: {} ({hint}); nothing was changed",
refusal.as_str()
)
}
}
}
fn read_code(command: &str) -> Result<Zeroizing<String>> {
eprint!("Code from your authenticator app to confirm `{command}`: ");
let _ = std::io::stderr().flush();
let typed = crate::terminal::read_answer().context("reading the code")?;
Ok(Zeroizing::new(typed.trim().to_owned()))
}
fn now_secs() -> u64 {
#[cfg(debug_assertions)]
if let Some(secs) = std::env::var(NOW_VARIABLE)
.ok()
.and_then(|v| v.parse::<u64>().ok())
{
return secs;
}
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
fn now_ms() -> i64 {
i64::try_from(now_secs().saturating_mul(1000)).unwrap_or(i64::MAX)
}
pub struct Enrolment {
secret: Zeroizing<Vec<u8>>,
}
impl std::fmt::Debug for Enrolment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Enrolment { .. }")
}
}
impl Enrolment {
pub fn new() -> Result<Self> {
Ok(Self {
secret: secret::generate()?,
})
}
pub fn uri(&self) -> Zeroizing<String> {
secret::uri(&self.secret)
}
pub fn text(&self) -> Zeroizing<String> {
secret::grouped(&self.secret)
}
pub fn confirm(&self, home: &Home, typed: &str) -> Result<()> {
let step = totp::check(&self.secret, typed, now_secs(), 0)
.map_err(|refusal| anyhow::Error::msg(refusal.as_str()))
.context("the code does not match the new secret; nothing was set up")?;
let path = path(home);
if !crate::home::write_private_new(&path, secret::encode_file(&self.secret).as_bytes())? {
bail!(
"{} is there already: run `openmoat gate remove` first",
path.display()
);
}
let mut state = state::State::default();
state.passed(step);
state.save(&state_path(home))?;
ledger::change(
home,
"openmoat gate setup",
Factor::Totp(step),
"possession factor enrolled",
&[],
);
Ok(())
}
}
pub fn remove(home: &Home) -> Result<()> {
remove_file(&path(home))?;
remove_file(&state_path(home))
}
fn remove_file(path: &Path) -> Result<()> {
match std::fs::remove_file(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
other => other.with_context(|| format!("removing {}", path.display())),
}
}
pub fn status(home: &Home) -> Result<(bool, usize)> {
let now_ms = now_ms();
let mut state = state::State::load(&state_path(home))?;
state.prune(now_ms);
Ok((enrolled(home), state.failures.len()))
}
#[cfg(test)]
mod tests;