]> git.proxmox.com Git - proxmox-backup.git/blob - src/backup/crypt_config.rs
add pbs-tools subcrate
[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
10 use std::fmt;
11 use std::fmt::Display;
12 use std::io::Write;
13
14 use anyhow::{Error};
15 use openssl::hash::MessageDigest;
16 use openssl::pkcs5::pbkdf2_hmac;
17 use openssl::symm::{decrypt_aead, Cipher, Crypter, Mode};
18 use serde::{Deserialize, Serialize};
19
20 use proxmox::api::api;
21
22 use pbs_tools::format::{as_fingerprint, bytes_as_fingerprint};
23
24 // openssl::sha::sha256(b"Proxmox Backup Encryption Key Fingerprint")
25 /// This constant is used to compute fingerprints.
26 const FINGERPRINT_INPUT: [u8; 32] = [
27 110, 208, 239, 119, 71, 31, 255, 77,
28 85, 199, 168, 254, 74, 157, 182, 33,
29 97, 64, 127, 19, 76, 114, 93, 223,
30 48, 153, 45, 37, 236, 69, 237, 38,
31 ];
32 #[api(default: "encrypt")]
33 #[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
34 #[serde(rename_all = "kebab-case")]
35 /// Defines whether data is encrypted (using an AEAD cipher), only signed, or neither.
36 pub enum CryptMode {
37 /// Don't encrypt.
38 None,
39 /// Encrypt.
40 Encrypt,
41 /// Only sign.
42 SignOnly,
43 }
44
45 #[derive(Debug, Eq, PartialEq, Hash, Clone, Deserialize, Serialize)]
46 #[serde(transparent)]
47 /// 32-byte fingerprint, usually calculated with SHA256.
48 pub struct Fingerprint {
49 #[serde(with = "bytes_as_fingerprint")]
50 bytes: [u8; 32],
51 }
52
53 impl Fingerprint {
54 pub fn new(bytes: [u8; 32]) -> Self {
55 Self { bytes }
56 }
57 pub fn bytes(&self) -> &[u8; 32] {
58 &self.bytes
59 }
60 }
61
62 /// Display as short key ID
63 impl Display for Fingerprint {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 write!(f, "{}", as_fingerprint(&self.bytes[0..8]))
66 }
67 }
68
69 impl std::str::FromStr for Fingerprint {
70 type Err = Error;
71
72 fn from_str(s: &str) -> Result<Self, Error> {
73 let mut tmp = s.to_string();
74 tmp.retain(|c| c != ':');
75 let bytes = proxmox::tools::hex_to_digest(&tmp)?;
76 Ok(Fingerprint::new(bytes))
77 }
78 }
79
80 /// Encryption Configuration with secret key
81 ///
82 /// This structure stores the secret key and provides helpers for
83 /// authenticated encryption.
84 pub struct CryptConfig {
85 // the Cipher
86 cipher: Cipher,
87 // A secrect key use to provide the chunk digest name space.
88 id_key: [u8; 32],
89 // Openssl hmac PKey of id_key
90 id_pkey: openssl::pkey::PKey<openssl::pkey::Private>,
91 // The private key used by the cipher.
92 enc_key: [u8; 32],
93 }
94
95 impl CryptConfig {
96
97 /// Create a new instance.
98 ///
99 /// We compute a derived 32 byte key using pbkdf2_hmac. This second
100 /// key is used in compute_digest.
101 pub fn new(enc_key: [u8; 32]) -> Result<Self, Error> {
102
103 let mut id_key = [0u8; 32];
104
105 pbkdf2_hmac(
106 &enc_key,
107 b"_id_key",
108 10,
109 MessageDigest::sha256(),
110 &mut id_key)?;
111
112 let id_pkey = openssl::pkey::PKey::hmac(&id_key).unwrap();
113
114 Ok(Self { id_key, id_pkey, enc_key, cipher: Cipher::aes_256_gcm() })
115 }
116
117 /// Expose Cipher
118 pub fn cipher(&self) -> &Cipher {
119 &self.cipher
120 }
121
122 /// Compute a chunk digest using a secret name space.
123 ///
124 /// Computes an SHA256 checksum over some secret data (derived
125 /// from the secret key) and the provided data. This ensures that
126 /// chunk digest values do not clash with values computed for
127 /// other sectret keys.
128 pub fn compute_digest(&self, data: &[u8]) -> [u8; 32] {
129 let mut hasher = openssl::sha::Sha256::new();
130 hasher.update(data);
131 hasher.update(&self.id_key); // at the end, to avoid length extensions attacks
132 hasher.finish()
133 }
134
135 pub fn data_signer(&self) -> openssl::sign::Signer {
136 openssl::sign::Signer::new(MessageDigest::sha256(), &self.id_pkey).unwrap()
137 }
138
139 /// Compute authentication tag (hmac/sha256)
140 ///
141 /// Computes an SHA256 HMAC using some secret data (derived
142 /// from the secret key) and the provided data.
143 pub fn compute_auth_tag(&self, data: &[u8]) -> [u8; 32] {
144 let mut signer = self.data_signer();
145 signer.update(data).unwrap();
146 let mut tag = [0u8; 32];
147 signer.sign(&mut tag).unwrap();
148 tag
149 }
150
151 pub fn fingerprint(&self) -> Fingerprint {
152 Fingerprint::new(self.compute_digest(&FINGERPRINT_INPUT))
153 }
154
155 pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> {
156 let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?;
157 crypter.aad_update(b"")?; //??
158 Ok(crypter)
159 }
160
161 /// Encrypt data using a random 16 byte IV.
162 ///
163 /// Writes encrypted data to ``output``, Return the used IV and computed MAC.
164 pub fn encrypt_to<W: Write>(
165 &self,
166 data: &[u8],
167 mut output: W,
168 ) -> Result<([u8;16], [u8;16]), Error> {
169
170 let mut iv = [0u8; 16];
171 proxmox::sys::linux::fill_with_random_data(&mut iv)?;
172
173 let mut tag = [0u8; 16];
174
175 let mut c = self.data_crypter(&iv, Mode::Encrypt)?;
176
177 const BUFFER_SIZE: usize = 32*1024;
178
179 let mut encr_buf = [0u8; BUFFER_SIZE];
180 let max_encoder_input = BUFFER_SIZE - self.cipher.block_size();
181
182 let mut start = 0;
183 loop {
184 let mut end = start + max_encoder_input;
185 if end > data.len() { end = data.len(); }
186 if end > start {
187 let count = c.update(&data[start..end], &mut encr_buf)?;
188 output.write_all(&encr_buf[..count])?;
189 start = end;
190 } else {
191 break;
192 }
193 }
194
195 let rest = c.finalize(&mut encr_buf)?;
196 if rest > 0 { output.write_all(&encr_buf[..rest])?; }
197
198 output.flush()?;
199
200 c.get_tag(&mut tag)?;
201
202 Ok((iv, tag))
203 }
204
205 /// Decompress and decrypt data, verify MAC.
206 pub fn decode_compressed_chunk(
207 &self,
208 data: &[u8],
209 iv: &[u8; 16],
210 tag: &[u8; 16],
211 ) -> Result<Vec<u8>, Error> {
212
213 let dec = Vec::with_capacity(1024*1024);
214
215 let mut decompressor = zstd::stream::write::Decoder::new(dec)?;
216
217 let mut c = self.data_crypter(iv, Mode::Decrypt)?;
218
219 const BUFFER_SIZE: usize = 32*1024;
220
221 let mut decr_buf = [0u8; BUFFER_SIZE];
222 let max_decoder_input = BUFFER_SIZE - self.cipher.block_size();
223
224 let mut start = 0;
225 loop {
226 let mut end = start + max_decoder_input;
227 if end > data.len() { end = data.len(); }
228 if end > start {
229 let count = c.update(&data[start..end], &mut decr_buf)?;
230 decompressor.write_all(&decr_buf[0..count])?;
231 start = end;
232 } else {
233 break;
234 }
235 }
236
237 c.set_tag(tag)?;
238 let rest = c.finalize(&mut decr_buf)?;
239 if rest > 0 { decompressor.write_all(&decr_buf[..rest])?; }
240
241 decompressor.flush()?;
242
243 Ok(decompressor.into_inner())
244 }
245
246 /// Decrypt data, verify tag.
247 pub fn decode_uncompressed_chunk(
248 &self,
249 data: &[u8],
250 iv: &[u8; 16],
251 tag: &[u8; 16],
252 ) -> Result<Vec<u8>, Error> {
253
254 let decr_data = decrypt_aead(
255 self.cipher,
256 &self.enc_key,
257 Some(iv),
258 b"", //??
259 data,
260 tag,
261 )?;
262
263 Ok(decr_data)
264 }
265 }