Browse Source

Initial commit

pull/5/head
Rodolphe Breard 5 years ago
commit
4ddefb73a5
  1. 14
      .gitignore
  2. 4
      Cargo.toml
  3. 202
      LICENSE-APACHE-2.0.txt
  4. 7
      LICENSE-MIT.txt
  5. 26
      acmed/Cargo.toml
  6. 359
      acmed/src/acmed.rs
  7. 247
      acmed/src/config.rs
  8. 213
      acmed/src/encoding.rs
  9. 58
      acmed/src/errors.rs
  10. 75
      acmed/src/main.rs
  11. 173
      acmed/src/storage.rs

14
.gitignore

@ -0,0 +1,14 @@
# Rust files
/target
**/*.rs.bk
Cargo.lock
# Backup files
*~
\#*
.\#*
*.swp
# Test files
/test
test.*

4
Cargo.toml

@ -0,0 +1,4 @@
[workspace]
members = [
"acmed",
]

202
LICENSE-APACHE-2.0.txt

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

7
LICENSE-MIT.txt

@ -0,0 +1,7 @@
Copyright 2019 Rodolphe Bréard
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

26
acmed/Cargo.toml

@ -0,0 +1,26 @@
[package]
name = "acmed"
version = "0.1.0"
authors = ["Rodolphe Breard <rodolphe@what.tf>"]
edition = "2018"
description = "ACME (RFC 8555) client daemon"
keywords = ["acme", "tls", "X.509"]
repository = "https://github.com/breard-r/acmed"
readme = "README.md"
license = "MIT OR Apache-2.0"
include = ["src/**/*", "Cargo.toml", "LICENSE-*.txt"]
[dependencies]
acme-lib = "0.4"
clap = "2.32"
env_logger = "0.6"
handlebars = "2.0.0-beta.1"
log = "0.4"
pem = "0.5"
serde = { version = "1.0", features = ["derive"] }
time = "0.1"
toml = "0.4"
x509-parser = "0.4"
[target.'cfg(unix)'.dependencies]
nix = "0.13"

359
acmed/src/acmed.rs

