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
//! Utilities to generate keys for tests.
//!
//! This is copy-paste from tokio-tls.

use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::process::Command;
use std::process::Stdio;
use std::ptr;
use std::sync::Once;

/// Client certificate
pub struct ClientKeys {
    pub cert_der: Vec<u8>,
}

/// Server keys
pub struct ServerKeys {
    /// Certificate and key
    pub pkcs12: Vec<u8>,
    /// Password from `pkcs12`
    pub pkcs12_password: String,

    /// The same in PEM format
    pub pem: Vec<u8>,
}

/// Client and server keys
pub struct Keys {
    /// Client keys
    pub client: ClientKeys,
    /// Server keys
    pub server: ServerKeys,
}

/// Generate keys
pub fn keys() -> &'static Keys {
    static INIT: Once = Once::new();
    static mut KEYS: *mut Keys = ptr::null_mut();

    INIT.call_once(|| {
        let path = env::current_exe().unwrap();
        let path = path.parent().unwrap();
        let keyfile = path.join("test.key");
        let certfile = path.join("test.crt");
        let config = path.join("openssl.config");

        File::create(&config)
            .unwrap()
            .write_all(
                b"\
                [req]\n\
                distinguished_name=dn\n\
                [dn]\n\
                CN=localhost\n\
                [ext]\n\
                basicConstraints=CA:FALSE,pathlen:0\n\
                subjectAltName = @alt_names\n\
                extendedKeyUsage=serverAuth,clientAuth\n\
                [alt_names]\n\
                DNS.1 = localhost\n\
            ",
            )
            .unwrap();

        let subj = "/C=US/ST=Denial/L=Sprintfield/O=Dis/CN=localhost";
        let output = Command::new("openssl")
            .arg("req")
            .arg("-nodes")
            .arg("-x509")
            .arg("-newkey")
            .arg("rsa:2048")
            .arg("-config")
            .arg(&config)
            .arg("-extensions")
            .arg("ext")
            .arg("-subj")
            .arg(subj)
            .arg("-keyout")
            .arg(&keyfile)
            .arg("-out")
            .arg(&certfile)
            .arg("-days")
            .arg("1")
            .output()
            .unwrap();
        assert!(output.status.success());

        let crtout = Command::new("openssl")
            .arg("x509")
            .arg("-outform")
            .arg("der")
            .arg("-in")
            .arg(&certfile)
            .output()
            .unwrap();
        assert!(crtout.status.success());

        let pkcs12out = Command::new("openssl")
            .arg("pkcs12")
            .arg("-export")
            .arg("-nodes")
            .arg("-inkey")
            .arg(&keyfile)
            .arg("-in")
            .arg(&certfile)
            .arg("-password")
            .arg("pass:foobar")
            .output()
            .unwrap();
        assert!(pkcs12out.status.success());

        let pem = pkcs12_to_pem(&pkcs12out.stdout, "foobar");

        let keys = Box::new(Keys {
            client: ClientKeys {
                cert_der: crtout.stdout,
            },
            server: ServerKeys {
                pem,
                pkcs12: pkcs12out.stdout,
                pkcs12_password: "foobar".to_owned(),
            },
        });
        unsafe {
            KEYS = Box::into_raw(keys);
        }
    });
    unsafe { &*KEYS }
}

fn pkcs12_to_pem(pkcs12: &[u8], passin: &str) -> Vec<u8> {
    let command = Command::new("openssl")
        .arg("pkcs12")
        .arg("-passin")
        .arg(&format!("pass:{}", passin))
        .arg("-nodes")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    command.stdin.unwrap().write_all(pkcs12).unwrap();

    let mut pem = Vec::new();
    command.stdout.unwrap().read_to_end(&mut pem).unwrap();

    pem
}

#[cfg(test)]
mod test {
    #[test]
    fn test() {
        // just check it does something
        super::keys();
    }
}