summaryrefslogtreecommitdiff
path: root/src/lib/ops.rs
blob: 27d874bd6ff1b3c1e7ca7295dfb3d6969a32ac74 (plain) (blame)
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
use clap::Args;
use openssl::asn1::Asn1Time;
use openssl::nid::Nid;
use std::cmp::Ordering;
use std::fs;
use std::path::Path;

use crate::KeyType;
use crate::*;

#[derive(Args, Debug)]
#[clap(about = "Generate a new root certificate")]
pub struct Init {
    /// Base directory to store certificates
    #[clap(long, default_value = "~/.hancock", env = "CA_BASE_DIR")]
    pub base_dir: String,

    /// Algorithm to generate private keys ('RSA' or 'ECDSA')
    #[clap(long, short = 't', default_value = "RSA", validator = validate_key_type)]
    pub key_type: String,

    /// Length to use when generating an RSA key. Ignored for ECDSA
    #[clap(long, short = 'b', default_value_t = 4096)]
    pub key_length: u32,

    /// Lifetime in days of the generated certificate
    #[clap(long, short = 'd', default_value_t = 365 * 10)]
    pub lifetime: u32,

    /// Certificate CommonName
    #[clap(long, short = 'n')]
    pub common_name: Option<String>,

    /// Certificate Country
    #[clap(long, short = 'c')]
    pub country: Option<String>,

    /// Certificate State or Province
    #[clap(long, short = 's')]
    pub state: Option<String>,

    /// Certificate Locality
    #[clap(long, short = 'l')]
    pub locality: Option<String>,

    /// Certificate Organization
    #[clap(long, short = 'o')]
    pub organization: Option<String>,

    /// Certificate Organizational Unit
    #[clap(long, short = 'u')]
    pub organizational_unit: Option<String>,

    /// Password for private key
    #[clap(long, short = 'p', env = "CA_PASSWORD")]
    pub password: Option<String>,
}

#[derive(Args, Debug)]
#[clap(about = "Issue a new certificate")]
pub struct Issue {
    /// Base directory to store certificates
    #[clap(long, default_value = "~/.hancock", env = "CA_BASE_DIR")]
    pub base_dir: String,

    /// Algorithm to generate private keys ('RSA' or 'ECDSA')
    #[clap(long, short = 't', default_value = "RSA", validator = validate_key_type)]
    pub key_type: String,

    /// Length to use when generating an RSA key. Ignored for ECDSA
    #[clap(long, short = 'b', default_value_t = 2048)]
    pub key_length: u32,

    /// Lifetime in days of the generated certificate
    #[clap(long, short = 'd', default_value_t = 90)]
    pub lifetime: u32,

    /// Certificate CommonName
    #[clap(long, short = 'n')]
    pub common_name: String,

    /// Certificate Country
    #[clap(long, short = 'c')]
    pub country: Option<String>,

    /// Certificate State or Province
    #[clap(long, short = 's')]
    pub state: Option<String>,

    /// Certificate Locality
    #[clap(long, short = 'l')]
    pub locality: Option<String>,

    /// Certificate Organization
    #[clap(long, short = 'o')]
    pub organization: Option<String>,

    /// Certificate Organizational Unit
    #[clap(long, short = 'u')]
    pub organizational_unit: Option<String>,

    /// Subject Alternative Names
    #[clap(long)]
    pub subject_alt_names: Option<String>,

    /// Password for private key
    #[clap(long, short = 'p', env = "CA_PASSWORD")]
    pub password: Option<String>,
}

#[derive(Args, Debug)]
#[clap(about = "List all known certificates")]
pub struct List {
    #[clap(long, default_value = "~/.hancock", env = "CA_BASE_DIR")]
    pub base_dir: String,
}

pub fn init(args: Init) {
    let base_dir = path::base_dir(&args.base_dir);

    let key_type = match args.key_type.to_uppercase().as_str() {
        "RSA" => KeyType::Rsa(args.key_length),
        "ECDSA" => KeyType::Ecdsa,
        _ => panic!("key_type not ECDSA or RSA after validation. This should never happen"),
    };

    let pkey_path = path::ca_pkey(&base_dir, key_type);

    let pkey = match Path::new(&pkey_path).exists() {
        true => pkey::read_pkey(&pkey_path, args.password),
        false => {
            let pkey = pkey::generate_pkey(key_type);
            pkey::save_pkey(&pkey_path, &pkey, args.password);
            pkey
        }
    };

    let cert_path = path::ca_crt(&base_dir, key_type);
    if !Path::new(&cert_path).exists() {
        let cert = root::generate_root_cert(
            args.lifetime,
            &args.common_name,
            &args.country,
            &args.state,
            &args.locality,
            &args.organization,
            &args.organizational_unit,
            &pkey,
        );
        cert::save_cert(&cert_path, &cert);
    }
}