@ -0,0 +1,359 @@
use acme_lib::{Directory, DirectoryUrl};
use crate::config::{self, Hook};
use crate::errors::Error;
use crate::storage::Storage;
use handlebars::Handlebars;
use log::{debug, info, warn};
use serde::Serialize;
use std::{fmt, thread};
use std::fs::File;
use std::io::Write;
use std::process::{Command, Stdio};
use std::time::Duration;
use x509_parser::parse_x509_der;
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub enum Format {
Der,
Pem,
}
impl fmt::Display for Format {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
Format::Der => "der",
Format::Pem => "pem",
};
write!(f, "{}", s)
}
}
#[derive(Clone, Debug)]
pub enum Challenge {
Http01,
Dns01,
}
impl Challenge {
pub fn from_str(s: &str) -> Result<Self, Error> {
match s.to_lowercase().as_str() {
"http-01" => Ok(Challenge::Http01),
"dns-01" => Ok(Challenge::Dns01),
_ => Err(Error::new(&format!("{}: unknown challenge.", s))),
}
}
}
impl fmt::Display for Challenge {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
Challenge::Http01 => "http-01",
Challenge::Dns01 => "dns-01",
};
write!(f, "{}", s)
}
}
#[derive(Clone, Debug)]
pub enum Algorithm {
Rsa2048,
Rsa4096,
EcdsaP256,
EcdsaP384,
}
impl Algorithm {
pub fn from_str(s: &str) -> Result<Self, Error> {
match s.to_lowercase().as_str() {
"rsa2048" => Ok(Algorithm::Rsa2048),
"rsa4096" => Ok(Algorithm::Rsa4096),
"ecdsa_p256" => Ok(Algorithm::EcdsaP256),
"ecdsa_p384" => Ok(Algorithm::EcdsaP384),
_ => Err(Error::new(&format!("{}: unknown algorithm.", s))),
}
}
}
impl fmt::Display for Algorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
Algorithm::Rsa2048 => "rsa2048",
Algorithm::Rsa4096 => "rsa4096",
Algorithm::EcdsaP256 => "ecdsa-p256",
Algorithm::EcdsaP384 => "ecdsa-p384",
};
write!(f, "{}", s)
}
}
#[derive(Serialize)]
struct HookData {
// Common
domains: Vec<String>,
algorithm: String,
challenge: String,
status: String,
// Challenge hooks
current_domain: String,
token: String,
proof: String,
}
macro_rules! get_hook_output {
($out: expr, $reg: ident, $data: expr) => {{
match $out {
Some(path) => {
let path = $reg.render_template(path, $data)?;
let file = File::create(path)?;
Stdio::from(file)
}
None => Stdio::null(),
}
}};
}
impl HookData {
pub fn call(&self, hook: &Hook) -> Result<(), Error> {
let reg = Handlebars::new();
let mut v = vec![];
let args = match &hook.args {
Some(lst) => {
for fmt in lst.iter() {
let s = reg.render_template(fmt, &self)?;
v.push(s);
}
v.as_slice()
}
None => &[],
};
let mut cmd = Command::new(&hook.cmd)
.args(args)
.stdout(get_hook_output!(&hook.stdout, reg, &self))
.stderr(get_hook_output!(&hook.stderr, reg, &self))
.stdin(match &hook.stdin {
Some(_) => Stdio::piped(),
None => Stdio::null(),
})
.spawn()?;
if hook.stdin.is_some() {
let data_in = reg.render_template(&hook.stdin.to_owned().unwrap(), &self)?;
let stdin = cmd.stdin.as_mut().unwrap();
stdin.write_all(data_in.as_bytes()).unwrap();
}
Ok(())
}
}
#[derive(Debug)]
struct Certificate {
domains: Vec<String>,
algo: Algorithm,
storage: Storage,
email: String,
remote_url: String,
challenge: Challenge,
challenge_hooks: Vec<Hook>,
post_operation_hooks: Vec<Hook>,
}
impl Certificate {
fn should_renew(&self) -> bool {
let domain = self.domains.first().unwrap();
let raw_cert = match self.storage.get_certificate(&Format::Der) {
Ok(c) => match c {
Some(d) => d,
None => {
debug!(
"{} certificate for {} is empty or does not exists",
self.algo, domain
);
return true;
}
},
Err(e) => {
warn!("{}", e);
return true;
}
};
match parse_x509_der(&raw_cert) {
Ok((_, cert)) => {
// TODO: allow a custom duration (using time-parse ?)
let renewal_time =
cert.tbs_certificate.validity.not_after - time::Duration::weeks(3);
debug!(
"{} certificate for {}: not after: {}",
self.algo,
domain,
cert.tbs_certificate.validity.not_after.asctime()
);
debug!(
"{} certificate for {}: renew on: {}",
self.algo,
domain,
renewal_time.asctime()
);
time::now_utc() > renewal_time
}
Err(_) => true,
}
}
fn call_challenge_hooks(&self, token: &str, proof: &str, domain: &str) -> Result<(), Error> {
let hook_data = HookData {
domains: self.domains.to_owned(),
algorithm: self.algo.to_string(),
challenge: self.challenge.to_string(),
status: format!("Validation pending for {}", domain),
current_domain: domain.to_string(),
token: token.to_string(),
proof: proof.to_string(),
};
for hook in self.challenge_hooks.iter() {
hook_data.call(&hook)?;
}
Ok(())
}
fn call_post_operation_hooks(&self, status: &str) -> Result<(), Error> {
let hook_data = HookData {
domains: self.domains.to_owned(),
algorithm: self.algo.to_string(),
challenge: self.challenge.to_string(),
status: status.to_string(),
current_domain: "".to_string(),
token: "".to_string(),
proof: "".to_string(),
};
for hook in self.post_operation_hooks.iter() {
hook_data.call(&hook)?;
}
Ok(())
}
fn renew(&mut self) -> Result<(), Error> {
// TODO: do it in a separated thread since it may take a while
let (name, alt_names_str) = self.domains.split_first().unwrap();
let mut alt_names = vec![];
for n in alt_names_str.iter() {
alt_names.push(n.as_str());
}
info!("Renewing the {} certificate for {}", self.algo, name);
let url = DirectoryUrl::Other(&self.remote_url);
let dir = Directory::from_url(self.storage.to_owned(), url)?;
let acc = dir.account(&self.email)?;
let mut ord_new = acc.new_order(name, &alt_names)?;
let ord_csr = loop {
if let Some(ord_csr) = ord_new.confirm_validations() {
break ord_csr;
}
let auths = ord_new.authorizations()?;
for auth in auths.iter() {
match self.challenge {
Challenge::Http01 => {
let chall = auth.http_challenge();
let token = chall.http_token();
let proof = chall.http_proof();
self.call_challenge_hooks(&token, &proof, auth.domain_name())?;
chall.validate(crate::DEFAULT_POOL_TIME)?;
}
Challenge::Dns01 => {
let chall = auth.dns_challenge();
let proof = chall.dns_proof();
self.call_challenge_hooks("", &proof, auth.domain_name())?;
chall.validate(crate::DEFAULT_POOL_TIME)?;
}
};
}
ord_new.refresh()?;
};
// TODO: allow PK reuse
let (pkey_pri, pkey_pub) = match self.algo {
Algorithm::Rsa2048 => acme_lib::create_rsa_key(2048),
Algorithm::Rsa4096 => acme_lib::create_rsa_key(4096),
Algorithm::EcdsaP256 => acme_lib::create_p256_key(),
Algorithm::EcdsaP384 => acme_lib::create_p384_key(),
};
let ord_cert = ord_csr.finalize_pkey(pkey_pri, pkey_pub, crate::DEFAULT_POOL_TIME)?;
ord_cert.download_and_save_cert()?;
Ok(())
}
}
pub struct Acmed {
certs: Vec<Certificate>,
}
impl Acmed {
pub fn new(config_file: &str) -> Result<Self, Error> {
let cnf = config::from_file(config_file)?;
let mut certs = Vec::new();
for crt in cnf.certificate.iter() {
let cert = Certificate {
domains: crt.domains.to_owned(),
algo: crt.get_algorithm()?,
storage: Storage {
account_directory: cnf.get_account_dir(),
account_name: crt.email.to_owned(),
crt_directory: crt.get_crt_dir(&cnf),
crt_name: crt.get_crt_name(),
crt_name_format: crt.get_crt_name_format(),
formats: crt.get_formats()?,
algo: crt.get_algorithm()?,
cert_file_mode: cnf.get_cert_file_mode(),
cert_file_owner: cnf.get_cert_file_user(),
cert_file_group: cnf.get_cert_file_group(),
pk_file_mode: cnf.get_pk_file_mode(),
pk_file_owner: cnf.get_pk_file_user(),
pk_file_group: cnf.get_pk_file_group(),
},
email: crt.email.to_owned(),
remote_url: crt.get_remote_url(&cnf)?,
challenge: crt.get_challenge()?,
challenge_hooks: crt.get_challenge_hooks(&cnf)?,
post_operation_hooks: crt.get_post_operation_hook(&cnf)?,
};
certs.push(cert);
}
Ok(Acmed { certs })
}
pub fn run(&mut self) {
loop {
for crt in self.certs.iter_mut() {
debug!("{:?}", crt);
if crt.should_renew() {
// TODO: keep track of (not yet implemented) threads and wait for them to end.
let status = match crt.renew() {
Ok(_) => "Success.".to_string(),
Err(e) => {
let msg = format!(
"Unable to renew the {} certificate for {}: {}",
crt.algo,
crt.domains.first().unwrap(),
e
);
warn!("{}", msg);
format!("Failed: {}", msg)
}
};
match crt.call_post_operation_hooks(&status) {
Ok(_) => {}
Err(e) => {
let msg = format!(
"{} certificate for {}: post-operation hook error: {}",
crt.algo,
crt.domains.first().unwrap(),
e
);
warn!("{}", msg);
}
};
}
}
thread::sleep(Duration::from_secs(crate::DEFAULT_SLEEP_TIME));
}
}
}

