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
//! Encryption and decryption routines for age.

use rand::{rngs::OsRng, RngCore};
use secrecy::{ExposeSecret, SecretString};
use std::io::{self, Read, Seek, Write};

use crate::{
    error::Error,
    format::{scrypt, Header, RecipientLine},
    keys::{FileKey, Identity, RecipientKey},
    primitives::{
        armor::{ArmoredReader, ArmoredWriter},
        hkdf,
        stream::{Stream, StreamReader, StreamWriter},
    },
};

const HEADER_KEY_LABEL: &[u8] = b"header";
const PAYLOAD_KEY_LABEL: &[u8] = b"payload";

/// Handles the various types of age encryption.
pub enum Encryptor {
    /// Encryption to a list of recipients identified by keys.
    Keys(Vec<RecipientKey>),
    /// Encryption to a passphrase.
    Passphrase(SecretString),
}

impl Encryptor {
    fn wrap_file_key(&self, file_key: &FileKey) -> Vec<RecipientLine> {
        match self {
            Encryptor::Keys(recipients) => recipients
                .iter()
                .map(|key| key.wrap_file_key(file_key))
                .collect(),
            Encryptor::Passphrase(passphrase) => {
                vec![scrypt::RecipientLine::wrap_file_key(file_key, passphrase).into()]
            }
        }
    }

    /// Creates a wrapper around a writer that will encrypt its input, and optionally
    /// ASCII armor the output.
    ///
    /// Returns errors from the underlying writer while writing the header.
    ///
    /// You **MUST** call `finish()` when you are done writing, in order to finish the
    /// encryption process. Failing to call `finish()` will result in a truncated message
    /// that will fail to decrypt.
    pub fn wrap_output<W: Write>(&self, output: W, armored: bool) -> io::Result<StreamWriter<W>> {
        let mut output = ArmoredWriter::wrap_output(output, armored)?;

        let file_key = FileKey::generate();

        let header = Header::new(
            self.wrap_file_key(&file_key),
            hkdf(&[], HEADER_KEY_LABEL, file_key.0.expose_secret()),
        );
        header.write(&mut output)?;

        let mut nonce = [0; 16];
        OsRng.fill_bytes(&mut nonce);
        output.write_all(&nonce)?;

        let payload_key = hkdf(&nonce, PAYLOAD_KEY_LABEL, file_key.0.expose_secret());
        Ok(Stream::encrypt(&payload_key, output))
    }
}

/// Handles the various types of age decryption.
pub enum Decryptor {
    /// Trial decryption against a list of secret keys.
    Keys(Vec<Identity>),
    /// Decryption with a passphrase.
    Passphrase(SecretString),
}

impl Decryptor {
    fn unwrap_file_key<P: Fn(&str) -> Option<SecretString> + Copy>(
        &self,
        line: &RecipientLine,
        request_passphrase: P,
    ) -> Result<Option<FileKey>, Error> {
        match (self, line) {
            (Decryptor::Keys(_), RecipientLine::Scrypt(_)) => Err(Error::MessageRequiresPassphrase),
            (Decryptor::Keys(keys), _) => keys
                .iter()
                .find_map(|key| key.unwrap_file_key(line, request_passphrase))
                .transpose(),
            (Decryptor::Passphrase(passphrase), RecipientLine::Scrypt(s)) => {
                s.unwrap_file_key(passphrase)
            }
            (Decryptor::Passphrase(_), _) => Err(Error::MessageRequiresKeys),
        }
    }

    /// Attempts to decrypt a message from the given reader.
    ///
    /// `request_passphrase` is a closure that will be called when an underlying key needs
    /// to be decrypted before it can be used to decrypt the message.
    ///
    /// If successful, returns a reader that will provide the plaintext.
    pub fn trial_decrypt<R: Read, P: Fn(&str) -> Option<SecretString> + Copy>(
        &self,
        input: R,
        request_passphrase: P,
    ) -> Result<impl Read, Error> {
        let mut input = ArmoredReader::from_reader(input);

        let header = Header::read(&mut input)?;

        let mut nonce = [0; 16];
        input.read_exact(&mut nonce)?;

        header
            .recipients
            .iter()
            .find_map(|r| {
                self.unwrap_file_key(r, request_passphrase)
                    .transpose()
                    .map(|res| {
                        res.and_then(|file_key| {
                            // Verify the MAC
                            header.verify_mac(hkdf(
                                &[],
                                HEADER_KEY_LABEL,
                                file_key.0.expose_secret(),
                            ))?;

                            // Return the payload key
                            Ok(hkdf(&nonce, PAYLOAD_KEY_LABEL, file_key.0.expose_secret()))
                        })
                    })
            })
            .unwrap_or(Err(Error::NoMatchingKeys))
            .map(|payload_key| Stream::decrypt(&payload_key, input))
    }

