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 crate::tools
::format
::{as_fingerprint, bytes_as_fingerprint}
;
22 use proxmox
::api
::api
;
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.
42 #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
44 /// 32-byte fingerprint, usually calculated with SHA256.
45 pub struct Fingerprint
{
46 #[serde(with = "bytes_as_fingerprint")]
51 pub fn new(bytes
: [u8; 32]) -> Self {
54 pub fn bytes(&self) -> &[u8; 32] {
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]))
66 /// Encryption Configuration with secret key
68 /// This structure stores the secret key and provides helpers for
69 /// authenticated encryption.
70 pub struct CryptConfig
{
73 // A secrect key use to provide the chunk digest name space.
75 // Openssl hmac PKey of id_key
76 id_pkey
: openssl
::pkey
::PKey
<openssl
::pkey
::Private
>,
77 // The private key used by the cipher.
83 /// Create a new instance.
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
> {
89 let mut id_key
= [0u8; 32];
95 MessageDigest
::sha256(),
98 let id_pkey
= openssl
::pkey
::PKey
::hmac(&id_key
).unwrap();
100 Ok(Self { id_key, id_pkey, enc_key, cipher: Cipher::aes_256_gcm() }
)
104 pub fn cipher(&self) -> &Cipher
{
108 /// Compute a chunk digest using a secret name space.
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();
117 hasher
.update(&self.id_key
); // at the end, to avoid length extensions attacks
121 pub fn data_signer(&self) -> openssl
::sign
::Signer
{
122 openssl
::sign
::Signer
::new(MessageDigest
::sha256(), &self.id_pkey
).unwrap()
125 /// Compute authentication tag (hmac/sha256)
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();
137 pub fn fingerprint(&self) -> Fingerprint
{
138 Fingerprint
::new(self.compute_digest(&FINGERPRINT_INPUT
))
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
"")?
; //??
147 /// Encrypt data using a random 16 byte IV.
149 /// Writes encrypted data to ``output``, Return the used IV and computed MAC.
150 pub fn encrypt_to
<W
: Write
>(
154 ) -> Result
<([u8;16], [u8;16]), Error
> {
156 let mut iv
= [0u8; 16];
157 proxmox
::sys
::linux
::fill_with_random_data(&mut iv
)?
;
159 let mut tag
= [0u8; 16];
161 let mut c
= self.data_crypter(&iv
, Mode
::Encrypt
)?
;
163 const BUFFER_SIZE
: usize = 32*1024;
165 let mut encr_buf
= [0u8; BUFFER_SIZE
];
166 let max_encoder_input
= BUFFER_SIZE
- self.cipher
.block_size();
170 let mut end
= start
+ max_encoder_input
;
171 if end
> data
.len() { end = data.len(); }
173 let count
= c
.update(&data
[start
..end
], &mut encr_buf
)?
;
174 output
.write_all(&encr_buf
[..count
])?
;
181 let rest
= c
.finalize(&mut encr_buf
)?
;
182 if rest
> 0 { output.write_all(&encr_buf[..rest])?; }
186 c
.get_tag(&mut tag
)?
;
191 /// Decompress and decrypt data, verify MAC.
192 pub fn decode_compressed_chunk(
197 ) -> Result
<Vec
<u8>, Error
> {
199 let dec
= Vec
::with_capacity(1024*1024);
201 let mut decompressor
= zstd
::stream
::write
::Decoder
::new(dec
)?
;
203 let mut c
= self.data_crypter(iv
, Mode
::Decrypt
)?
;
205 const BUFFER_SIZE
: usize = 32*1024;
207 let mut decr_buf
= [0u8; BUFFER_SIZE
];
208 let max_decoder_input
= BUFFER_SIZE
- self.cipher
.block_size();
212 let mut end
= start
+ max_decoder_input
;
213 if end
> data
.len() { end = data.len(); }
215 let count
= c
.update(&data
[start
..end
], &mut decr_buf
)?
;
216 decompressor
.write_all(&decr_buf
[0..count
])?
;
224 let rest
= c
.finalize(&mut decr_buf
)?
;
225 if rest
> 0 { decompressor.write_all(&decr_buf[..rest])?; }
227 decompressor
.flush()?
;
229 Ok(decompressor
.into_inner())
232 /// Decrypt data, verify tag.
233 pub fn decode_uncompressed_chunk(
238 ) -> Result
<Vec
<u8>, Error
> {
240 let decr_data
= decrypt_aead(