247
acmed/src/config.rs

@ -0,0 +1,247 @@
use crate::acmed::{Algorithm, Challenge, Format};
use crate::errors::Error;
use log::info;
use serde::Deserialize;
use std::fs::{self, File};
use std::path::Path;
use std::io::prelude::*;
#[derive(Deserialize)]
pub struct Config {
pub global: Option<GlobalOptions>,
pub endpoint: Vec<Endpoint>,
pub hook: Vec<Hook>,
pub certificate: Vec<Certificate>,
}
impl Config {
pub fn get_account_dir(&self) -> String {
let account_dir = match &self.global {
Some(g) => match &g.accounts_directory {
Some(d) => &d,
None => crate::DEFAULT_ACCOUNTS_DIR,
},
None => crate::DEFAULT_ACCOUNTS_DIR,
};
account_dir.to_string()
}
pub fn get_hook(&self, name: &str) -> Result<Hook, Error> {
for hook in self.hook.iter() {
if name == hook.name {
return Ok(hook.clone());
}
}
Err(Error::new(&format!("{}: hook not found", name)))
}
pub fn get_cert_file_mode(&self) -> u32 {
match &self.global {
Some(g) => match g.cert_file_mode {
Some(m) => m,
None => crate::DEFAULT_CERT_FILE_MODE,
},
None => crate::DEFAULT_CERT_FILE_MODE,
}
}
pub fn get_cert_file_user(&self) -> Option<String> {
match &self.global {
Some(g) => g.cert_file_user.to_owned(),
None => None,
}
}
pub fn get_cert_file_group(&self) -> Option<String> {
match &self.global {
Some(g) => g.cert_file_group.to_owned(),
None => None,
}
}
pub fn get_pk_file_mode(&self) -> u32 {
match &self.global {
Some(g) => match g.pk_file_mode {
Some(m) => m,
None => crate::DEFAULT_PK_FILE_MODE,
},
None => crate::DEFAULT_PK_FILE_MODE,
}
}
pub fn get_pk_file_user(&self) -> Option<String> {
match &self.global {
Some(g) => g.pk_file_user.to_owned(),
None => None,
}
}
pub fn get_pk_file_group(&self) -> Option<String> {
match &self.global {
Some(g) => g.pk_file_group.to_owned(),
None => None,
}
}
}
#[derive(Deserialize)]
pub struct GlobalOptions {
pub accounts_directory: Option<String>,
pub certificates_directory: Option<String>,
pub cert_file_mode: Option<u32>,
pub cert_file_user: Option<String>,
pub cert_file_group: Option<String>,
pub pk_file_mode: Option<u32>,
pub pk_file_user: Option<String>,
pub pk_file_group: Option<String>,
}
#[derive(Deserialize)]
pub struct Endpoint {
pub name: String,
pub url: String,
}
#[derive(Deserialize, Clone, Debug)]
pub struct Hook {
pub name: String,
pub cmd: String,
pub args: Option<Vec<String>>,
pub stdin: Option<String>,
pub stdout: Option<String>,
pub stderr: Option<String>,
}
#[derive(Deserialize)]
pub struct Certificate {
pub email: String,
pub endpoint: String,
pub domains: Vec<String>,
pub challenge: String,
pub challenge_hooks: Vec<String>,
pub post_operation_hook: Option<Vec<String>>,
pub algorithm: Option<String>,
pub directory: Option<String>,
pub name: Option<String>,
pub name_format: Option<String>,
pub formats: Option<Vec<String>>,
}
impl Certificate {
pub fn get_algorithm(&self) -> Result<Algorithm, Error> {
let algo = match &self.algorithm {
Some(a) => &a,
None => crate::DEFAULT_ALGO,
};
Algorithm::from_str(algo)
}
pub fn get_challenge(&self) -> Result<Challenge, Error> {
Challenge::from_str(&self.challenge)
}
pub fn get_formats(&self) -> Result<Vec<Format>, Error> {
let ret = match &self.formats {
Some(fmts) => {
let mut lst = Vec::new();
for f in fmts.iter() {
lst.push(match f.as_str() {
"der" => Format::Der,
"pem" => Format::Pem,
_ => return Err(Error::new(&format!("{}: unknown format.", f))),
});
}
lst.sort();
lst.dedup();
lst
}
None => vec![crate::DEFAULT_FMT],
};
Ok(ret)
}
pub fn get_crt_name(&self) -> String {
match &self.name {
Some(n) => n.to_string(),
None => self.domains.first().unwrap().to_string(),
}
}
pub fn get_crt_name_format(&self) -> String {
match &self.name_format {
Some(n) => n.to_string(),
None => crate::DEFAULT_CERT_FORMAT.to_string(),
}
}
pub fn get_crt_dir(&self, cnf: &Config) -> String {
let crt_directory = match &self.directory {
Some(d) => &d,
None => match &cnf.global {
Some(g) => match &g.certificates_directory {
Some(d) => &d,
None => crate::DEFAULT_CERT_DIR,
},
None => crate::DEFAULT_CERT_DIR,
},
};
crt_directory.to_string()
}
pub fn get_remote_url(&self, cnf: &Config) -> Result<String, Error> {
for endpoint in cnf.endpoint.iter() {
if endpoint.name == self.endpoint {
return Ok(endpoint.url.to_owned());
}
}
Err(Error::new(&format!("{}: unknown endpoint.", self.endpoint)))
}
pub fn get_challenge_hooks(&self, cnf: &Config) -> Result<Vec<Hook>, Error> {
let mut res = vec![];
for name in self.challenge_hooks.iter() {
let h = cnf.get_hook(&name)?;
res.push(h);
}
Ok(res)
}
pub fn get_post_operation_hook(&self, cnf: &Config) -> Result<Vec<Hook>, Error> {
let mut res = vec![];
match &self.post_operation_hook {
Some(po_hooks) => for name in po_hooks.iter() {
let h = cnf.get_hook(&name)?;
res.push(h);
},
None => {}
};
Ok(res)
}
}
fn create_dir(path: &str) -> Result<(), Error> {
if Path::new(path).is_dir() {
Ok(())
} else {
fs::create_dir_all(path)?;
Ok(())
}
}
fn init_directories(config: &Config) -> Result<(), Error> {
create_dir(&config.get_account_dir())?;
for crt in config.certificate.iter() {
create_dir(&crt.get_crt_dir(config))?;
}
Ok(())
}
pub fn from_file(file: &str) -> Result<Config, Error> {
info!("Loading configuration file: {}", file);
let mut file = File::open(file)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let config: Config = toml::from_str(&contents)?;
init_directories(&config)?;
Ok(config)
}

