summaryrefslogtreecommitdiff
path: root/src/sshkeys.rs
blob: 1425cb3934cf9423a6e28f1d2123a1de49c9fdb9 (plain)
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
//! Generate SSH host keys and certificates.

use std::fs::{read, File, Permissions};
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use tempfile::tempdir;

/// Errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum KeyError {
    /// Could not generate a new key pair.
    #[error("ssh-keygen failed to generate a key: {0}")]
    KeyGen(String),

    /// Error creating a certificate.
    #[error("ssh-keygen failed to certify a key: {0}")]
    CertError(String),

    /// I/O error.
    #[error(transparent)]
    IoError(#[from] std::io::Error),

    /// Error parsing a string as UTF8.
    #[error(transparent)]
    Utf8Error(#[from] std::string::FromUtf8Error),
}

/// Type of SSH key.
pub enum KeyKind {
    /// RSA key of desired length in bits.
    RSA(u32),

    /// DSA of fixed length.
    DSA,

    /// ECDSA key of 256 bits.
    ECDSA256,

    /// ECDSA key of 384 bits.
    ECDSA384,

    /// ECDSA key of 521 bits.
    ECDSA521,

    /// Ed25519 key of fixed length.
    Ed25519,
}

impl KeyKind {
    /// Type of key as string for ssh-keygen -t option.
    pub fn as_str(&self) -> &str {
        match self {
            Self::RSA(_) => "rsa",
            Self::DSA => "dsa",
            Self::ECDSA256 => "ecdsa",
            Self::ECDSA384 => "ecdsa",
            Self::ECDSA521 => "ecdsa",
            Self::Ed25519 => "ed25519",
        }
    }

    /// Number of bits needed for the key.
    ///
    /// This is only really meaningful for RSA keys.
    pub fn bits(&self) -> u32 {
        match self {
            Self::RSA(bits) => *bits,
            Self::DSA => 1024,
            Self::ECDSA256 => 256,
            Self::ECDSA384 => 384,
            Self::ECDSA521 => 521,
            Self::Ed25519 => 1024,
        }
    }
}

/// A public/private key pair.
pub struct KeyPair {
    public: String,
    private: String,
}

impl KeyPair {
    /// Create pair from string representation.
    pub fn from_str(public: String, private: String) -> Self {
        Self { private, public }
    }

    /// Generate a new key pair of the desired kind.
    pub fn generate(kind: KeyKind) -> Result<Self, KeyError> {
        let dirname = tempdir()?;
        let private_key = dirname.path().join("key");
        let output = Command::new("ssh-keygen")
            .arg("-f")
            .arg(&private_key)
            .arg("-t")
            .arg(kind.as_str())
            .arg("-b")
            .arg(format!("{}", kind.bits()))
            .arg("-N")
            .arg("")
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
            return Err(KeyError::KeyGen(stderr));
        }

        let public_key = private_key.with_extension("pub");

        Ok(Self::from_str(
            read_string(&public_key)?,
            read_string(&private_key)?,
        ))
    }

    /// Public key of the pair, as a string.
    pub fn public(&self) -> &str {
        &self.public
    }

    /// Private key of the pair, as a string.
    pub fn private(&self) -> &str {
        &self.private
    }
}

fn read_string(filename: &Path) -> Result<String, KeyError> {
    let bytes = read(filename)?;
    Ok(String::from_utf8(bytes)?)
}

/// A key for SSH certificate authority.
///
/// This is used for creating host certificates.
pub struct CaKey {
    private: String,
}

impl CaKey {
    /// Create new CA key from a key pair.
    pub fn from(pair: KeyPair) -> Self {
        Self {
            private: pair.private().to_string(),
        }
    }

    /// Read CA key from a file.
    pub fn from_file(filename: &Path) -> Result<Self, KeyError> {
        let private = read_string(filename)?;
        Ok(Self { private })
    }

    /// Create a host certificate.
    ///
    /// Return as a string.
    pub fn certify_host(&self, host_key: &KeyPair, hostname: &str) -> Result<String, KeyError> {
        let dirname = tempdir()?;
        let ca_key = dirname.path().join("ca");
        let host_key_pub = dirname.path().join("host.pub");
        let cert = dirname.path().join("host-cert.pub");

        write_string(&ca_key, &self.private)?;
        write_string(&host_key_pub, host_key.public())?;

        let output = Command::new("ssh-keygen")
            .arg("-s")
            .arg(&ca_key)
            .arg("-h")
            .arg("-n")
            .arg(hostname)
            .arg("-I")
            .arg(format!("host key for {}", hostname))
            .arg(&host_key_pub)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
            return Err(KeyError::CertError(stderr));
        }

        Ok(read_string(&cert)?)
    }
}

fn write_string(filename: &Path, s: &str) -> Result<(), KeyError> {
    let mut file = File::create(filename)?;
    let ro_user = Permissions::from_mode(0o600);
    file.set_permissions(ro_user)?;
    file.write_all(s.as_bytes())?;
    Ok(())
}

#[cfg(test)]
mod keypair_test {
    use super::{CaKey, KeyKind, KeyPair};

    #[test]
    fn generate_key() {
        let pair = KeyPair::generate(KeyKind::Ed25519).unwrap();
        assert_ne!(pair.public(), "");
        assert_ne!(pair.private(), "");
        assert_ne!(pair.private(), pair.public());
    }

    #[test]
    fn certify_host_key() {
        let ca = KeyPair::generate(KeyKind::Ed25519).unwrap();
        let ca = CaKey::from(ca);
        let host = KeyPair::generate(KeyKind::Ed25519).unwrap();
        let cert = ca.certify_host(&host, "dummy").unwrap();
        assert_ne!(cert, "");
    }
}