Compare commits
15 Commits
023f262fea
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
8f6e1ddc53
|
|||
|
67f925f160
|
|||
|
7a22af7598
|
|||
|
73435ae70a
|
|||
|
9bf2103c47
|
|||
|
1179840114
|
|||
|
5e3ec48259
|
|||
|
cdac6d2aa5
|
|||
|
f5e207654c
|
|||
|
232ad335fa
|
|||
|
c7677bdb70
|
|||
|
fa9c1ecb2c
|
|||
|
8c1add6ff1
|
|||
|
e20aecea81
|
|||
|
531e0bcc24
|
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1 +1,5 @@
|
|||||||
/target
|
/target
|
||||||
|
/.env.ps1
|
||||||
|
/.vscode
|
||||||
|
/.idea
|
||||||
|
|
||||||
|
|||||||
952
Cargo.lock
generated
952
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,22 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "peazyrsa"
|
name = "peazyrsa"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.90"
|
anyhow = "1.0.90"
|
||||||
async-stream = "0.3.6"
|
async-stream = "0.3.6"
|
||||||
|
chrono = "0.4.38"
|
||||||
clap = { version = "4.5.20", features = ["derive"] }
|
clap = { version = "4.5.20", features = ["derive"] }
|
||||||
encoding = "0.2.33"
|
encoding = "0.2.33"
|
||||||
futures = "0.3.31"
|
futures = "0.3.31"
|
||||||
futures-core = "0.3.31"
|
futures-core = "0.3.31"
|
||||||
futures-util = "0.3.31"
|
futures-util = "0.3.31"
|
||||||
|
lazy_static = "1.5.0"
|
||||||
|
openssl = { version="0.10.68" }
|
||||||
regex = "1.11.0"
|
regex = "1.11.0"
|
||||||
tokio = { version = "1.40.0", features = ["fs", "rt", "process", "macros", "io-util"] }
|
tera = "1.20.0"
|
||||||
|
tokio = { version = "1.41.0", features = ["fs", "rt", "process", "macros", "io-util"] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = 3
|
opt-level = 3
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef
|
FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
RUN apt --no-install-recommends update && apt install -y libssl-dev
|
||||||
|
|
||||||
FROM chef AS planner
|
FROM chef AS planner
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|||||||
69
src/arcstr.rs
Normal file
69
src/arcstr.rs
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
use std::ffi::OsStr;
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Ord, PartialOrd, Eq)]
|
||||||
|
pub(crate) struct ArcStr {
|
||||||
|
inner: Arc<str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for ArcStr {
|
||||||
|
type Target = str;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.inner.deref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for ArcStr {
|
||||||
|
fn from(value: &str) -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Arc::from(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(suspicious_double_ref_op)]
|
||||||
|
impl From<&&str> for ArcStr {
|
||||||
|
fn from(value: &&str) -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Arc::from(value.deref()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<OsStr> for ArcStr {
|
||||||
|
fn as_ref(&self) -> &OsStr {
|
||||||
|
self.inner.as_ref().as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<Path> for ArcStr {
|
||||||
|
fn as_ref(&self) -> &Path {
|
||||||
|
self.inner.as_ref().as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<ArcStr> for ArcStr {
|
||||||
|
fn as_ref(&self) -> &ArcStr {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ArcStr {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}", self.deref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArcStr {
|
||||||
|
pub(crate) fn as_path(&self) -> &Path {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn as_str(&self) -> &str {
|
||||||
|
self.inner.deref()
|
||||||
|
}
|
||||||
|
}
|
||||||
47
src/certs.rs
Normal file
47
src/certs.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
|
use std::{path::PathBuf, sync::Arc};
|
||||||
|
|
||||||
|
use crate::common::AppConfig;
|
||||||
|
use crate::crypto_provider::ICryptoProvider;
|
||||||
|
|
||||||
|
pub(crate) struct Certs<T>
|
||||||
|
where
|
||||||
|
T: ICryptoProvider,
|
||||||
|
{
|
||||||
|
pub(crate) ca_file: PathBuf,
|
||||||
|
pub(crate) key_file: PathBuf,
|
||||||
|
pub(crate) cert_file: PathBuf,
|
||||||
|
pub(crate) provider: Arc<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Certs<T>
|
||||||
|
where
|
||||||
|
T: ICryptoProvider,
|
||||||
|
{
|
||||||
|
pub(crate) fn new(cfg: &AppConfig, provider: T) -> Self {
|
||||||
|
let provider = Arc::new(provider);
|
||||||
|
|
||||||
|
Certs {
|
||||||
|
ca_file: cfg.ca_filepath.clone(),
|
||||||
|
key_file: cfg.key_filepath.clone(),
|
||||||
|
cert_file: cfg.cert_filepath.clone(),
|
||||||
|
provider,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn request(&self) -> Result<()> {
|
||||||
|
self.provider.request().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn sign(&self) -> Result<()> {
|
||||||
|
self.provider.sign().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn build_all(&self) -> Result<()> {
|
||||||
|
self.request().await.context("request")?;
|
||||||
|
self.sign().await.context("sign")?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
255
src/common.rs
Normal file
255
src/common.rs
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use async_stream::stream;
|
||||||
|
use clap::Parser;
|
||||||
|
use encoding::{label::encoding_from_whatwg_label, EncoderTrap};
|
||||||
|
use std::{
|
||||||
|
fmt::Display,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
fs::{self, File},
|
||||||
|
io::{AsyncBufReadExt, BufReader},
|
||||||
|
};
|
||||||
|
|
||||||
|
use futures_core::stream::Stream;
|
||||||
|
|
||||||
|
pub(crate) const UTF8_STR: &str = "utf8";
|
||||||
|
pub(crate) const DEFAULT_ENCODING: &str = UTF8_STR;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum OpenSSLProviderArg {
|
||||||
|
Internal,
|
||||||
|
ExternalBin(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Option<&String>> for OpenSSLProviderArg {
|
||||||
|
fn from(value: Option<&String>) -> Self {
|
||||||
|
match value {
|
||||||
|
Some(x) => OpenSSLProviderArg::ExternalBin(x.clone()),
|
||||||
|
_ => OpenSSLProviderArg::Internal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for OpenSSLProviderArg {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
OpenSSLProviderArg::ExternalBin(x) => write!(f, "{}", x),
|
||||||
|
_ => write!(f, "internal"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(author, version, about, long_about = None)]
|
||||||
|
pub(crate) struct Args {
|
||||||
|
/// new client name
|
||||||
|
pub(crate) name: String,
|
||||||
|
|
||||||
|
/// pki directory
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub(crate) directory: Option<String>,
|
||||||
|
|
||||||
|
/// client email
|
||||||
|
#[arg(short, long)]
|
||||||
|
pub(crate) email: Option<String>,
|
||||||
|
|
||||||
|
/// files encoding
|
||||||
|
#[arg(short = 'c', long)]
|
||||||
|
pub(crate) encoding: Option<String>,
|
||||||
|
|
||||||
|
/// keys subdir
|
||||||
|
#[arg(long, default_value = "keys")]
|
||||||
|
pub(crate) keys_dir: String,
|
||||||
|
|
||||||
|
/// config subdir
|
||||||
|
#[arg(long, default_value = "config")]
|
||||||
|
pub(crate) config_dir: String,
|
||||||
|
|
||||||
|
/// valid days
|
||||||
|
#[arg(long, default_value = "3650")]
|
||||||
|
pub(crate) days: u32,
|
||||||
|
|
||||||
|
/// use openssl binary
|
||||||
|
#[arg(long = "with-openssl", short)]
|
||||||
|
pub(crate) openssl: Option<String>,
|
||||||
|
|
||||||
|
/// template file
|
||||||
|
#[arg(long, default_value = "template.ovpn")]
|
||||||
|
pub(crate) template_file: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct AppConfig {
|
||||||
|
pub(crate) encoding: String,
|
||||||
|
pub(crate) req_days: u32,
|
||||||
|
pub(crate) template_file: PathBuf,
|
||||||
|
pub(crate) openssl_default_cnf: String,
|
||||||
|
pub(crate) openssl_cnf_env: String,
|
||||||
|
pub(crate) ca_filepath: PathBuf,
|
||||||
|
pub(crate) ca_key_filepath: PathBuf,
|
||||||
|
pub(crate) default_email_domain: String,
|
||||||
|
pub(crate) openssl: OpenSSLProviderArg,
|
||||||
|
pub(crate) base_directory: PathBuf,
|
||||||
|
pub(crate) email: String,
|
||||||
|
pub(crate) name: String,
|
||||||
|
pub(crate) conf_filepath: PathBuf,
|
||||||
|
pub(crate) req_filepath: PathBuf,
|
||||||
|
pub(crate) key_filepath: PathBuf,
|
||||||
|
pub(crate) cert_filepath: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AppConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
let name = String::from("user");
|
||||||
|
let base_directory: PathBuf = ".".into();
|
||||||
|
let keys_directory = base_directory.join("keys");
|
||||||
|
let config_directory = base_directory.join("config");
|
||||||
|
let template_file = base_directory.join("template.ovpn");
|
||||||
|
let openssl_default_cnf = String::from("openssl-1.0.0.cnf");
|
||||||
|
let ca_filepath = keys_directory.join("ca.crt");
|
||||||
|
let ca_key_filepath = keys_directory.join("ca.key");
|
||||||
|
let req_filepath = keys_directory.join(format!("{}.csr", &name));
|
||||||
|
let key_filepath = keys_directory.join(format!("{}.key", &name));
|
||||||
|
let cert_filepath = keys_directory.join(format!("{}.crt", &name));
|
||||||
|
let conf_filepath = config_directory.join(format!("{}.ovpn", &name));
|
||||||
|
|
||||||
|
Self {
|
||||||
|
encoding: DEFAULT_ENCODING.into(),
|
||||||
|
req_days: 30650,
|
||||||
|
template_file,
|
||||||
|
conf_filepath,
|
||||||
|
req_filepath,
|
||||||
|
key_filepath,
|
||||||
|
cert_filepath,
|
||||||
|
openssl_default_cnf,
|
||||||
|
openssl_cnf_env: "KEY_CONFIG".into(),
|
||||||
|
ca_filepath,
|
||||||
|
ca_key_filepath,
|
||||||
|
default_email_domain: "example.com".into(),
|
||||||
|
openssl: OpenSSLProviderArg::Internal,
|
||||||
|
base_directory,
|
||||||
|
email: "name@example.com".into(),
|
||||||
|
name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&Args> for AppConfig {
|
||||||
|
fn from(args: &Args) -> Self {
|
||||||
|
let defaults = Self::default();
|
||||||
|
|
||||||
|
let name = args.name.clone();
|
||||||
|
let base_directory = args
|
||||||
|
.directory
|
||||||
|
.as_ref()
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or(defaults.base_directory)
|
||||||
|
.clone();
|
||||||
|
|
||||||
|
let keys_directory = base_directory.join(&args.keys_dir);
|
||||||
|
let config_directory = base_directory.join(&args.config_dir);
|
||||||
|
let template_file = base_directory.join(&args.template_file);
|
||||||
|
let openssl_default_cnf = String::from("openssl-1.0.0.cnf");
|
||||||
|
let ca_filepath = keys_directory.join("ca.crt");
|
||||||
|
let ca_key_filepath = keys_directory.join("ca.key");
|
||||||
|
let req_filepath = keys_directory.join(format!("{}.csr", &name));
|
||||||
|
let key_filepath = keys_directory.join(format!("{}.key", &name));
|
||||||
|
let cert_filepath = keys_directory.join(format!("{}.crt", &name));
|
||||||
|
let conf_filepath = config_directory.join(format!("{}.ovpn", &name));
|
||||||
|
|
||||||
|
let email = args.email.clone().unwrap_or(format!(
|
||||||
|
"{}@{}",
|
||||||
|
&args.name,
|
||||||
|
defaults.default_email_domain.clone()
|
||||||
|
));
|
||||||
|
let encoding = if let Some(enc) = args.encoding.clone() {
|
||||||
|
enc.to_string()
|
||||||
|
} else {
|
||||||
|
defaults.encoding.clone()
|
||||||
|
};
|
||||||
|
let name = args.name.clone();
|
||||||
|
let openssl: OpenSSLProviderArg = args.openssl.as_ref().into();
|
||||||
|
let req_days = args.days;
|
||||||
|
|
||||||
|
Self {
|
||||||
|
base_directory,
|
||||||
|
template_file,
|
||||||
|
openssl_default_cnf,
|
||||||
|
ca_filepath,
|
||||||
|
ca_key_filepath,
|
||||||
|
req_filepath,
|
||||||
|
key_filepath,
|
||||||
|
cert_filepath,
|
||||||
|
conf_filepath,
|
||||||
|
email,
|
||||||
|
encoding,
|
||||||
|
name,
|
||||||
|
openssl,
|
||||||
|
req_days,
|
||||||
|
..defaults
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn is_file_exist(filepath: &PathBuf) -> bool {
|
||||||
|
match tokio::fs::metadata(&filepath).await {
|
||||||
|
Ok(x) => x.is_file(),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn read_file<P>(filepath: P, encoding: &str) -> Result<String>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let filepath = PathBuf::from(filepath.as_ref());
|
||||||
|
if encoding == UTF8_STR {
|
||||||
|
return Ok(fs::read_to_string(filepath).await?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let enc = encoding_from_whatwg_label(encoding).ok_or(anyhow!("encoding not found"))?;
|
||||||
|
|
||||||
|
let bytes = fs::read(filepath).await?;
|
||||||
|
enc.decode(&bytes, encoding::DecoderTrap::Ignore)
|
||||||
|
.map_err(|_| anyhow!("could not read file"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn write_file<P: AsRef<Path>>(
|
||||||
|
filepath: P,
|
||||||
|
text: &str,
|
||||||
|
encoding: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
if encoding == UTF8_STR {
|
||||||
|
return Ok(fs::write(filepath, text).await?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let enc = encoding_from_whatwg_label(encoding).ok_or(anyhow!("encoding not found"))?;
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
enc.encode_to(text, EncoderTrap::Ignore, &mut bytes)
|
||||||
|
.map_err(|e| anyhow!("can't encode: {:?}", e))?;
|
||||||
|
|
||||||
|
fs::write(filepath, bytes).await.context("can't write file")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn read_file_by_lines<P: AsRef<Path>>(
|
||||||
|
filepath: P,
|
||||||
|
encoding: &str,
|
||||||
|
) -> Result<Box<dyn Stream<Item = String>>> {
|
||||||
|
Ok(if encoding == UTF8_STR {
|
||||||
|
let f = File::open(filepath).await?;
|
||||||
|
let reader = BufReader::new(f);
|
||||||
|
let mut lines = reader.lines();
|
||||||
|
Box::new(stream! {
|
||||||
|
while let Ok(Some(line)) = lines.next_line().await {
|
||||||
|
yield line
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
let text = read_file(filepath, encoding).await?;
|
||||||
|
Box::new(stream! {
|
||||||
|
for line in text.lines() {
|
||||||
|
yield line.to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
6
src/crypto_provider.rs
Normal file
6
src/crypto_provider.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
pub(crate) trait ICryptoProvider {
|
||||||
|
async fn request(&self) -> Result<()>;
|
||||||
|
async fn sign(&self) -> Result<()>;
|
||||||
|
}
|
||||||
562
src/main.rs
562
src/main.rs
@@ -1,513 +1,52 @@
|
|||||||
use anyhow::{anyhow, Context, Result};
|
use anyhow::{anyhow, Context, Result};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use encoding::{label::encoding_from_whatwg_label, EncoderTrap};
|
use common::{is_file_exist, OpenSSLProviderArg};
|
||||||
use regex::Regex;
|
use crypto_provider::ICryptoProvider;
|
||||||
use std::{
|
|
||||||
collections::BTreeMap,
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
pin::Pin,
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
use tokio::{
|
|
||||||
fs::{self, File},
|
|
||||||
io::{AsyncBufReadExt, BufReader},
|
|
||||||
};
|
|
||||||
use tokio::{pin, process::Command};
|
|
||||||
|
|
||||||
use async_stream::stream;
|
mod arcstr;
|
||||||
|
mod certs;
|
||||||
|
mod common;
|
||||||
|
mod crypto_provider;
|
||||||
|
mod openssl;
|
||||||
|
mod ovpn;
|
||||||
|
mod vars;
|
||||||
|
|
||||||
use futures_core::stream::Stream;
|
use crate::certs::Certs;
|
||||||
use futures_util::stream::StreamExt;
|
use crate::common::{AppConfig, Args};
|
||||||
|
use crate::openssl::{external::OpenSSLExternalProvider, internal::OpenSSLInternalProvider};
|
||||||
|
use crate::ovpn::OvpnConfig;
|
||||||
|
use crate::vars::{VarsFile, VarsMap};
|
||||||
|
|
||||||
#[derive(Parser)]
|
async fn build_client_with<T: ICryptoProvider>(config: &AppConfig, provider: T) -> Result<String> {
|
||||||
#[command(author, version, about, long_about = None)]
|
let config_file = config.conf_filepath.clone();
|
||||||
struct Args {
|
let config_file_str = config_file
|
||||||
/// new client name
|
.to_str()
|
||||||
name: String,
|
.ok_or(anyhow!("config file exist err"))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
/// pki directory
|
if is_file_exist(&config_file).await {
|
||||||
#[arg(short, long)]
|
return Err(anyhow!("Config file exist: {}", &config_file_str));
|
||||||
directory: Option<String>,
|
}
|
||||||
|
|
||||||
/// client email
|
let certs = Certs::new(config, provider);
|
||||||
#[arg(short, long)]
|
OvpnConfig::try_from_certs(certs, config)
|
||||||
email: Option<String>,
|
.await?
|
||||||
|
.render()?
|
||||||
|
.to_file(&config_file)
|
||||||
|
.await?;
|
||||||
|
|
||||||
/// files encoding
|
Ok(config_file_str)
|
||||||
#[arg(short = 'c', long)]
|
|
||||||
encoding: Option<String>,
|
|
||||||
|
|
||||||
/// keys subdir
|
|
||||||
#[arg(long, default_value = "keys")]
|
|
||||||
keys_dir: String,
|
|
||||||
|
|
||||||
/// config subdir
|
|
||||||
#[arg(long, default_value = "config")]
|
|
||||||
config_dir: String,
|
|
||||||
|
|
||||||
/// valid days
|
|
||||||
#[arg(long, default_value = "30650")]
|
|
||||||
days: u32,
|
|
||||||
|
|
||||||
/// openssl binary
|
|
||||||
#[arg(long, default_value = "openssl")]
|
|
||||||
openssl: String,
|
|
||||||
|
|
||||||
/// template file
|
|
||||||
#[arg(long, default_value = "template.ovpn")]
|
|
||||||
template_file: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct VarsFile {
|
async fn build_client_config(config: &AppConfig, vars: VarsMap) -> Result<String> {
|
||||||
filepath: PathBuf,
|
match config.openssl {
|
||||||
vars: Option<BTreeMap<String, String>>,
|
OpenSSLProviderArg::Internal => {
|
||||||
encoding: String,
|
let provider = OpenSSLInternalProvider::try_from_cfg(config, vars)?;
|
||||||
}
|
build_client_with(config, provider).await
|
||||||
|
|
||||||
struct AppConfig {
|
|
||||||
encoding: String,
|
|
||||||
req_days: u32,
|
|
||||||
keys_subdir: String,
|
|
||||||
config_subdir: String,
|
|
||||||
template_file: String,
|
|
||||||
openssl_default_cnf: String,
|
|
||||||
openssl_cnf_env: String,
|
|
||||||
ca_filename: String,
|
|
||||||
default_email_domain: String,
|
|
||||||
openssl: String,
|
|
||||||
base_directory: String,
|
|
||||||
email: String,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AppConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
encoding: "cp866".into(),
|
|
||||||
req_days: 30650,
|
|
||||||
keys_subdir: "keys".into(),
|
|
||||||
config_subdir: "config".into(),
|
|
||||||
template_file: "template.ovpn".into(),
|
|
||||||
openssl_default_cnf: "openssl-1.0.0.cnf".into(),
|
|
||||||
openssl_cnf_env: "KEY_CONFIG".into(),
|
|
||||||
ca_filename: "ca.crt".into(),
|
|
||||||
default_email_domain: "example.com".into(),
|
|
||||||
openssl: "openssl".into(),
|
|
||||||
base_directory: ".".into(),
|
|
||||||
email: "name@example.com".into(),
|
|
||||||
name: "user".into(),
|
|
||||||
}
|
}
|
||||||
}
|
OpenSSLProviderArg::ExternalBin(_) => {
|
||||||
}
|
let provider = OpenSSLExternalProvider::from_cfg(config, vars);
|
||||||
|
build_client_with(config, provider).await
|
||||||
impl From<&Args> for AppConfig {
|
|
||||||
fn from(args: &Args) -> Self {
|
|
||||||
let defaults = Self::default();
|
|
||||||
|
|
||||||
let base_directory = args
|
|
||||||
.directory
|
|
||||||
.as_ref()
|
|
||||||
.unwrap_or(&defaults.base_directory)
|
|
||||||
.clone();
|
|
||||||
let email = args.email.clone().unwrap_or(format!(
|
|
||||||
"{}@{}",
|
|
||||||
&args.name,
|
|
||||||
defaults.default_email_domain.clone()
|
|
||||||
));
|
|
||||||
let encoding = if let Some(enc) = args.encoding.clone() {
|
|
||||||
enc.to_string()
|
|
||||||
} else {
|
|
||||||
defaults.encoding.clone()
|
|
||||||
};
|
|
||||||
let name = args.name.clone();
|
|
||||||
let openssl = args.openssl.clone();
|
|
||||||
let template_file = args.template_file.clone();
|
|
||||||
let req_days = args.days;
|
|
||||||
let keys_subdir = args.keys_dir.clone();
|
|
||||||
let config_subdir = args.config_dir.clone();
|
|
||||||
|
|
||||||
Self {
|
|
||||||
base_directory,
|
|
||||||
email,
|
|
||||||
encoding,
|
|
||||||
name,
|
|
||||||
openssl,
|
|
||||||
template_file,
|
|
||||||
req_days,
|
|
||||||
keys_subdir,
|
|
||||||
config_subdir,
|
|
||||||
..defaults
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_file_exist(filepath: &PathBuf) -> bool {
|
|
||||||
let metadata = tokio::fs::metadata(&filepath).await;
|
|
||||||
if metadata.is_err() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if !metadata.unwrap().is_file() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read_file<'a, S, P>(filepath: P, encoding: S) -> Result<String>
|
|
||||||
where
|
|
||||||
S: AsRef<str> + std::cmp::PartialEq<&'a str>,
|
|
||||||
P: AsRef<Path>,
|
|
||||||
{
|
|
||||||
let filepath = PathBuf::from(filepath.as_ref());
|
|
||||||
if encoding == "utf8" {
|
|
||||||
return Ok(fs::read_to_string(filepath).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
let enc = encoding_from_whatwg_label(encoding.as_ref()).ok_or(anyhow!("encoding not found"))?;
|
|
||||||
|
|
||||||
let bytes = fs::read(filepath).await?;
|
|
||||||
enc.decode(&bytes, encoding::DecoderTrap::Ignore)
|
|
||||||
.map_err(|_| anyhow!("could not read file"))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn write_file(filepath: &PathBuf, text: String, encoding: &str) -> Result<()> {
|
|
||||||
if encoding == "utf8" {
|
|
||||||
return Ok(fs::write(filepath, text).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
let enc = encoding_from_whatwg_label(encoding).ok_or(anyhow!("encoding not found"))?;
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
enc.encode_to(&text, EncoderTrap::Ignore, &mut bytes)
|
|
||||||
.map_err(|_| anyhow!("can't encode"))?;
|
|
||||||
|
|
||||||
fs::write(filepath, bytes).await.context("can't write file")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read_file_by_lines(
|
|
||||||
filepath: &PathBuf,
|
|
||||||
encoding: &str,
|
|
||||||
) -> Result<Box<dyn Stream<Item = String>>> {
|
|
||||||
Ok(if encoding == "utf8" {
|
|
||||||
let f = File::open(filepath).await?;
|
|
||||||
let reader = BufReader::new(f);
|
|
||||||
let mut lines = reader.lines();
|
|
||||||
Box::new(stream! {
|
|
||||||
while let Ok(Some(line)) = lines.next_line().await {
|
|
||||||
yield line
|
|
||||||
}
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
let text = read_file(filepath, encoding).await?;
|
|
||||||
Box::new(stream! {
|
|
||||||
for line in text.lines() {
|
|
||||||
yield line.to_string()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VarsFile {
|
|
||||||
async fn from_file(filepath: &PathBuf, encoding: String) -> Result<Self> {
|
|
||||||
let metadata = tokio::fs::metadata(&filepath).await.context(format!(
|
|
||||||
"file not found {}",
|
|
||||||
filepath.to_str().expect("str")
|
|
||||||
))?;
|
|
||||||
if !metadata.is_file() {
|
|
||||||
Err(anyhow!("{} is not a file", filepath.to_str().expect("str")))?
|
|
||||||
}
|
|
||||||
Ok(VarsFile {
|
|
||||||
filepath: filepath.to_path_buf(),
|
|
||||||
vars: None,
|
|
||||||
encoding,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn from_dir(dir: PathBuf, encoding: String) -> Result<Self> {
|
|
||||||
let filepath = dir.join("vars");
|
|
||||||
let err_context = format!(
|
|
||||||
"vars or vars.bat file not found in {}",
|
|
||||||
dir.to_str().expect("str")
|
|
||||||
);
|
|
||||||
|
|
||||||
match Self::from_file(&filepath, encoding.clone()).await {
|
|
||||||
Ok(res) => Ok(res),
|
|
||||||
Err(_) => Self::from_file(&filepath.with_extension("bat"), encoding.clone())
|
|
||||||
.await
|
|
||||||
.map_err(|e| e.context(err_context)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn from_config(config: &AppConfig) -> Result<Self> {
|
|
||||||
Self::from_dir(
|
|
||||||
PathBuf::from(&config.base_directory),
|
|
||||||
config.encoding.clone(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn parse(&mut self) -> Result<()> {
|
|
||||||
let mut result = BTreeMap::new();
|
|
||||||
let lines = read_file_by_lines(&self.filepath, &self.encoding).await?;
|
|
||||||
let lines = Pin::from(lines);
|
|
||||||
pin!(lines);
|
|
||||||
|
|
||||||
let re_v2 =
|
|
||||||
Regex::new(r#"^(export|set)\s\b(?P<key>[\w\d_]+)\b=\s?"?(?P<value>[^\#]+?)"?$"#)
|
|
||||||
.context("regex v2")?;
|
|
||||||
let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^\#]+?)$")
|
|
||||||
.context("regex v3")?;
|
|
||||||
|
|
||||||
while let Some(line) = lines.next().await {
|
|
||||||
if let Some(caps) = re_v2.captures(line.as_str()) {
|
|
||||||
result.insert(caps["key"].to_string(), caps["value"].to_string());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(caps) = re_v3.captures(line.as_str()) {
|
|
||||||
result.insert(caps["key"].to_string(), caps["value"].to_string());
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
self.vars = Some(result);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
fn apply(&self) -> Result<()> {
|
|
||||||
if let Some(vars) = self.vars.clone() {
|
|
||||||
for (key, value) in vars.iter() {
|
|
||||||
unsafe {
|
|
||||||
std::env::set_var(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("vars not parsed"))?
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
trait ICryptoProvider {
|
|
||||||
async fn request(&self) -> Result<()>;
|
|
||||||
async fn sign(&self) -> Result<()>;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct OpenSSLProvider {
|
|
||||||
vars: BTreeMap<String, String>,
|
|
||||||
base_dir: PathBuf,
|
|
||||||
openssl_cnf: PathBuf,
|
|
||||||
openssl: String,
|
|
||||||
ca_file: PathBuf,
|
|
||||||
req_file: PathBuf,
|
|
||||||
key_file: PathBuf,
|
|
||||||
cert_file: PathBuf,
|
|
||||||
req_days: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OpenSSLProvider {
|
|
||||||
async fn is_ca_exists(&self) -> bool {
|
|
||||||
is_file_exist(&self.ca_file).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_cert_exists(&self) -> bool {
|
|
||||||
is_file_exist(&self.cert_file).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_req_exists(&self) -> bool {
|
|
||||||
is_file_exist(&self.req_file).await
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_cfg(cfg: &AppConfig, vars: BTreeMap<String, String>) -> Self {
|
|
||||||
let base_dir = PathBuf::from(&cfg.base_directory);
|
|
||||||
let keys_dir = base_dir.clone().join(cfg.keys_subdir.clone());
|
|
||||||
let name = cfg.name.clone();
|
|
||||||
let mut vars = vars;
|
|
||||||
|
|
||||||
vars.insert("KEY_CN".into(), name.clone());
|
|
||||||
vars.insert("KEY_NAME".into(), name.clone());
|
|
||||||
vars.insert("KEY_EMAIL".into(), cfg.email.clone());
|
|
||||||
|
|
||||||
let ca_file = keys_dir.join(cfg.ca_filename.clone());
|
|
||||||
let req_file = keys_dir.join(format!("{}.csr", &name));
|
|
||||||
let key_file = keys_dir.join(format!("{}.key", &name));
|
|
||||||
let cert_file = keys_dir.join(format!("{}.crt", &name));
|
|
||||||
let openssl_cnf = base_dir.clone().join(
|
|
||||||
std::env::var(cfg.openssl_cnf_env.clone()).unwrap_or(cfg.openssl_default_cnf.clone()),
|
|
||||||
);
|
|
||||||
|
|
||||||
Self {
|
|
||||||
vars,
|
|
||||||
base_dir,
|
|
||||||
openssl_cnf,
|
|
||||||
openssl: cfg.openssl.clone(),
|
|
||||||
ca_file,
|
|
||||||
req_file,
|
|
||||||
key_file,
|
|
||||||
cert_file,
|
|
||||||
req_days: cfg.req_days,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ICryptoProvider for OpenSSLProvider {
|
|
||||||
async fn request(&self) -> Result<()> {
|
|
||||||
if self.is_req_exists().await {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !self.is_ca_exists().await {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"ca file not found: {}",
|
|
||||||
&self.ca_file.to_str().unwrap()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let status = Command::new(&self.openssl)
|
|
||||||
.args([
|
|
||||||
"req",
|
|
||||||
"-nodes",
|
|
||||||
"-new",
|
|
||||||
"-keyout",
|
|
||||||
self.key_file.to_str().unwrap(),
|
|
||||||
"-out",
|
|
||||||
self.req_file.to_str().unwrap(),
|
|
||||||
"-config",
|
|
||||||
self.openssl_cnf.to_str().unwrap(),
|
|
||||||
"-batch",
|
|
||||||
])
|
|
||||||
.current_dir(&self.base_dir)
|
|
||||||
.envs(&self.vars)
|
|
||||||
.status()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
match status.success() {
|
|
||||||
true => Ok(()),
|
|
||||||
false => Err(anyhow!("openssl req execution failed")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn sign(&self) -> Result<()> {
|
|
||||||
if self.is_cert_exists().await {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !self.is_ca_exists().await {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"ca file not found: {}",
|
|
||||||
&self.ca_file.to_str().unwrap()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let status = Command::new(&self.openssl)
|
|
||||||
.args([
|
|
||||||
"ca",
|
|
||||||
"-days",
|
|
||||||
format!("{}", self.req_days).as_str(),
|
|
||||||
"-out",
|
|
||||||
self.cert_file.to_str().unwrap(),
|
|
||||||
"-in",
|
|
||||||
self.req_file.to_str().unwrap(),
|
|
||||||
"-config",
|
|
||||||
self.openssl_cnf.to_str().unwrap(),
|
|
||||||
"-batch",
|
|
||||||
])
|
|
||||||
.current_dir(&self.base_dir)
|
|
||||||
.envs(&self.vars)
|
|
||||||
.status()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
match status.success() {
|
|
||||||
true => Ok(()),
|
|
||||||
false => Err(anyhow!("ssl ca execution failed")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Certs<T>
|
|
||||||
where
|
|
||||||
T: ICryptoProvider,
|
|
||||||
{
|
|
||||||
encoding: String,
|
|
||||||
ca_file: PathBuf,
|
|
||||||
key_file: PathBuf,
|
|
||||||
cert_file: PathBuf,
|
|
||||||
config_file: PathBuf,
|
|
||||||
template_file: PathBuf,
|
|
||||||
provider: Arc<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_certs_provider(cfg: &AppConfig, vars: BTreeMap<String, String>) -> impl ICryptoProvider {
|
|
||||||
OpenSSLProvider::from_cfg(cfg, vars)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Certs<T>
|
|
||||||
where
|
|
||||||
T: ICryptoProvider,
|
|
||||||
{
|
|
||||||
fn new(cfg: &AppConfig, provider: T) -> Self {
|
|
||||||
let base_dir = PathBuf::from(&cfg.base_directory);
|
|
||||||
let keys_dir = base_dir.clone().join(cfg.keys_subdir.clone());
|
|
||||||
let config_dir = base_dir.clone().join(cfg.config_subdir.clone());
|
|
||||||
let name = cfg.name.clone();
|
|
||||||
|
|
||||||
Certs {
|
|
||||||
encoding: cfg.encoding.clone(),
|
|
||||||
ca_file: keys_dir.join(cfg.ca_filename.clone()),
|
|
||||||
key_file: keys_dir.join(format!("{}.key", &name)),
|
|
||||||
cert_file: keys_dir.join(format!("{}.crt", &name)),
|
|
||||||
config_file: config_dir.join(format!("{}.ovpn", &name)),
|
|
||||||
template_file: base_dir.clone().join(cfg.template_file.clone()),
|
|
||||||
provider: Arc::new(provider),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_config_exists(&self) -> bool {
|
|
||||||
is_file_exist(&self.config_file).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn request(&self) -> Result<()> {
|
|
||||||
self.provider.request().await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn sign(&self) -> Result<()> {
|
|
||||||
self.provider.sign().await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn build_client_config(&self) -> Result<bool> {
|
|
||||||
if self.is_config_exists().await {
|
|
||||||
return Ok(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.request().await?;
|
|
||||||
self.sign().await?;
|
|
||||||
|
|
||||||
let (template_file, ca_file, cert_file, key_file) = (
|
|
||||||
self.template_file.clone(),
|
|
||||||
self.ca_file.clone(),
|
|
||||||
self.cert_file.clone(),
|
|
||||||
self.key_file.clone(),
|
|
||||||
);
|
|
||||||
let enc = self.encoding.clone();
|
|
||||||
let (enc1, enc2, enc3, enc4) = (enc.clone(), enc.clone(), enc.clone(), enc.clone());
|
|
||||||
|
|
||||||
if let (Ok(Ok(template)), Ok(Ok(ca)), Ok(Ok(cert)), Ok(Ok(key))) = tokio::join!(
|
|
||||||
tokio::spawn(read_file(template_file, enc1)),
|
|
||||||
tokio::spawn(read_file(ca_file, enc2)),
|
|
||||||
tokio::spawn(read_file(cert_file, enc3)),
|
|
||||||
tokio::spawn(read_file(key_file, enc4))
|
|
||||||
) {
|
|
||||||
let text = template
|
|
||||||
.replace("{{ca}}", ca.trim())
|
|
||||||
.replace("{{cert}}", cert.trim())
|
|
||||||
.replace("{{key}}", key.trim());
|
|
||||||
|
|
||||||
write_file(&self.config_file, text, &self.encoding).await?;
|
|
||||||
|
|
||||||
Ok(true)
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("files read error"))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -516,22 +55,17 @@ where
|
|||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
let config = AppConfig::from(&args);
|
let config = AppConfig::from(&args);
|
||||||
let mut vars = VarsFile::from_config(&config).await?;
|
let vars = VarsFile::from_config(&config)
|
||||||
vars.parse().await?;
|
.await
|
||||||
|
.context("vars from config")?
|
||||||
|
.parse()
|
||||||
|
.await
|
||||||
|
.context("parse vars")?;
|
||||||
|
|
||||||
println!("found vars: {}", vars.filepath.to_str().expect("fff"));
|
println!("loaded: {:#?}", &vars);
|
||||||
println!("loaded: {:#?}", &vars.vars);
|
|
||||||
|
|
||||||
let provider = make_certs_provider(&config, vars.vars.unwrap());
|
let config_file = build_client_config(&config, vars).await?;
|
||||||
let certs = Certs::new(&config, provider);
|
println!("created: {}", &config_file);
|
||||||
let created = certs.build_client_config().await?;
|
|
||||||
|
|
||||||
let result_file = certs.config_file.to_str().unwrap();
|
Ok(())
|
||||||
|
|
||||||
if created {
|
|
||||||
println!("created: {result_file}");
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("file exists: {result_file}"))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
136
src/openssl/external.rs
Normal file
136
src/openssl/external.rs
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use tokio::process::Command;
|
||||||
|
|
||||||
|
use crate::common::{is_file_exist, AppConfig};
|
||||||
|
use crate::crypto_provider::ICryptoProvider;
|
||||||
|
use crate::vars::{IStrMap, VarsMap};
|
||||||
|
|
||||||
|
pub(crate) struct OpenSSLExternalProvider {
|
||||||
|
vars: VarsMap,
|
||||||
|
base_dir: PathBuf,
|
||||||
|
openssl_cnf: PathBuf,
|
||||||
|
openssl: String,
|
||||||
|
ca_file: PathBuf,
|
||||||
|
req_file: PathBuf,
|
||||||
|
key_file: PathBuf,
|
||||||
|
cert_file: PathBuf,
|
||||||
|
req_days: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpenSSLExternalProvider {
|
||||||
|
async fn is_ca_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.ca_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_cert_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.cert_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_req_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.req_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_cfg(cfg: &AppConfig, vars: VarsMap) -> Self {
|
||||||
|
let base_dir = PathBuf::from(&cfg.base_directory);
|
||||||
|
let mut vars = vars;
|
||||||
|
|
||||||
|
vars.insert("KEY_CN", &cfg.name);
|
||||||
|
vars.insert("KEY_NAME", &cfg.name);
|
||||||
|
vars.insert("KEY_EMAIL", &cfg.email);
|
||||||
|
|
||||||
|
let openssl_cnf = base_dir.join(
|
||||||
|
std::env::var(&cfg.openssl_cnf_env)
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(&cfg.openssl_default_cnf),
|
||||||
|
);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
vars,
|
||||||
|
base_dir,
|
||||||
|
openssl_cnf,
|
||||||
|
openssl: cfg.openssl.to_string(),
|
||||||
|
ca_file: cfg.ca_filepath.clone(),
|
||||||
|
req_file: cfg.req_filepath.clone(),
|
||||||
|
key_file: cfg.key_filepath.clone(),
|
||||||
|
cert_file: cfg.cert_filepath.clone(),
|
||||||
|
req_days: cfg.req_days,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ICryptoProvider for OpenSSLExternalProvider {
|
||||||
|
async fn request(&self) -> Result<()> {
|
||||||
|
if self.is_req_exists().await {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_ca_exists().await {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"ca file not found: {}",
|
||||||
|
&self.ca_file.to_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let status = Command::new(&self.openssl)
|
||||||
|
.args([
|
||||||
|
"req",
|
||||||
|
"-nodes",
|
||||||
|
"-new",
|
||||||
|
"-keyout",
|
||||||
|
self.key_file.to_str().unwrap(),
|
||||||
|
"-out",
|
||||||
|
self.req_file.to_str().unwrap(),
|
||||||
|
"-config",
|
||||||
|
self.openssl_cnf.to_str().unwrap(),
|
||||||
|
"-batch",
|
||||||
|
])
|
||||||
|
.current_dir(&self.base_dir)
|
||||||
|
.envs(self.vars.deref())
|
||||||
|
.status()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
match status.success() {
|
||||||
|
true => Ok(()),
|
||||||
|
false => Err(anyhow!("openssl req execution failed")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sign(&self) -> Result<()> {
|
||||||
|
if self.is_cert_exists().await {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_ca_exists().await {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"ca file not found: {}",
|
||||||
|
&self.ca_file.to_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let status = Command::new(&self.openssl)
|
||||||
|
.args([
|
||||||
|
"ca",
|
||||||
|
"-days",
|
||||||
|
format!("{}", self.req_days).as_str(),
|
||||||
|
"-out",
|
||||||
|
self.cert_file.to_str().unwrap(),
|
||||||
|
"-in",
|
||||||
|
self.req_file.to_str().unwrap(),
|
||||||
|
"-config",
|
||||||
|
self.openssl_cnf.to_str().unwrap(),
|
||||||
|
"-batch",
|
||||||
|
])
|
||||||
|
.current_dir(&self.base_dir)
|
||||||
|
.envs(self.vars.deref())
|
||||||
|
.status()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
match status.success() {
|
||||||
|
true => Ok(()),
|
||||||
|
false => Err(anyhow!("ssl ca execution failed")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
331
src/openssl/internal.rs
Normal file
331
src/openssl/internal.rs
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use openssl::{
|
||||||
|
asn1::Asn1Time,
|
||||||
|
conf::{Conf, ConfMethod},
|
||||||
|
hash::MessageDigest,
|
||||||
|
pkey::{PKey, Private},
|
||||||
|
rsa::Rsa,
|
||||||
|
stack::Stack,
|
||||||
|
x509::{
|
||||||
|
extension::{ExtendedKeyUsage, KeyUsage, SubjectAlternativeName},
|
||||||
|
X509Extension, X509Name, X509NameBuilder, X509Req, X509ReqBuilder, X509,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use tokio::fs;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
common::{is_file_exist, read_file, AppConfig},
|
||||||
|
crypto_provider::ICryptoProvider,
|
||||||
|
};
|
||||||
|
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use crate::vars::{IStrMap, VarsMap};
|
||||||
|
use chrono::{Datelike, Days, Timelike, Utc};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref KEYMAP: HashMap<&'static str, &'static str> = {
|
||||||
|
let mut m = HashMap::new();
|
||||||
|
m.insert("C", "KEY_COUNTRY");
|
||||||
|
m.insert("ST", "KEY_PROVINCE");
|
||||||
|
m.insert("O", "KEY_ORG");
|
||||||
|
m.insert("OU", "KEY_OU");
|
||||||
|
m.insert("CN", "KEY_CN");
|
||||||
|
m.insert("name", "KEY_NAME");
|
||||||
|
m
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ToPemX {
|
||||||
|
fn to_pem_x(&self) -> Result<Vec<u8>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToPemX for X509 {
|
||||||
|
fn to_pem_x(&self) -> Result<Vec<u8>> {
|
||||||
|
Ok(self.to_pem()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToPemX for X509Req {
|
||||||
|
fn to_pem_x(&self) -> Result<Vec<u8>> {
|
||||||
|
Ok(self.to_pem()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToPemX for PKey<Private> {
|
||||||
|
fn to_pem_x(&self) -> Result<Vec<u8>> {
|
||||||
|
Ok(self.private_key_to_pem_pkcs8()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Pem<'a, T: ToPemX>(&'a T);
|
||||||
|
|
||||||
|
trait WritePem {
|
||||||
|
async fn write<T: AsRef<Path>>(&self, path: T) -> Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, P: ToPemX> WritePem for Pem<'a, P> {
|
||||||
|
async fn write<T: AsRef<Path>>(&self, path: T) -> Result<()> {
|
||||||
|
let pem = self.0.to_pem_x().context("to_pem()")?;
|
||||||
|
fs::write(path, pem).await.context("write pem")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_time_str_x509(days: u32) -> Result<String> {
|
||||||
|
let dt = Utc::now();
|
||||||
|
let dt = dt
|
||||||
|
.checked_add_days(Days::new(days as u64))
|
||||||
|
.ok_or(anyhow!("failed to add days"))
|
||||||
|
.context("checked_add_days")?;
|
||||||
|
|
||||||
|
let year = dt.year() % 10000;
|
||||||
|
let month = dt.month() % 13;
|
||||||
|
let day = dt.day() % 32;
|
||||||
|
let hour = dt.hour() % 25;
|
||||||
|
let minute = dt.minute() % 60;
|
||||||
|
let second = dt.second() % 60;
|
||||||
|
let s = format!("{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}Z");
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct OpenSSLInternalProvider {
|
||||||
|
vars: VarsMap,
|
||||||
|
ca_file: PathBuf,
|
||||||
|
ca_key_file: PathBuf,
|
||||||
|
req_file: PathBuf,
|
||||||
|
key_file: PathBuf,
|
||||||
|
cert_file: PathBuf,
|
||||||
|
req_days: u32,
|
||||||
|
key_size: u32,
|
||||||
|
encoding: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpenSSLInternalProvider {
|
||||||
|
async fn is_ca_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.ca_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_cert_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.cert_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_req_exists(&self) -> bool {
|
||||||
|
is_file_exist(&self.req_file).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn try_from_cfg(cfg: &AppConfig, vars: VarsMap) -> Result<Self> {
|
||||||
|
let mut vars = vars;
|
||||||
|
|
||||||
|
vars.insert("KEY_CN", &cfg.name);
|
||||||
|
vars.insert("KEY_NAME", &cfg.name);
|
||||||
|
vars.insert("KEY_EMAIL", &cfg.email);
|
||||||
|
|
||||||
|
let key_size_s = vars.get(&"KEY_SIZE").unwrap_or("2048");
|
||||||
|
let key_size: u32 = key_size_s.parse().context("parse key size error")?;
|
||||||
|
|
||||||
|
let encoding = cfg.encoding.clone();
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
vars,
|
||||||
|
ca_file: cfg.ca_filepath.clone(),
|
||||||
|
ca_key_file: cfg.ca_key_filepath.clone(),
|
||||||
|
req_file: cfg.req_filepath.clone(),
|
||||||
|
key_file: cfg.key_filepath.clone(),
|
||||||
|
cert_file: cfg.cert_filepath.clone(),
|
||||||
|
req_days: cfg.req_days,
|
||||||
|
key_size,
|
||||||
|
encoding,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_key_pair(&self) -> Result<(Rsa<Private>, PKey<Private>)> {
|
||||||
|
let rsa = Rsa::generate(self.key_size)?;
|
||||||
|
let pkey = PKey::from_rsa(rsa.clone())?;
|
||||||
|
Ok((rsa, pkey))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_ca_cert(&self) -> Result<X509> {
|
||||||
|
let text = read_file(&self.ca_file, &self.encoding).await?;
|
||||||
|
Ok(X509::from_pem(text.as_bytes())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_ca_key(&self) -> Result<PKey<Private>> {
|
||||||
|
let text = read_file(&self.ca_key_file, &self.encoding).await?;
|
||||||
|
Ok(PKey::from_rsa(Rsa::private_key_from_pem(text.as_bytes())?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_key(&self) -> Result<(Rsa<Private>, PKey<Private>)> {
|
||||||
|
let text = read_file(&self.key_file, &self.encoding).await?;
|
||||||
|
let rsa = Rsa::private_key_from_pem(text.as_bytes())?;
|
||||||
|
let pkey = PKey::from_rsa(rsa.clone())?;
|
||||||
|
Ok((rsa, pkey))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_req(&self) -> Result<X509Req> {
|
||||||
|
let text = read_file(&self.req_file, &self.encoding).await?;
|
||||||
|
Ok(X509Req::from_pem(text.as_bytes())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ensure_key(&self) -> Result<(Rsa<Private>, PKey<Private>)> {
|
||||||
|
if is_file_exist(&self.key_file).await {
|
||||||
|
self.get_key().await
|
||||||
|
} else {
|
||||||
|
let (rsa, pkey) = self.generate_key_pair()?;
|
||||||
|
Pem(&pkey)
|
||||||
|
.write(&self.key_file)
|
||||||
|
.await
|
||||||
|
.context("key write pem")?;
|
||||||
|
Ok((rsa, pkey))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_x509_name(&self) -> Result<X509Name> {
|
||||||
|
let mut name_builder =
|
||||||
|
X509NameBuilder::new().context("Failed to create X509 name builder")?;
|
||||||
|
for (&key, &var) in KEYMAP.iter() {
|
||||||
|
let value = self
|
||||||
|
.vars
|
||||||
|
.get(&var)
|
||||||
|
.ok_or(anyhow!("variable not set: {}", var))?;
|
||||||
|
name_builder.append_entry_by_text(key, value)?;
|
||||||
|
}
|
||||||
|
Ok(name_builder.build())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gen_x509_extensions(
|
||||||
|
context: &openssl::x509::X509v3Context,
|
||||||
|
vars: &VarsMap,
|
||||||
|
) -> Result<Vec<X509Extension>> {
|
||||||
|
let key_usage = KeyUsage::new()
|
||||||
|
.key_agreement()
|
||||||
|
.digital_signature()
|
||||||
|
.build()?;
|
||||||
|
let key_extended_ext = ExtendedKeyUsage::new().client_auth().build()?;
|
||||||
|
|
||||||
|
let mut san_extension = SubjectAlternativeName::new();
|
||||||
|
if let Some(name) = vars.get(&"KEY_NAME") {
|
||||||
|
san_extension.dns(name);
|
||||||
|
}
|
||||||
|
if let Some(email) = vars.get(&"KEY_EMAIL") {
|
||||||
|
san_extension.email(email);
|
||||||
|
}
|
||||||
|
let san_ext = san_extension.build(context).context("build san")?;
|
||||||
|
|
||||||
|
Ok(vec![san_ext, key_usage, key_extended_ext])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gen_x509_extensions_stack(
|
||||||
|
context: &openssl::x509::X509v3Context,
|
||||||
|
vars: &VarsMap,
|
||||||
|
) -> Result<Stack<X509Extension>> {
|
||||||
|
let mut stack = Stack::new()?;
|
||||||
|
for extension in Self::gen_x509_extensions(context, vars)?.into_iter() {
|
||||||
|
stack.push(extension).context("push ext")?;
|
||||||
|
}
|
||||||
|
Ok(stack)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ICryptoProvider for OpenSSLInternalProvider {
|
||||||
|
async fn request(&self) -> Result<()> {
|
||||||
|
if self.is_req_exists().await {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_ca_exists().await {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"ca file not found: {}",
|
||||||
|
&self.ca_file.to_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (_, pkey) = self.ensure_key().await?;
|
||||||
|
|
||||||
|
let name = self.build_x509_name()?;
|
||||||
|
let conf = Conf::new(ConfMethod::default()).context("conf new")?;
|
||||||
|
|
||||||
|
// Create certificate signing request (CSR)
|
||||||
|
let mut csr_builder = X509ReqBuilder::new()?;
|
||||||
|
csr_builder.set_version(2).context("set version")?;
|
||||||
|
csr_builder.set_pubkey(&pkey).context("set pubkey")?;
|
||||||
|
csr_builder
|
||||||
|
.set_subject_name(&name)
|
||||||
|
.context("set subject name")?;
|
||||||
|
let context = csr_builder.x509v3_context(Some(&conf));
|
||||||
|
let extensions = Self::gen_x509_extensions_stack(&context, &self.vars)?;
|
||||||
|
csr_builder.add_extensions(&extensions)?;
|
||||||
|
csr_builder.sign(&pkey, MessageDigest::sha512())?;
|
||||||
|
let csr = csr_builder.build();
|
||||||
|
|
||||||
|
Pem(&csr)
|
||||||
|
.write(&self.req_file)
|
||||||
|
.await
|
||||||
|
.context("req write pem")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sign(&self) -> Result<()> {
|
||||||
|
if self.is_cert_exists().await {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_ca_exists().await {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"ca file not found: {}",
|
||||||
|
&self.ca_file.to_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_req_exists().await {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"csr file not found: {}",
|
||||||
|
&self.req_file.to_str().unwrap()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let ca_key = self.get_ca_key().await?;
|
||||||
|
let ca_cert = self.get_ca_cert().await?;
|
||||||
|
|
||||||
|
let req = self.get_req().await?;
|
||||||
|
let pub_key = req.public_key()?;
|
||||||
|
let subject_name = req.subject_name();
|
||||||
|
|
||||||
|
let mut builder = openssl::x509::X509Builder::new().context("new builder")?;
|
||||||
|
let not_before = Asn1Time::days_from_now(0).context("days_from_now 0")?;
|
||||||
|
let na_s = get_time_str_x509(self.req_days).context("na_s get_time_str_x509")?;
|
||||||
|
let not_after = Asn1Time::from_str_x509(&na_s)
|
||||||
|
.context(format!("not_after from_str_x509: {}", &na_s))?;
|
||||||
|
builder.set_version(2).context("set version")?;
|
||||||
|
builder
|
||||||
|
.set_not_before(¬_before)
|
||||||
|
.context("set not_before")?;
|
||||||
|
builder.set_not_after(¬_after).context("set not_after")?;
|
||||||
|
builder
|
||||||
|
.set_issuer_name(ca_cert.issuer_name())
|
||||||
|
.context("set_issuer_name")?;
|
||||||
|
builder.set_pubkey(&pub_key).context("set_pubkey")?;
|
||||||
|
builder
|
||||||
|
.set_subject_name(subject_name)
|
||||||
|
.context("set_subject_name")?;
|
||||||
|
|
||||||
|
let context = builder.x509v3_context(Some(&ca_cert), None);
|
||||||
|
for extension in Self::gen_x509_extensions(&context, &self.vars)? {
|
||||||
|
builder.append_extension(extension).context("append ext")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder
|
||||||
|
.sign(&ca_key, MessageDigest::sha512())
|
||||||
|
.context("builder.sign")?;
|
||||||
|
let cert = builder.build();
|
||||||
|
|
||||||
|
Pem(&cert)
|
||||||
|
.write(&self.cert_file)
|
||||||
|
.await
|
||||||
|
.context("cert.to_pem()")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
2
src/openssl/mod.rs
Normal file
2
src/openssl/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub(crate) mod external;
|
||||||
|
pub(crate) mod internal;
|
||||||
183
src/ovpn.rs
Normal file
183
src/ovpn.rs
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
certs::Certs,
|
||||||
|
common::{read_file, write_file, AppConfig, DEFAULT_ENCODING},
|
||||||
|
crypto_provider::ICryptoProvider,
|
||||||
|
};
|
||||||
|
use anyhow::{anyhow, Context, Ok, Result};
|
||||||
|
use tera::Tera;
|
||||||
|
|
||||||
|
pub(crate) struct OvpnConfig {
|
||||||
|
pub(crate) name: String,
|
||||||
|
pub(crate) encoding: String,
|
||||||
|
pub(crate) email: Option<String>,
|
||||||
|
pub(crate) template: String,
|
||||||
|
pub(crate) template_filename: Option<String>,
|
||||||
|
pub(crate) ca_cert: String,
|
||||||
|
pub(crate) cert: String,
|
||||||
|
pub(crate) key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&OvpnConfig> for tera::Context {
|
||||||
|
fn from(value: &OvpnConfig) -> Self {
|
||||||
|
let mut context = tera::Context::new();
|
||||||
|
context.insert("name", &value.name);
|
||||||
|
context.insert("encoding", &value.encoding);
|
||||||
|
context.insert("email", &value.email);
|
||||||
|
context.insert("template_filename", &value.template_filename);
|
||||||
|
context.insert("ca", &value.ca_cert);
|
||||||
|
context.insert("cert", &value.cert);
|
||||||
|
context.insert("key", &value.key);
|
||||||
|
context
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub(crate) struct OvpnConfigBuilder {
|
||||||
|
name: String,
|
||||||
|
encoding: Option<String>,
|
||||||
|
email: Option<String>,
|
||||||
|
template_file: PathBuf,
|
||||||
|
ca_cert_file: Option<PathBuf>,
|
||||||
|
cert_file: Option<PathBuf>,
|
||||||
|
key_file: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OvpnConfigBuilder {
|
||||||
|
pub(crate) fn new<P: Into<PathBuf>>(name: String, template_file: P) -> Self {
|
||||||
|
Self {
|
||||||
|
name,
|
||||||
|
template_file: template_file.into(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn with_encoding(&mut self, encoding: String) -> &mut Self {
|
||||||
|
self.encoding = Some(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub(crate) fn with_email(&mut self, email: String) -> &mut Self {
|
||||||
|
self.email = Some(email);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub(crate) fn with_ca_cert_file<P: Into<PathBuf>>(&mut self, ca_cert_file: P) -> &mut Self {
|
||||||
|
self.ca_cert_file = Some(ca_cert_file.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub(crate) fn with_cert_file<P: Into<PathBuf>>(&mut self, cert_file: P) -> &mut Self {
|
||||||
|
self.cert_file = Some(cert_file.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub(crate) fn with_key_file<P: Into<PathBuf>>(&mut self, key_file: P) -> &mut Self {
|
||||||
|
self.key_file = Some(key_file.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn build(self) -> Result<OvpnConfig> {
|
||||||
|
let name = self.name;
|
||||||
|
let encoding = self.encoding.unwrap_or(DEFAULT_ENCODING.into());
|
||||||
|
let template = read_file(&self.template_file, &encoding)
|
||||||
|
.await
|
||||||
|
.context("template file read error")?;
|
||||||
|
|
||||||
|
let ca_cert_file = self.ca_cert_file.ok_or(anyhow!("ca cert file not set"))?;
|
||||||
|
let cert_file = self.cert_file.ok_or(anyhow!("cert file not set"))?;
|
||||||
|
let key_file = self.key_file.ok_or(anyhow!("key file not set"))?;
|
||||||
|
|
||||||
|
let ca_cert = read_file(ca_cert_file, &encoding)
|
||||||
|
.await
|
||||||
|
.context("ca cert file read error")?
|
||||||
|
.trim_end()
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let cert = read_file(cert_file, &encoding)
|
||||||
|
.await
|
||||||
|
.context("cert file read error")?
|
||||||
|
.trim_end()
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let key = read_file(key_file, &encoding)
|
||||||
|
.await
|
||||||
|
.context("key file read error")?
|
||||||
|
.trim_end()
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let template_filename = self
|
||||||
|
.template_file
|
||||||
|
.file_name()
|
||||||
|
.ok_or(anyhow!("template_file filename"))?
|
||||||
|
.to_str()
|
||||||
|
.ok_or(anyhow!("template_file to_str"))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
Ok(OvpnConfig {
|
||||||
|
name,
|
||||||
|
encoding,
|
||||||
|
email: self.email,
|
||||||
|
template,
|
||||||
|
ca_cert,
|
||||||
|
cert,
|
||||||
|
key,
|
||||||
|
template_filename: Some(template_filename),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct OvpnConfigRendered {
|
||||||
|
content: String,
|
||||||
|
encoding: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OvpnConfigRendered {
|
||||||
|
pub async fn to_file<P: AsRef<Path>>(&self, filepath: P) -> Result<()> {
|
||||||
|
write_file(filepath, &self.content, &self.encoding)
|
||||||
|
.await
|
||||||
|
.context("ovpn config file write error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<OvpnConfig> for OvpnConfigRendered {
|
||||||
|
type Error = anyhow::Error;
|
||||||
|
|
||||||
|
fn try_from(value: OvpnConfig) -> Result<Self> {
|
||||||
|
let mut tera = Tera::default();
|
||||||
|
tera.add_raw_template("template", &value.template)
|
||||||
|
.context("raw template add error")?;
|
||||||
|
|
||||||
|
let context: tera::Context = (&value).into();
|
||||||
|
let content = tera
|
||||||
|
.render("template", &context)
|
||||||
|
.context("config render error")?;
|
||||||
|
|
||||||
|
Ok(OvpnConfigRendered {
|
||||||
|
content,
|
||||||
|
encoding: value.encoding,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OvpnConfig {
|
||||||
|
pub(crate) fn render(self) -> Result<OvpnConfigRendered> {
|
||||||
|
OvpnConfigRendered::try_from(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn try_from_certs<T: ICryptoProvider>(
|
||||||
|
certs: Certs<T>,
|
||||||
|
config: &AppConfig,
|
||||||
|
) -> Result<Self> {
|
||||||
|
let base_dir = PathBuf::from(&config.base_directory);
|
||||||
|
let template_file = base_dir.join(&config.template_file);
|
||||||
|
|
||||||
|
certs.build_all().await.context("certs build all error")?;
|
||||||
|
|
||||||
|
let mut builder = OvpnConfigBuilder::new(config.name.clone(), template_file);
|
||||||
|
builder
|
||||||
|
.with_encoding(config.encoding.clone())
|
||||||
|
.with_ca_cert_file(certs.ca_file.clone())
|
||||||
|
.with_email(config.email.clone())
|
||||||
|
.with_cert_file(certs.cert_file.clone())
|
||||||
|
.with_key_file(certs.key_file.clone());
|
||||||
|
|
||||||
|
Ok(builder.build().await.context("ovpn config build error")?)
|
||||||
|
}
|
||||||
|
}
|
||||||
130
src/vars.rs
Normal file
130
src/vars.rs
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use regex::Regex;
|
||||||
|
use std::{path::PathBuf, pin::Pin};
|
||||||
|
use tokio::pin;
|
||||||
|
|
||||||
|
use crate::arcstr::ArcStr;
|
||||||
|
use crate::common::{read_file_by_lines, AppConfig};
|
||||||
|
use futures_util::stream::StreamExt;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fmt::{Debug, Formatter};
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub(crate) type ArcVarsMap = BTreeMap<ArcStr, ArcStr>;
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Ord, PartialOrd, Eq)]
|
||||||
|
pub(crate) struct VarsMap(ArcVarsMap);
|
||||||
|
|
||||||
|
pub(crate) trait IStrMap {
|
||||||
|
fn get<S: AsRef<str> + Clone>(&self, key: &S) -> Option<&str>;
|
||||||
|
fn insert<S: AsRef<str> + Clone>(&mut self, key: S, value: S) -> Option<S>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IStrMap for VarsMap {
|
||||||
|
fn get<S: AsRef<str> + Clone>(&self, key: &S) -> Option<&str> {
|
||||||
|
self.0.get(&ArcStr::from(key.as_ref())).map(|x| x.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert<S: AsRef<str> + Clone>(&mut self, key: S, value: S) -> Option<S> {
|
||||||
|
let key = ArcStr::from(key.as_ref());
|
||||||
|
let value2 = ArcStr::from(value.clone().as_ref());
|
||||||
|
self.0.insert(key, value2).and(Some(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for VarsMap {
|
||||||
|
type Target = BTreeMap<ArcStr, ArcStr>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for VarsMap {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let debug_map: BTreeMap<_, _> =
|
||||||
|
self.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||||
|
debug_map.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct VarsFile {
|
||||||
|
pub(crate) filepath: ArcStr,
|
||||||
|
pub(crate) encoding: ArcStr,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VarsFile {
|
||||||
|
async fn from_file<P>(filepath: P, encoding: ArcStr) -> Result<Self>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let filepath_str = filepath
|
||||||
|
.as_ref()
|
||||||
|
.to_str()
|
||||||
|
.ok_or(anyhow!("filepath to str"))?;
|
||||||
|
let metadata = tokio::fs::metadata(filepath_str)
|
||||||
|
.await
|
||||||
|
.context(format!("config file not found: {}", &filepath_str))?;
|
||||||
|
if !metadata.is_file() {
|
||||||
|
Err(anyhow!("config is not a file {}", &filepath_str))?;
|
||||||
|
}
|
||||||
|
Ok(VarsFile {
|
||||||
|
filepath: ArcStr::from(filepath_str),
|
||||||
|
encoding,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_dir<P>(dir: P, encoding: ArcStr) -> Result<Self>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let filepath = dir.as_ref().join("vars");
|
||||||
|
let err_context = "vars or vars.bat file not found";
|
||||||
|
|
||||||
|
match Self::from_file(&filepath, encoding.clone()).await {
|
||||||
|
Ok(res) => Ok(res),
|
||||||
|
Err(_) => Self::from_file(&filepath.with_extension("bat"), encoding.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.context(err_context)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn from_config(config: &AppConfig) -> Result<Self> {
|
||||||
|
Self::from_dir(
|
||||||
|
PathBuf::from(&config.base_directory),
|
||||||
|
ArcStr::from(config.encoding.as_str()),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn parse(&self) -> Result<VarsMap> {
|
||||||
|
let mut result = ArcVarsMap::new();
|
||||||
|
result.insert("__file__".into(), self.filepath.clone());
|
||||||
|
result.insert("__encoding__".into(), self.encoding.clone());
|
||||||
|
|
||||||
|
let lines = read_file_by_lines(&self.filepath.as_path(), &self.encoding)
|
||||||
|
.await
|
||||||
|
.context("vars read error")?;
|
||||||
|
let lines = Pin::from(lines);
|
||||||
|
pin!(lines);
|
||||||
|
|
||||||
|
let re_v2 = Regex::new(r#"^(export|set)\s\b(?P<key>[\w\d_]+)\b=\s?"?(?P<value>[^#]+?)"?$"#)
|
||||||
|
.context("regex v2")
|
||||||
|
.context("re_v2 error")?;
|
||||||
|
let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^#]+?)$")
|
||||||
|
.context("regex v3")
|
||||||
|
.context("re_v3 error")?;
|
||||||
|
|
||||||
|
while let Some(line) = lines.next().await {
|
||||||
|
for re in [&re_v2, &re_v3].iter() {
|
||||||
|
if let Some(caps) = re.captures(line.as_str()) {
|
||||||
|
let [key, value] = [&caps["key"], &caps["value"]].map(ArcStr::from);
|
||||||
|
result.insert(key, value);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(VarsMap(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user