A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::fs::File as FsFile;
use std::io::{self, Write};
use command_runner::CommandRunner;
use symbols::Symbol;
pub struct AcmeCert<'a> {
domain: Cow<'a, str>,
command_runner: &'a CommandRunner
}
impl<'a> AcmeCert<'a> {
pub fn new(domain: Cow<'a, str>, command_runner: &'a CommandRunner) -> AcmeCert<'a> {
AcmeCert {
domain: domain,
command_runner: command_runner
}
}
fn get_key_path(&self) -> String {
format!("/etc/ssl/private/{}.key", self.domain)
}
fn get_csr_path(&self) -> String {
format!("/etc/ssl/local_certs/{}.csr", self.domain)
}
fn get_cert_path(&self) -> String {
format!("/etc/ssl/local_certs/{}.crt", self.domain)
}
}
impl<'a> fmt::Display for AcmeCert<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "AcmeCert {}", self.domain)
}
}
const DAYS_IN_SECONDS: u32 = 24*60*60;
impl<'a> Symbol for AcmeCert<'a> {
fn target_reached(&self) -> Result<bool, Box<Error>> {
let file = FsFile::open(self.get_cert_path());
// Check first if file exists to support dry-run mode where the acme user is not even created
if let Err(e) = file {
return if e.kind() == io::ErrorKind::NotFound {
Ok(false)
} else {
Err(Box::new(e))
};
}
// FIXME: check who signed it
let result = self.command_runner.run_with_args("openssl", &["x509", "-in", &self.get_cert_path(), "-noout", "-subject", "-checkend", &(30*DAYS_IN_SECONDS).to_string()]);
match result {
Err(e) => Err(Box::new(e)),
Ok(output) => match output.status.code() {
Some(0) => if output.stdout == format!("subject=CN = {}\nCertificate will not expire\n", self.domain).as_bytes() {
let result = try!(self.command_runner.run_with_args("openssl", &["verify", "--untrusted", "/home/acme/lets_encrypt_x3_cross_signed.pem", &self.get_cert_path()]).map_err(|e| Box::new(e)));
Ok(result.status.code() == Some(0))
} else { Ok(false) },
Some(_) => Ok(false),
_ => Err("Didn't work".to_string().into())
}
}
}
fn execute(&self) -> Result<(), Box<Error>> {
let output = try!(self.command_runner.run_with_args("acme-tiny", &["--account-key", "/home/acme/account.key", "--csr", &self.get_csr_path(), "--acme-dir", "/home/acme/challenges/"]).map_err(|e| Box::new(e)));
let mut file = try!(FsFile::create(self.get_cert_path()));
try!(file.write_all(&output.stdout));
Ok(())
}
}
#[cfg(test)]
mod test {
}