]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/crypt_config.rs
switch from failure to anyhow
[proxmox-backup.git] / src / backup / crypt_config.rs
1 //! Wrappers for OpenSSL crypto functions
2 //!
3 //! We use this to encrypt and decryprt data chunks. Cipher is
4 //! AES_256_GCM, which is fast and provides authenticated encryption.
5 //!
6 //! See the Wikipedia Artikel for [Authenticated
7 //! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption)
8 //! for a short introduction.
9 use anyhow::{bail, Error};
10 use openssl::pkcs5::pbkdf2_hmac;
11 use openssl::hash::MessageDigest;
12 use openssl::symm::{decrypt_aead, Cipher, Crypter, Mode};
13 use std::io::Write;
14 use chrono::{Local, TimeZone, DateTime};
15
16 /// Encryption Configuration with secret key
17 ///
18 /// This structure stores the secret key and provides helpers for
19 /// authenticated encryption.
20 pub struct CryptConfig {
21 // the Cipher
22 cipher: Cipher,
23 // A secrect key use to provide the chunk digest name space.
24 id_key: [u8; 32],
25 // Openssl hmac PKey of id_key
26 id_pkey: openssl::pkey::PKey<openssl::pkey::Private>,
27 // The private key used by the cipher.
28 enc_key: [u8; 32],
29
30 }
31
32 impl CryptConfig {
33
34 /// Create a new instance.
35 ///
36 /// We compute a derived 32 byte key using pbkdf2_hmac. This second
37 /// key is used in compute_digest.
38 pub fn new(enc_key: [u8; 32]) -> Result<Self, Error> {
39
40 let mut id_key = [0u8; 32];
41
42 pbkdf2_hmac(
43 &enc_key,
44 b"_id_key",
45 10,
46 MessageDigest::sha256(),
47 &mut id_key)?;
48
49 let id_pkey = openssl::pkey::PKey::hmac(&id_key).unwrap();
50
51 Ok(Self { id_key, id_pkey, enc_key, cipher: Cipher::aes_256_gcm() })
52 }
53
54 /// Expose Cipher
55 pub fn cipher(&self) -> &Cipher {
56 &self.cipher
57 }
58
59 /// Compute a chunk digest using a secret name space.
60 ///
61 /// Computes an SHA256 checksum over some secret data (derived
62 /// from the secret key) and the provided data. This ensures that
63 /// chunk digest values do not clash with values computed for
64 /// other sectret keys.
65 pub fn compute_digest(&self, data: &[u8]) -> [u8; 32] {
66 // FIXME: use HMAC-SHA256 instead??
67 let mut hasher = openssl::sha::Sha256::new();
68 hasher.update(&self.id_key);
69 hasher.update(data);
70 hasher.finish()
71 }
72
73 pub fn data_signer(&self) -> openssl::sign::Signer {
74 openssl::sign::Signer::new(MessageDigest::sha256(), &self.id_pkey).unwrap()
75 }
76
77 /// Compute authentication tag (hmac/sha256)
78 ///
79 /// Computes an SHA256 HMAC using some secret data (derived
80 /// from the secret key) and the provided data.
81 pub fn compute_auth_tag(&self, data: &[u8]) -> [u8; 32] {
82 let mut signer = self.data_signer();
83 signer.update(data).unwrap();
84 let mut tag = [0u8; 32];
85 signer.sign(&mut tag).unwrap();
86 tag
87 }
88
89 pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> {
90 let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?;
91 crypter.aad_update(b"")?; //??
92 Ok(crypter)
93 }
94
95 /// Encrypt data using a random 16 byte IV.
96 ///
97 /// Writes encrypted data to ``output``, Return the used IV and computed MAC.
98 pub fn encrypt_to<W: Write>(
99 &self,
100 data: &[u8],
101 mut output: W,
102 ) -> Result<([u8;16], [u8;16]), Error> {
103
104 let mut iv = [0u8; 16];
105 proxmox::sys::linux::fill_with_random_data(&mut iv)?;
106
107 let mut tag = [0u8; 16];
108
109 let mut c = self.data_crypter(&iv, Mode::Encrypt)?;
110
111 const BUFFER_SIZE: usize = 32*1024;
112
113 let mut encr_buf = [0u8; BUFFER_SIZE];
114 let max_encoder_input = BUFFER_SIZE - self.cipher.block_size();
115
116 let mut start = 0;
117 loop {
118 let mut end = start + max_encoder_input;
119 if end > data.len() { end = data.len(); }
120 if end > start {
121 let count = c.update(&data[start..end], &mut encr_buf)?;
122 output.write_all(&encr_buf[..count])?;
123 start = end;
124 } else {
125 break;
126 }
127 }
128
129 let rest = c.finalize(&mut encr_buf)?;
130 if rest > 0 { output.write_all(&encr_buf[..rest])?; }
131
132 output.flush()?;
133
134 c.get_tag(&mut tag)?;
135
136 Ok((iv, tag))
137 }
138
139 /// Decompress and decrypt data, verify MAC.
140 pub fn decode_compressed_chunk(
141 &self,
142 data: &[u8],
143 iv: &[u8; 16],
144 tag: &[u8; 16],
145 ) -> Result<Vec<u8>, Error> {
146
147 let dec = Vec::with_capacity(1024*1024);
148
149 let mut decompressor = zstd::stream::write::Decoder::new(dec)?;
150
151 let mut c = self.data_crypter(iv, Mode::Decrypt)?;
152
153 const BUFFER_SIZE: usize = 32*1024;
154
155 let mut decr_buf = [0u8; BUFFER_SIZE];
156 let max_decoder_input = BUFFER_SIZE - self.cipher.block_size();
157
158 let mut start = 0;
159 loop {
160 let mut end = start + max_decoder_input;
161 if end > data.len() { end = data.len(); }
162 if end > start {
163 let count = c.update(&data[start..end], &mut decr_buf)?;
164 decompressor.write_all(&decr_buf[0..count])?;
165 start = end;
166 } else {
167 break;
168 }
169 }
170
171 c.set_tag(tag)?;
172 let rest = c.finalize(&mut decr_buf)?;
173 if rest > 0 { decompressor.write_all(&decr_buf[..rest])?; }
174
175 decompressor.flush()?;
176
177 Ok(decompressor.into_inner())
178 }
179
180 /// Decrypt data, verify tag.
181 pub fn decode_uncompressed_chunk(
182 &self,
183 data: &[u8],
184 iv: &[u8; 16],
185 tag: &[u8; 16],
186 ) -> Result<Vec<u8>, Error> {
187
188 let decr_data = decrypt_aead(
189 self.cipher,
190 &self.enc_key,
191 Some(iv),
192 b"", //??
193 data,
194 tag,
195 )?;
196
197 Ok(decr_data)
198 }
199
200 pub fn generate_rsa_encoded_key(
201 &self,
202 rsa: openssl::rsa::Rsa<openssl::pkey::Public>,
203 created: DateTime<Local>,
204 ) -> Result<Vec<u8>, Error> {
205
206 let modified = Local.timestamp(Local::now().timestamp(), 0);
207 let key_config = super::KeyConfig { kdf: None, created, modified, data: self.enc_key.to_vec() };
208 let data = serde_json::to_string(&key_config)?.as_bytes().to_vec();
209
210 let mut buffer = vec![0u8; rsa.size() as usize];
211 let len = rsa.public_encrypt(&data, &mut buffer, openssl::rsa::Padding::PKCS1)?;
212 if len != buffer.len() {
213 bail!("got unexpected length from rsa.public_encrypt().");
214 }
215 Ok(buffer)
216 }
217 }