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

7 years ago
  1. use std::borrow::Cow;
  2. use std::error::Error;
  3. use std::fmt;
  4. use std::fs::File as FsFile;
  5. use std::io::{self, Write};
  6. use command_runner::CommandRunner;
  7. use symbols::Symbol;
  8. pub struct AcmeCert<'a> {
  9. domain: Cow<'a, str>,
  10. command_runner: &'a CommandRunner
  11. }
  12. impl<'a> AcmeCert<'a> {
  13. pub fn new(domain: Cow<'a, str>, command_runner: &'a CommandRunner) -> AcmeCert<'a> {
  14. AcmeCert {
  15. domain: domain,
  16. command_runner: command_runner
  17. }
  18. }
  19. fn get_key_path(&self) -> String {
  20. format!("/etc/ssl/private/{}.key", self.domain)
  21. }
  22. fn get_csr_path(&self) -> String {
  23. format!("/etc/ssl/local_certs/{}.csr", self.domain)
  24. }
  25. fn get_cert_path(&self) -> String {
  26. format!("/etc/ssl/local_certs/{}.crt", self.domain)
  27. }
  28. }
  29. impl<'a> fmt::Display for AcmeCert<'a> {
  30. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  31. write!(f, "AcmeCert {}", self.domain)
  32. }
  33. }
  34. const DAYS_IN_SECONDS: u32 = 24*60*60;
  35. impl<'a> Symbol for AcmeCert<'a> {
  36. fn target_reached(&self) -> Result<bool, Box<Error>> {
  37. let file = FsFile::open(self.get_cert_path());
  38. // Check first if file exists to support dry-run mode where the acme user is not even created
  39. if let Err(e) = file {
  40. return if e.kind() == io::ErrorKind::NotFound {
  41. Ok(false)
  42. } else {
  43. Err(Box::new(e))
  44. };
  45. }
  46. // FIXME: check who signed it
  47. let result = self.command_runner.run_with_args("openssl", &["x509", "-in", &self.get_cert_path(), "-noout", "-subject", "-checkend", &(30*DAYS_IN_SECONDS).to_string()]);
  48. match result {
  49. Err(e) => Err(Box::new(e)),
  50. Ok(output) => match output.status.code() {
  51. Some(0) => if output.stdout == format!("subject=CN = {}\nCertificate will not expire\n", self.domain).as_bytes() {
  52. 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)));
  53. Ok(result.status.code() == Some(0))
  54. } else { Ok(false) },
  55. Some(_) => Ok(false),
  56. _ => Err("Didn't work".to_string().into())
  57. }
  58. }
  59. }
  60. fn execute(&self) -> Result<(), Box<Error>> {
  61. 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)));
  62. let mut file = try!(FsFile::create(self.get_cert_path()));
  63. try!(file.write_all(&output.stdout));
  64. Ok(())
  65. }
  66. }
  67. #[cfg(test)]
  68. mod test {
  69. }