1 //! Wrappers for OpenSSL crypto functions
3 //! We use this to encrypt and decryprt data chunks. Cipher is
4 //! AES_256_GCM, which is fast and provides authenticated encryption.
6 //! See the Wikipedia Artikel for [Authenticated
7 //! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption)
8 //! for a short introduction.
11 use std
::fmt
::Display
;
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}
;
20 use proxmox
::api
::api
;
22 use pbs_tools
::format
::{as_fingerprint, bytes_as_fingerprint}
;
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,
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.
45 #[derive(Debug, Eq, PartialEq, Hash, Clone, Deserialize, Serialize)]
47 /// 32-byte fingerprint, usually calculated with SHA256.
48 pub struct Fingerprint
{
49 #[serde(with = "bytes_as_fingerprint")]
54 pub fn new(bytes
: [u8; 32]) -> Self {
57 pub fn bytes(&self) -> &[u8; 32] {
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]))
69 impl std
::str::FromStr
for Fingerprint
{
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
))
80 /// Encryption Configuration with secret key
82 /// This structure stores the secret key and provides helpers for
83 /// authenticated encryption.
84 pub struct CryptConfig
{
87 // A secrect key use to provide the chunk digest name space.
89 // Openssl hmac PKey of id_key
90 id_pkey
: openssl
::pkey
::PKey
<openssl
::pkey
::Private
>,
91 // The private key used by the cipher.
97 /// Create a new instance.
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
> {
103 let mut id_key
= [0u8; 32];
109 MessageDigest
::sha256(),
112 let id_pkey
= openssl
::pkey
::PKey
::hmac(&id_key
).unwrap();
114 Ok(Self { id_key, id_pkey, enc_key, cipher: Cipher::aes_256_gcm() }
)
118 pub fn cipher(&self) -> &Cipher
{
122 /// Compute a chunk digest using a secret name space.
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();
131 hasher
.update(&self.id_key
); // at the end, to avoid length extensions attacks
135 pub fn data_signer(&self) -> openssl
::sign
::Signer
{
136 openssl
::sign
::Signer
::new(MessageDigest
::sha256(), &self.id_pkey
).unwrap()
139 /// Compute authentication tag (hmac/sha256)
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();
151 pub fn fingerprint(&self) -> Fingerprint
{
152 Fingerprint
::new(self.compute_digest(&FINGERPRINT_INPUT
))
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
"")?
; //??
161 /// Encrypt data using a random 16 byte IV.
163 /// Writes encrypted data to ``output``, Return the used IV and computed MAC.
164 pub fn encrypt_to
<W
: Write
>(
168 ) -> Result
<([u8;16], [u8;16]), Error
> {
170 let mut iv
= [0u8; 16];
171 proxmox
::sys
::linux
::fill_with_random_data(&mut iv
)?
;
173 let mut tag
= [0u8; 16];
175 let mut c
= self.data_crypter(&iv
, Mode
::Encrypt
)?
;
177 const BUFFER_SIZE
: usize = 32*1024;
179 let mut encr_buf
= [0u8; BUFFER_SIZE
];
180 let max_encoder_input
= BUFFER_SIZE
- self.cipher
.block_size();
184 let mut end
= start
+ max_encoder_input
;
185 if end
> data
.len() { end = data.len(); }
187 let count
= c
.update(&data
[start
..end
], &mut encr_buf
)?
;
188 output
.write_all(&encr_buf
[..count
])?
;
195 let rest
= c
.finalize(&mut encr_buf
)?
;
196 if rest
> 0 { output.write_all(&encr_buf[..rest])?; }
200 c
.get_tag(&mut tag
)?
;
205 /// Decompress and decrypt data, verify MAC.
206 pub fn decode_compressed_chunk(
211 ) -> Result
<Vec
<u8>, Error
> {
213 let dec
= Vec
::with_capacity(1024*1024);
215 let mut decompressor
= zstd
::stream
::write
::Decoder
::new(dec
)?
;
217 let mut c
= self.data_crypter(iv
, Mode
::Decrypt
)?
;
219 const BUFFER_SIZE
: usize = 32*1024;
221 let mut decr_buf
= [0u8; BUFFER_SIZE
];
222 let max_decoder_input
= BUFFER_SIZE
- self.cipher
.block_size();
226 let mut end
= start
+ max_decoder_input
;
227 if end
> data
.len() { end = data.len(); }
229 let count
= c
.update(&data
[start
..end
], &mut decr_buf
)?
;
230 decompressor
.write_all(&decr_buf
[0..count
])?
;
238 let rest
= c
.finalize(&mut decr_buf
)?
;
239 if rest
> 0 { decompressor.write_all(&decr_buf[..rest])?; }
241 decompressor
.flush()?
;
243 Ok(decompressor
.into_inner())
246 /// Decrypt data, verify tag.
247 pub fn decode_uncompressed_chunk(
252 ) -> Result
<Vec
<u8>, Error
> {
254 let decr_data
= decrypt_aead(