simple-ssl-acme-cloudflare 1.0.11

Simple SSL with ACME and CloudFlare is a tool to simply apply SSL certificates by using OpenSSL and ACME via CloudFlare DNS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#[macro_use]
extern crate concat_with;
extern crate clap;
extern crate terminal_size;

#[macro_use]
extern crate execute;

extern crate path_absolutize;

use std::borrow::Cow;
use std::env;
use std::error::Error;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
use std::process::{self, Stdio};

use clap::{App, Arg};
use terminal_size::terminal_size;

use execute::Execute;
use path_absolutize::Absolutize;

const APP_NAME: &str = "Simple SSL with ACME and CloudFlare";
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const CARGO_PKG_AUTHORS: &str = env!("CARGO_PKG_AUTHORS");

const DEFAULT_OPENSSL_PATH: &str = "openssl";
const DEFAULT_ACME_PATH: &str = "acme.sh";
const DEFAULT_OUTPUT_PATH: &str = "ssl";

fn main() -> Result<(), Box<dyn Error>> {
    let matches = App::new(APP_NAME)
        .set_term_width(terminal_size().map(|(width, _)| width.0 as usize).unwrap_or(0))
        .version(CARGO_PKG_VERSION)
        .author(CARGO_PKG_AUTHORS)
        .about(concat!("Simple SSL with ACME and CloudFlare is a tool to simply apply SSL certificates by using OpenSSL and ACME via CloudFlare DNS.\n\nEXAMPLES:\n", concat_line!(prefix "simple-ssl-acme-cloudflare ",
                "--cf-email xxx@example.com --cf-key xxxooo                    # Applies a SSL certificate and installs to the ssl folder in the current working directory",
                "--cf-email xxx@example.com --cf-key xxxooo -o /path/to/folder # Applies a SSL certificate and installs to /path/to/folder",
            )))
        .arg(Arg::with_name("OPENSSL_PATH")
            .global(true)
            .long("openssl-path")
            .help("Specifies the path of your openssl executable binary file.")
            .takes_value(true)
            .default_value(DEFAULT_OPENSSL_PATH)
        )
        .arg(Arg::with_name("ACME_PATH")
            .global(true)
            .long("acme-path")
            .help("Specifies the path of your ACME executable script file.")
            .takes_value(true)
            .default_value(DEFAULT_ACME_PATH)
        )
        .arg(Arg::with_name("OUTPUT_PATH")
            .long("output")
            .short("o")
            .help("Assigns a destination of your installed certificate files. It should be a folder.")
            .takes_value(true)
            .default_value(DEFAULT_OUTPUT_PATH)
        )
        .arg(Arg::with_name("CF_KEY")
            .long("cf-key")
            .short("k")
            .help("Sets the CloudFlare API key for your domain.")
            .takes_value(true)
        )
        .arg(Arg::with_name("CF_EMAIL")
            .long("cf-email")
            .short("e")
            .help("Sets the CloudFlare API email for your domain.")
            .takes_value(true)
        )
        .arg(Arg::with_name("FORCE_CSR_KEY")
            .long("force-csr-key")
            .help("Forces to regenerate a new CSR and a new key.")
        )
        .arg(Arg::with_name("FORCE_DHPARAM")
            .long("force-dhparam")
            .help("Forces to regenerate a new dhparam.")
        )
        .after_help("Enjoy it! https://magiclen.org")
        .get_matches();

    let openssl_path = matches.value_of("OPENSSL_PATH").unwrap();
    let acme_path = matches.value_of("ACME_PATH").unwrap();

    let output_path = matches.value_of("OUTPUT_PATH").unwrap();

    let cf_key = matches.value_of("CF_KEY");
    let cf_email = matches.value_of("CF_EMAIL");

    let force_csr_key = matches.is_present("FORCE_CSR_KEY");
    let force_dhparam = matches.is_present("FORCE_DHPARAM");

    if command_args!(openssl_path, "version", "-v").execute_check_exit_status_code(0).is_err() {
        return Err("Cannot find openssl.".into());
    }

    if command_args!(acme_path, "--version").execute_check_exit_status_code(0).is_err() {
        return Err("Cannot find acme.sh.".into());
    }

    let cf_key = match cf_key {
        Some(s) => Cow::from(s),
        None => Cow::from(env::var("CF_Key").map_err(|_| "Cannot find CF_Key.")?),
    };

    let cf_email = match cf_email {
        Some(s) => Cow::from(s),
        None => Cow::from(env::var("CF_Email").map_err(|_| "Cannot find CF_Email.")?),
    };

    let output_path = Path::new(output_path);

    match output_path.metadata() {
        Ok(metadata) => {
            if !metadata.is_dir() {
                return Err(format!(
                    "{} exists and it is not a directory.",
                    output_path.absolutize()?.to_string_lossy()
                )
                .into());
            }
        }
        Err(_) => {
            fs::create_dir_all(output_path)?;
        }
    }

    let dhparam_path = Path::join(output_path, "dhparam");
    let csr_path = Path::join(output_path, "csr");
    let key_path = Path::join(output_path, "key");
    let crt_path = Path::join(output_path, "crt");
    let ca_path = Path::join(output_path, "ca");
    let chain_path = Path::join(output_path, "chain");
    let config_txt_path = Path::join(output_path, "config.txt");

    let generate_dhparam = if dhparam_path.exists() {
        if !dhparam_path.is_file() {
            return Err(
                format!("{} is not a file.", dhparam_path.absolutize()?.to_string_lossy()).into()
            );
        }

        force_dhparam
    } else {
        true
    };

    if generate_dhparam {
        println!("Generating dhparam, please wait for minutes...");

        let mut command =
            command_args!(openssl_path, "dhparam", "-dsaparam", "-out", dhparam_path, "4096");

        let output = command.execute_output()?;

        match output.status.code() {
            Some(exit_code) => {
                if exit_code != 0 {
                    return Err("Cannot generate dhparam.".into());
                }
            }
            None => {
                process::exit(1);
            }
        }
    }

    let generate_csr = if csr_path.is_file() && key_path.is_file() {
        force_csr_key
    } else {
        true
    };

    if generate_csr {
        match config_txt_path.metadata() {
            Ok(metadata) => {
                if !metadata.is_file() {
                    return Err(format!(
                        "{} is a directory.",
                        config_txt_path.absolutize()?.to_string_lossy()
                    )
                    .into());
                }
            }
            Err(_) => {
                let mut f = File::create(config_txt_path.as_path())?;

                f.write_all(
                    b"[req]
default_bits       = 4096
prompt             = no
default_md         = sha256
req_extensions     = req_ext
distinguished_name = dn

[dn]
# *Common Name (e.g. server FQDN or YOUR name)
CN =

# Locality Name (e.g. YOUR city name)
L  =

# State or Province Name
ST =

# Organization Name (e.g. YOUR company name)
O  =

# Organizational Unit Name (e.g. YOUR section name)
OU =

# Country Name (ISO 3166-1 alpha-2 code)
C  =

# Email Address
emailAddress    =

[req_ext]
subjectAltName = @alt_names

[alt_names]
DNS.1 =",
                )?;

                println!("Please make your config.txt by using a text editor. For example,");
                println!("\tvim \"{}\"", config_txt_path.to_str().unwrap());

                return Ok(());
            }
        }
        if !config_txt_path.is_file() {
            if config_txt_path.is_dir() {
                return Err(format!("{} is a directory.", config_txt_path.to_str().unwrap()).into());
            }
        } else {
            let mut f = File::create(&config_txt_path)?;

            f.write_all(
                br#"[req]
default_bits       = 4096
prompt             = no
default_md         = sha256
req_extensions     = req_ext
distinguished_name = dn

[dn]
# *Common Name (e.g. server FQDN or YOUR name)
CN =

# Locality Name (e.g. YOUR city name)
L  =

# State or Province Name
ST =

# Organization Name (e.g. YOUR company name)
O  =

# Organizational Unit Name (e.g. YOUR section name)
OU =

# Country Name (ISO 3166-1 alpha-2 code)
C  =

# Email Address
emailAddress    =

[req_ext]
subjectAltName = @alt_names

[alt_names]
DNS.1 ="#,
            )?;

            println!("Please make your config.txt by using a text editor. For example,");
            println!("\tvim \"{}\"", config_txt_path.absolutize()?.to_string_lossy());
            return Ok(());
        }

        let mut command = command_args!(
            openssl_path,
            "req",
            "-config",
            config_txt_path,
            "-newkey",
            "rsa:4096",
            "-out",
            csr_path.as_path(),
            "-nodes",
            "-keyout",
            key_path
        );

        let output = command.execute_output()?;

        match output.status.code() {
            Some(exit_code) => {
                if exit_code != 0 {
                    return Err("Is Your config.txt correct?".into());
                }
            }
            None => {
                process::exit(1);
            }
        }
    }

    println!("Applying your ssl certificate...");

    let domain = {
        let mut command1 = command_args!(acme_path, "--showcsr", "--csr", csr_path.as_path());
        let mut command2 = command!("head -n 1");
        let mut command3 = command!("cut -d '=' -f 2");

        command3.stdout(Stdio::piped());

        let output = command1.execute_multiple_output(&mut [&mut command2, &mut command3])?;

        match output.status.code() {
            Some(exit_code) => {
                if exit_code != 0 {
                    return Err("Is Your CSR correct?".into());
                } else {
                    unsafe { String::from_utf8_unchecked(output.stdout) }
                }
            }
            None => {
                process::exit(1);
            }
        }
    };

    let domain = domain.trim();

    let domain_path = Path::new(acme_path).parent().unwrap().join(domain);

    if fs::remove_dir_all(&domain_path).is_err() {
        // do nothing
    }

    let mut command = command_args!(
        acme_path,
        "--signcsr",
        "--csr",
        csr_path.as_path(),
        "--dns",
        "dns_cf",
        "--force"
    );
    command.env("CF_Key", cf_key.as_ref()).env("CF_Email", cf_email.as_ref());

    let output = command.execute_output()?;

    match output.status.code() {
        Some(exit_code) => {
            if exit_code != 0 {
                return Err("Cannot apply your ssl certificate.".into());
            }
        }
        None => {
            process::exit(1);
        }
    }

    let mut command = command_args!(
        acme_path,
        "--installcert",
        "--cert-file",
        crt_path,
        "--ca-file",
        ca_path,
        "--fullchain-file",
        chain_path,
        "-d",
        domain
    );

    let output = command.execute_output()?;

    match output.status.code() {
        Some(exit_code) => {
            if exit_code != 0 {
                return Err("Cannot install your ssl certificate.".into());
            }
        }
        None => {
            process::exit(1);
        }
    }

    println!("Your new ssl certificate has been applied and installed successfully.");

    println!(
        r#"
-----Nginx-----
ssl_certificate "{0}/chain"
ssl_certificate_key "{0}/key"
ssl_dhparam "{0}/dhparam"

-----Apache-----
SSLCertificateFile "{0}/chain"
SSLCertificateKeyFile "{0}/key"
SSLOpenSSLConfCmd DHParameters "{0}/dhparam""#,
        output_path.absolutize()?.to_string_lossy()
    );

    Ok(())
}