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