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