pub fn issue(args: Issue) {
    let base_dir = path::base_dir(&args.base_dir);

    let key_type = match args.key_type.to_uppercase().as_str() {
        "RSA" => KeyType::Rsa(args.key_length),
        "ECDSA" => KeyType::Ecdsa,
        _ => panic!("key_type not ECDSA or RSA after validation. This should never happen"),
    };

    let ca_pkey_path = path::ca_pkey(&base_dir, key_type);

    let ca_pkey = match Path::new(&ca_pkey_path).exists() {
        true => pkey::read_pkey(&ca_pkey_path, args.password),
        false => {
            let pkey = pkey::generate_pkey(key_type);
            pkey::save_pkey(&ca_pkey_path, &pkey, args.password);
            pkey
        }
    };

    let ca_cert_path = path::ca_crt(&base_dir, key_type);
    let ca_cert = cert::read_cert(&ca_cert_path);

    let pkey_path = path::cert_pkey(&base_dir, &args.common_name, key_type);
    let pkey = match Path::new(&pkey_path).exists() {
        true => pkey::read_pkey(&pkey_path, None),
        false => {
            let pkey = pkey::generate_pkey(key_type);
            pkey::save_pkey(&pkey_path, &pkey, None);
            pkey
        }
    };

    let x509_req_path = path::cert_csr(&base_dir, &args.common_name, key_type);
    let x509_req = {
        let req = req::generate_req(
            &Some(args.common_name.clone()),
            &args.country,
            &args.state,
            &args.locality,
            &args.organization,
            &args.organizational_unit,
            &args.subject_alt_names,
            &pkey,
        );
        req::save_req(&x509_req_path, &req);
        req
    };

    let cert = cert::generate_cert(args.lifetime, &x509_req, &ca_cert, &ca_pkey);
    cert::save_cert(
        &path::cert_crt(&base_dir, &args.common_name, key_type),
        &cert,
    );
}

pub fn list(args: List) {
    let base_dir = path::base_dir(&args.base_dir);

    let rsa_ca_crt_path = path::ca_crt(&base_dir, KeyType::Rsa(0));
    if Path::new(&rsa_ca_crt_path).is_file() {
        let crt = cert::read_cert(&rsa_ca_crt_path);
        println!("{}", cert_info(crt));
    }

    let ecda_ca_crt_path = path::ca_crt(&base_dir, KeyType::Ecdsa);
    if Path::new(&ecda_ca_crt_path).is_file() {
        let crt = cert::read_cert(&ecda_ca_crt_path);
        println!("{}", cert_info(crt));
    }

    for name in fs::read_dir(&base_dir).unwrap() {
        let name = name.unwrap();
        if name.file_type().unwrap().is_dir() {
            let name = format!("{}", name.file_name().to_string_lossy());
            let rsa_crt_path = path::cert_crt(&base_dir, &name, KeyType::Rsa(0));
            if Path::new(&rsa_crt_path).is_file() {
                let crt = cert::read_cert(&rsa_crt_path);
                println!("{}", cert_info(crt));
            }
        
            let ecda_crt_path = path::cert_crt(&base_dir, &name, KeyType::Ecdsa);
            if Path::new(&ecda_crt_path).is_file() {
                let crt = cert::read_cert(&ecda_crt_path);
                println!("{}", cert_info(crt));
            }        
        }
    }
}

fn cert_info(crt: openssl::x509::X509) -> String {
    let now = Asn1Time::days_from_now(0).unwrap();

    let get_cn = |cert: &openssl::x509::X509| -> String {
        let cn = cert.subject_name().entries_by_nid(Nid::COMMONNAME);
        for entry in cn {
            return format!("{}", entry.data().as_utf8().unwrap());
        }
        String::from("Unknown CN")
    };

    let cn = get_cn(&crt);
    let orig = crt.not_before().diff(crt.not_after()).unwrap().days;
    let ex = match now.compare(crt.not_after()).unwrap() {
        Ordering::Greater => {
            match now.diff(crt.not_after()).unwrap().days {
                1 => {
                    String::from("1 day ago")
                }
                d @ _ => {
                    format!("{} days ago", d)
                }
            }
        }
        Ordering::Less => {
            match now.diff(crt.not_after()).unwrap().days {
                1 => {
                    String::from("in 1 day")
                }
                d @ _ => {
                    format!("in {} days", d)
                }
            }
        }
        Ordering::Equal => String::from("right now"),
    };
    format!("{cn} - expires {ex} (originally {orig} days)")
}

fn validate_key_type(input: &str) -> Result<(), String> {
    let input = input.to_string().to_uppercase();
    if input == "RSA" || input == "ECDSA" {
        Ok(())
    } else {
        Err(format!(
            "{} is not a valid key type ['rsa', 'ecdsa']",
            input
        ))
    }
}