    /// Attempts to decrypt a message from the given seekable reader.
    ///
    /// `request_passphrase` is a closure that will be called when an underlying key needs
    /// to be decrypted before it can be used to decrypt the message.
    ///
    /// If successful, returns a seekable reader that will provide the plaintext.
    pub fn trial_decrypt_seekable<R: Read + Seek, P: Fn(&str) -> Option<SecretString> + Copy>(
        &self,
        mut input: R,
        request_passphrase: P,
    ) -> Result<StreamReader<R>, Error> {
        let header = Header::read(&mut input)?;

        let mut nonce = [0; 16];
        input.read_exact(&mut nonce)?;

        header
            .recipients
            .iter()
            .find_map(|r| {
                self.unwrap_file_key(r, request_passphrase)
                    .transpose()
                    .map(|res| {
                        res.and_then(|file_key| {
                            // Verify the MAC
                            header.verify_mac(hkdf(
                                &[],
                                HEADER_KEY_LABEL,
                                file_key.0.expose_secret(),
                            ))?;

                            // Return the payload key
                            Ok(hkdf(&nonce, PAYLOAD_KEY_LABEL, file_key.0.expose_secret()))
                        })
                    })
            })
            .unwrap_or(Err(Error::NoMatchingKeys))
            .and_then(|payload_key| {
                Stream::decrypt_seekable(&payload_key, input).map_err(Error::from)
            })
    }
}

#[cfg(test)]
mod tests {
    use std::io::{BufReader, Read, Write};

    use super::{Decryptor, Encryptor};
    use crate::keys::{Identity, RecipientKey};

    #[test]
    fn x25519_round_trip() {
        let buf = BufReader::new(crate::keys::tests::TEST_SK.as_bytes());
        let sk = Identity::from_buffer(buf).unwrap();
        let pk: RecipientKey = crate::keys::tests::TEST_PK.parse().unwrap();

        let test_msg = b"This is a test message. For testing.";

        let mut encrypted = vec![];
        let e = Encryptor::Keys(vec![pk]);
        {
            let mut w = e.wrap_output(&mut encrypted, false).unwrap();
            w.write_all(test_msg).unwrap();
            w.finish().unwrap();
        }

        let d = Decryptor::Keys(sk);
        let mut r = d.trial_decrypt(&encrypted[..], |_| None).unwrap();
        let mut decrypted = vec![];
        r.read_to_end(&mut decrypted).unwrap();

        assert_eq!(&decrypted[..], &test_msg[..]);
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn ssh_rsa_round_trip() {
        let buf = BufReader::new(crate::keys::tests::TEST_SSH_RSA_SK.as_bytes());
        let sk = Identity::from_buffer(buf).unwrap();
        let pk: RecipientKey = crate::keys::tests::TEST_SSH_RSA_PK.parse().unwrap();

        let test_msg = b"This is a test message. For testing.";

        let mut encrypted = vec![];
        let e = Encryptor::Keys(vec![pk]);
        {
            let mut w = e.wrap_output(&mut encrypted, false).unwrap();
            w.write_all(test_msg).unwrap();
            w.finish().unwrap();
        }

        let d = Decryptor::Keys(sk);
        let mut r = d.trial_decrypt(&encrypted[..], |_| None).unwrap();
        let mut decrypted = vec![];
        r.read_to_end(&mut decrypted).unwrap();

        assert_eq!(&decrypted[..], &test_msg[..]);
    }

    #[test]
    fn ssh_ed25519_round_trip() {
        let buf = BufReader::new(crate::keys::tests::TEST_SSH_ED25519_SK.as_bytes());
        let sk = Identity::from_buffer(buf).unwrap();
        let pk: RecipientKey = crate::keys::tests::TEST_SSH_ED25519_PK.parse().unwrap();

        let test_msg = b"This is a test message. For testing.";

        let mut encrypted = vec![];
        let e = Encryptor::Keys(vec![pk]);
        {
            let mut w = e.wrap_output(&mut encrypted, false).unwrap();
            w.write_all(test_msg).unwrap();
            w.finish().unwrap();
        }

        let d = Decryptor::Keys(sk);
        let mut r = d.trial_decrypt(&encrypted[..], |_| None).unwrap();
        let mut decrypted = vec![];
        r.read_to_end(&mut decrypted).unwrap();

        assert_eq!(&decrypted[..], &test_msg[..]);
    }
}