213
acmed/src/encoding.rs

@ -0,0 +1,213 @@
use acme_lib::Error;
use acme_lib::persist::PersistKind;
use crate::acmed::Format;
use log::debug;
use pem::{encode, Pem};
enum ConversionType {
PemToDer,
DerToPem,
None,
}
impl ConversionType {
fn get(from: &Format, to: &Format) -> Self {
match from {
Format::Pem => match to {
Format::Pem => ConversionType::None,
Format::Der => ConversionType::PemToDer,
},
Format::Der => match to {
Format::Pem => ConversionType::DerToPem,
Format::Der => ConversionType::None,
},
}
}
}
fn pem_to_der(data: &[u8]) -> Result<Vec<u8>, Error> {
// We need to convert all CRLF into LF since x509_parser only supports the later.
let mut data = data.to_vec();
data.retain(|&c| c != 0x0d);
match x509_parser::pem::pem_to_der(&data) {
Ok((_, cert)) => Ok(cert.contents),
Err(_) => Err(Error::Other("invalid PEM certificate".to_string())),
}
}
fn der_to_pem(data: &[u8], kind: PersistKind) -> Result<Vec<u8>, Error> {
// TODO: allow the user to specify if we should use CRLF or LF (default is CRLF).
let tag_str = match kind {
PersistKind::AccountPrivateKey => "PRIVATE KEY",
PersistKind::PrivateKey => "PRIVATE KEY",
PersistKind::Certificate => "CERTIFICATE",
};
let pem = Pem {
tag: String::from(tag_str),
contents: data.to_vec(),
};
let res = encode(&pem);
Ok(res.into_bytes())
}
/// Convert a certificate encoded in a format into another format.
///
/// Warning: if the data contains multiple certificates (eg: a PEM
/// certificate chain), converting to DER will only include the first
/// certificate, the others will be lost.
pub fn convert(
data: &[u8],
from: &Format,
to: &Format,
kind: PersistKind,
) -> Result<Vec<u8>, Error> {
debug!("Converting a certificate from {} to {}", from, to);
match ConversionType::get(from, to) {
ConversionType::PemToDer => pem_to_der(data),
ConversionType::DerToPem => der_to_pem(data, kind),
ConversionType::None => Ok(data.to_vec()),
}
}
#[cfg(test)]
mod tests {
use acme_lib::persist::PersistKind;
use crate::acmed::Format;
use super::convert;
// Test data generated using:
//
// openssl req -x509 -nodes -newkey ED25519 -keyout key.pem -out cert.pem -days 365
// openssl pkey -inform PEM -outform DER -in key.pem -out key.der
// openssl x509 -inform PEM -outform DER -in cert.pem -out cert.der
pub const PK_PEM: &'static [u8] = b"-----BEGIN PRIVATE KEY-----\r
MC4CAQAwBQYDK2VwBCIEIJRKGvS3yKtxf+zjzvDTHx2dIcDXz0LKeBLnqE0H8ALb\r
-----END PRIVATE KEY-----\r\n";
pub const PK_DER: &'static [u8] = b"\x30\x2E\x02\x01\x00\x30\x05\x06\x03\
\x2B\x65\x70\x04\x22\x04\x20\x94\x4A\x1A\xF4\xB7\xC8\xAB\x71\x7F\xEC\xE3\xCE\
\xF0\xD3\x1F\x1D\x9D\x21\xC0\xD7\xCF\x42\xCA\x78\x12\xE7\xA8\x4D\x07\xF0\x02\
\xDB";
pub const CERT_PEM: &'static [u8] = b"-----BEGIN CERTIFICATE-----\r
MIICLzCCAeGgAwIBAgIUdlMenq7MVkx5b1lFrvaBwvjlIEQwBQYDK2VwMIGMMQsw\r
CQYDVQQGEwJGUjEZMBcGA1UECAwQw4PCjmxlLWRlLUZyYW5jZTEOMAwGA1UEBwwF\r
UGFyaXMxDjAMBgNVBAoMBUFDTUVkMRkwFwYDVQQDDBB0ZXN0LmV4YW1wbGUub3Jn\r
MScwJQYJKoZIhvcNAQkBFhhpbnZhbGlkQHRlc3QuZXhhbXBsZS5vcmcwHhcNMTkw\r
MzE0MTE0NDI1WhcNMjAwMzEzMTE0NDI1WjCBjDELMAkGA1UEBhMCRlIxGTAXBgNV\r
BAgMEMODwo5sZS1kZS1GcmFuY2UxDjAMBgNVBAcMBVBhcmlzMQ4wDAYDVQQKDAVB\r
Q01FZDEZMBcGA1UEAwwQdGVzdC5leGFtcGxlLm9yZzEnMCUGCSqGSIb3DQEJARYY\r
aW52YWxpZEB0ZXN0LmV4YW1wbGUub3JnMCowBQYDK2VwAyEAboP+S9yfoP3euk+C\r
FgMIZ9J/Q6KxLwteCAvJSkbWTwKjUzBRMB0GA1UdDgQWBBT49UVSayhFWUaRiyiB\r
oXkSoRgynTAfBgNVHSMEGDAWgBT49UVSayhFWUaRiyiBoXkSoRgynTAPBgNVHRMB\r
Af8EBTADAQH/MAUGAytlcANBAPITjbIYNioMcpMDMvbyzHf2IqPFiNW/Ce3KTS8T\r
zseNNFkN0oOc55UAd2ECe6gGOXB0r4MycFOM9ccR2t8ttwE=\r
-----END CERTIFICATE-----\r\n";
pub const CERT_DER: &'static [u8] = b"\x30\x82\x02\x2F\x30\x82\x01\xE1\xA0\
\x03\x02\x01\x02\x02\x14\x76\x53\x1E\x9E\xAE\xCC\x56\x4C\x79\x6F\x59\x45\xAE\
\xF6\x81\xC2\xF8\xE5\x20\x44\x30\x05\x06\x03\x2B\x65\x70\x30\x81\x8C\x31\x0B\
\x30\x09\x06\x03\x55\x04\x06\x13\x02\x46\x52\x31\x19\x30\x17\x06\x03\x55\x04\
\x08\x0C\x10\xC3\x83\xC2\x8E\x6C\x65\x2D\x64\x65\x2D\x46\x72\x61\x6E\x63\x65\
\x31\x0E\x30\x0C\x06\x03\x55\x04\x07\x0C\x05\x50\x61\x72\x69\x73\x31\x0E\x30\
\x0C\x06\x03\x55\x04\x0A\x0C\x05\x41\x43\x4D\x45\x64\x31\x19\x30\x17\x06\x03\
\x55\x04\x03\x0C\x10\x74\x65\x73\x74\x2E\x65\x78\x61\x6D\x70\x6C\x65\x2E\x6F\
\x72\x67\x31\x27\x30\x25\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x09\x01\x16\x18\
\x69\x6E\x76\x61\x6C\x69\x64\x40\x74\x65\x73\x74\x2E\x65\x78\x61\x6D\x70\x6C\
\x65\x2E\x6F\x72\x67\x30\x1E\x17\x0D\x31\x39\x30\x33\x31\x34\x31\x31\x34\x34\
\x32\x35\x5A\x17\x0D\x32\x30\x30\x33\x31\x33\x31\x31\x34\x34\x32\x35\x5A\x30\
\x81\x8C\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02\x46\x52\x31\x19\x30\x17\
\x06\x03\x55\x04\x08\x0C\x10\xC3\x83\xC2\x8E\x6C\x65\x2D\x64\x65\x2D\x46\x72\
\x61\x6E\x63\x65\x31\x0E\x30\x0C\x06\x03\x55\x04\x07\x0C\x05\x50\x61\x72\x69\
\x73\x31\x0E\x30\x0C\x06\x03\x55\x04\x0A\x0C\x05\x41\x43\x4D\x45\x64\x31\x19\
\x30\x17\x06\x03\x55\x04\x03\x0C\x10\x74\x65\x73\x74\x2E\x65\x78\x61\x6D\x70\
\x6C\x65\x2E\x6F\x72\x67\x31\x27\x30\x25\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\
\x09\x01\x16\x18\x69\x6E\x76\x61\x6C\x69\x64\x40\x74\x65\x73\x74\x2E\x65\x78\
\x61\x6D\x70\x6C\x65\x2E\x6F\x72\x67\x30\x2A\x30\x05\x06\x03\x2B\x65\x70\x03\
\x21\x00\x6E\x83\xFE\x4B\xDC\x9F\xA0\xFD\xDE\xBA\x4F\x82\x16\x03\x08\x67\xD2\
\x7F\x43\xA2\xB1\x2F\x0B\x5E\x08\x0B\xC9\x4A\x46\xD6\x4F\x02\xA3\x53\x30\x51\
\x30\x1D\x06\x03\x55\x1D\x0E\x04\x16\x04\x14\xF8\xF5\x45\x52\x6B\x28\x45\x59\
\x46\x91\x8B\x28\x81\xA1\x79\x12\xA1\x18\x32\x9D\x30\x1F\x06\x03\x55\x1D\x23\
\x04\x18\x30\x16\x80\x14\xF8\xF5\x45\x52\x6B\x28\x45\x59\x46\x91\x8B\x28\x81\
\xA1\x79\x12\xA1\x18\x32\x9D\x30\x0F\x06\x03\x55\x1D\x13\x01\x01\xFF\x04\x05\
\x30\x03\x01\x01\xFF\x30\x05\x06\x03\x2B\x65\x70\x03\x41\x00\xF2\x13\x8D\xB2\
\x18\x36\x2A\x0C\x72\x93\x03\x32\xF6\xF2\xCC\x77\xF6\x22\xA3\xC5\x88\xD5\xBF\
\x09\xED\xCA\x4D\x2F\x13\xCE\xC7\x8D\x34\x59\x0D\xD2\x83\x9C\xE7\x95\x00\x77\
\x61\x02\x7B\xA8\x06\x39\x70\x74\xAF\x83\x32\x70\x53\x8C\xF5\xC7\x11\xDA\xDF\
\x2D\xB7\x01";
#[test]
fn test_der_to_der() {
let res = convert(
&CERT_DER,
&Format::Der,
&Format::Der,
&PersistKind::Certificate,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(CERT_DER, res.as_slice());
}
#[test]
fn test_pem_to_pem() {
let res = convert(
&CERT_PEM,
&Format::Pem,
&Format::Pem,
&PersistKind::Certificate,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(CERT_PEM, res.as_slice());
}
#[test]
fn test_der_to_pem_pk() {
let res = convert(
&PK_DER,
&Format::Der,
&Format::Pem,
&PersistKind::PrivateKey,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(PK_PEM, res.as_slice());
}
#[test]
fn test_der_to_pem_crt() {
let res = convert(
&CERT_DER,
&Format::Der,
&Format::Pem,
&PersistKind::Certificate,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(CERT_PEM, res.as_slice());
}
#[test]
fn test_pem_to_der_crt() {
let res = convert(
&CERT_PEM,
&Format::Pem,
&Format::Der,
&PersistKind::Certificate,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(CERT_DER, res.as_slice());
}
#[test]
fn test_pem_to_der_pk() {
let res = convert(
&PK_PEM,
&Format::Pem,
&Format::Der,
&PersistKind::PrivateKey,
);
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(PK_DER, res.as_slice());
}
}

58
acmed/src/errors.rs

@ -0,0 +1,58 @@
use std::fmt;
pub struct Error {
pub message: String,
}
impl Error {
pub fn new(msg: &str) -> Self {
Error {
message: msg.to_string(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Error::new(&format!("IO error: {}", error))
}
}
impl From<toml::de::Error> for Error {
fn from(error: toml::de::Error) -> Self {
Error::new(&format!("IO error: {}", error))
}
}
impl From<acme_lib::Error> for Error {
fn from(error: acme_lib::Error) -> Self {
let msg = match error {
acme_lib::Error::ApiProblem(e) => format!("An API call failed: {}", e),
acme_lib::Error::Call(e) => format!("An API call failed: {}", e),
acme_lib::Error::Base64Decode(e) => format!("base 64 decode error: {}", e),
acme_lib::Error::Json(e) => format!("JSON error: {}", e),
acme_lib::Error::Io(e) => format!("IO error: {}", e),
acme_lib::Error::Other(s) => s,
};
Error::new(&msg)
}
}
impl From<handlebars::TemplateRenderError> for Error {
fn from(error: handlebars::TemplateRenderError) -> Self {
Error::new(&format!("Template error: {}", error))
}
}
#[cfg(unix)]
impl From<nix::Error> for Error {
fn from(error: nix::Error) -> Self {
Error::new(&format!("{}", error))
}
}

75
acmed/src/main.rs

@ -0,0 +1,75 @@
use clap::{App, Arg};
use env_logger::Builder;
use log::{error, LevelFilter};
mod acmed;
mod config;
mod encoding;
mod errors;
mod storage;
pub const DEFAULT_CONFIG_FILE: &str = "/etc/acmed/acmed.toml";
pub const DEFAULT_ACCOUNTS_DIR: &str = "/etc/acmed/accounts";
pub const DEFAULT_CERT_DIR: &str = "/etc/acmed/certs";
pub const DEFAULT_CERT_FORMAT: &str = "{name}_{algo}.{kind}.{ext}";
pub const DEFAULT_ALGO: &str = "rsa2048";
pub const DEFAULT_FMT: acmed::Format = acmed::Format::Pem;
pub const DEFAULT_SLEEP_TIME: u64 = 3600;
pub const DEFAULT_POOL_TIME: u64 = 5000;
pub const DEFAULT_CERT_FILE_MODE: u32 = 0o644;
pub const DEFAULT_PK_FILE_MODE: u32 = 0o600;
fn main() {
let matches = App::new("acmed")
.version("0.1.0")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
.help("Specify an alternative configuration file.")
.takes_value(true)
.value_name("FILE"),
)
.arg(
Arg::with_name("log-level")
.long("log-level")
.help("Specify the log level.")
.takes_value(true)
.value_name("LEVEL")
.possible_values(&["error", "warn", "info", "debug", "trace"]),
)
.get_matches();
let mut builder = Builder::from_env("ACMED_LOG_LEVEL");
if let Some(v) = matches.value_of("log-level") {
match v {
"error" => {
builder.filter_level(LevelFilter::Error);
}
"warn" => {
builder.filter_level(LevelFilter::Warn);
}
"info" => {
builder.filter_level(LevelFilter::Info);
}
"debug" => {
builder.filter_level(LevelFilter::Debug);
}
"trace" => {
builder.filter_level(LevelFilter::Trace);
}
_ => {}
}
};
builder.init();
let config_file = matches.value_of("config").unwrap_or(DEFAULT_CONFIG_FILE);
let mut srv = match acmed::Acmed::new(&config_file) {
Ok(s) => s,
Err(e) => {
error!("{}", e);
std::process::exit(1);
}
};
srv.run();
}

173
acmed/src/storage.rs

@ -0,0 +1,173 @@
use acme_lib::Error;
use acme_lib::persist::{Persist, PersistKey, PersistKind};
use crate::acmed::{Algorithm, Format};
use crate::encoding::convert;
use log::debug;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::path::PathBuf;
#[cfg(target_family = "unix")]
use std::os::unix::fs::OpenOptionsExt;
macro_rules! get_file_name {
($self: ident, $kind: ident, $fmt: ident) => {{
let kind = match $kind {
PersistKind::Certificate => "crt",
PersistKind::PrivateKey => "pk",
PersistKind::AccountPrivateKey => "pk",
};
format!(
// TODO: use self.crt_name_format instead of a string literal
"{name}_{algo}.{kind}.{ext}",
name = $self.crt_name,
algo = $self.algo.to_string(),
kind = kind,
ext = $fmt.to_string()
)
}};
}
#[derive(Clone, Debug)]
pub struct Storage {
pub account_directory: String,
pub account_name: String,
pub crt_directory: String,
pub crt_name: String,
pub crt_name_format: String,
pub formats: Vec<Format>,
pub algo: Algorithm,
pub cert_file_mode: u32,
pub cert_file_owner: Option<String>,
pub cert_file_group: Option<String>,
pub pk_file_mode: u32,
pub pk_file_owner: Option<String>,
pub pk_file_group: Option<String>,
}
impl Storage {
#[cfg(unix)]
fn get_file_mode(&self, kind: PersistKind) -> u32 {
match kind {
PersistKind::Certificate => self.cert_file_mode,
PersistKind::PrivateKey | PersistKind::AccountPrivateKey => self.pk_file_mode,
}
}
#[cfg(unix)]
fn set_owner(&self, path: &PathBuf, kind: PersistKind) -> Result<(), Error> {
let (uid, gid) = match kind {
PersistKind::Certificate => (&self.cert_file_owner, &self.cert_file_group),
PersistKind::PrivateKey | PersistKind::AccountPrivateKey => {
(&self.pk_file_owner, &self.pk_file_group)
}
};
let uid = match uid {
Some(u) => if u.bytes().all(|b| b.is_ascii_digit()) {
let raw_uid = u.parse::<u32>().unwrap();
let nix_uid = nix::unistd::Uid::from_raw(raw_uid);
Some(nix_uid)
} else {
// TODO: handle username
None
},
None => None,
};
let gid = match gid {
Some(g) => if g.bytes().all(|b| b.is_ascii_digit()) {
let raw_gid = g.parse::<u32>().unwrap();
let nix_gid = nix::unistd::Gid::from_raw(raw_gid);
Some(nix_gid)
} else {
// TODO: handle group name
None
},
None => None,
};
match nix::unistd::chown(path, uid, gid) {
Ok(_) => Ok(()),
Err(e) => Err(Error::Other(format!("{}", e))),
}
}
fn get_file_path(&self, kind: PersistKind, fmt: &Format) -> PathBuf {
let base_path = match kind {
PersistKind::Certificate => &self.crt_directory,
PersistKind::PrivateKey => &self.crt_directory,
PersistKind::AccountPrivateKey => &self.account_directory,
};
let file_name = match kind {
PersistKind::Certificate => get_file_name!(self, kind, fmt),
PersistKind::PrivateKey => get_file_name!(self, kind, fmt),
PersistKind::AccountPrivateKey => {
format!("{}.{}", self.account_name.to_owned(), fmt.to_string())
}
};
let mut path = PathBuf::from(base_path);
path.push(file_name);
path
}
pub fn get_certificate(&self, fmt: &Format) -> Result<Option<Vec<u8>>, Error> {
self.get_file(PersistKind::Certificate, fmt)
}
pub fn get_file(&self, kind: PersistKind, fmt: &Format) -> Result<Option<Vec<u8>>, Error> {
let src_fmt = if self.formats.contains(fmt) {
fmt
} else {
self.formats.first().unwrap()
};
let path = self.get_file_path(kind, src_fmt);
debug!("Reading file {:?}", path);
if !path.exists() {
return Ok(None);
}
let mut file = File::open(&path)?;
let mut contents = vec![];
file.read_to_end(&mut contents)?;
if contents.is_empty() {
return Ok(None);
}
if src_fmt == fmt {
Ok(Some(contents))
} else {
let ret = convert(&contents, src_fmt, fmt, kind)?;
Ok(Some(ret))
}
}
}
impl Persist for Storage {
fn put(&self, key: &PersistKey, value: &[u8]) -> Result<(), Error> {
for fmt in self.formats.iter() {
let path = self.get_file_path(key.kind, &fmt);
debug!("Writing file {:?}", path);
{
let mut f = if cfg!(unix) {
let mut options = OpenOptions::new();
options.mode(self.get_file_mode(key.kind));
options.write(true).create(true).open(&path)?
} else {
File::create(&path)?
};
match fmt {
Format::Der => {
let val = convert(value, &Format::Pem, &Format::Der, key.kind)?;
f.write_all(&val)?;
}
Format::Pem => f.write_all(value)?,
};
f.sync_all()?;
}
if cfg!(unix) {
self.set_owner(&path, key.kind)?;
}
}
Ok(())
}
fn get(&self, key: &PersistKey) -> Result<Option<Vec<u8>>, Error> {
self.get_file(key.kind, &Format::Pem)
}
}
Loading…
Cancel
Save