1 use anyhow
::{bail, format_err, Error}
;
2 use std
::convert
::TryFrom
;
5 use serde_json
::{json, Value}
;
6 use ::serde
::{Deserialize, Serialize}
;
8 use crate::backup
::{BackupDir, CryptMode, CryptConfig}
;
10 pub const MANIFEST_BLOB_NAME
: &str = "index.json.blob";
11 pub const MANIFEST_LOCK_NAME
: &str = ".index.json.lck";
12 pub const CLIENT_LOG_BLOB_NAME
: &str = "client.log.blob";
15 use serde
::{self, Deserialize, Serializer, Deserializer}
;
20 ) -> Result
<S
::Ok
, S
::Error
>
24 let s
= proxmox
::tools
::digest_to_hex(csum
);
25 serializer
.serialize_str(&s
)
28 pub fn deserialize
<'de
, D
>(
30 ) -> Result
<[u8; 32], D
::Error
>
34 let s
= String
::deserialize(deserializer
)?
;
35 proxmox
::tools
::hex_to_digest(&s
).map_err(serde
::de
::Error
::custom
)
39 fn crypt_mode_none() -> CryptMode { CryptMode::None }
40 fn empty_value() -> Value { json!({}
) }
42 #[derive(Serialize, Deserialize)]
43 #[serde(rename_all="kebab-case")]
46 #[serde(default="crypt_mode_none")] // to be compatible with < 0.8.0 backups
47 pub crypt_mode
: CryptMode
,
49 #[serde(with = "hex_csum")]
55 /// Return expected CryptMode of referenced chunks
57 /// Encrypted Indices should only reference encrypted chunks, while signed or plain indices
58 /// should only reference plain chunks.
59 pub fn chunk_crypt_mode (&self) -> CryptMode
{
60 match self.crypt_mode
{
61 CryptMode
::Encrypt
=> CryptMode
::Encrypt
,
62 CryptMode
::SignOnly
| CryptMode
::None
=> CryptMode
::None
,
67 #[derive(Serialize, Deserialize)]
68 #[serde(rename_all="kebab-case")]
69 pub struct BackupManifest
{
74 #[serde(default="empty_value")] // to be compatible with < 0.8.0 backups
75 pub unprotected
: Value
,
76 pub signature
: Option
<String
>,
80 pub enum ArchiveType
{
86 pub fn archive_type
<P
: AsRef
<Path
>>(
88 ) -> Result
<ArchiveType
, Error
> {
90 let archive_name
= archive_name
.as_ref();
91 let archive_type
= match archive_name
.extension().and_then(|ext
| ext
.to_str()) {
92 Some("didx") => ArchiveType
::DynamicIndex
,
93 Some("fidx") => ArchiveType
::FixedIndex
,
94 Some("blob") => ArchiveType
::Blob
,
95 _
=> bail
!("unknown archive type: {:?}", archive_name
),
101 impl BackupManifest
{
103 pub fn new(snapshot
: BackupDir
) -> Self {
105 backup_type
: snapshot
.group().backup_type().into(),
106 backup_id
: snapshot
.group().backup_id().into(),
107 backup_time
: snapshot
.backup_time(),
109 unprotected
: json
!({}
),
114 pub fn add_file(&mut self, filename
: String
, size
: u64, csum
: [u8; 32], crypt_mode
: CryptMode
) -> Result
<(), Error
> {
115 let _archive_type
= archive_type(&filename
)?
; // check type
116 self.files
.push(FileInfo { filename, size, csum, crypt_mode }
);
120 pub fn files(&self) -> &[FileInfo
] {
124 pub fn lookup_file_info(&self, name
: &str) -> Result
<&FileInfo
, Error
> {
126 let info
= self.files
.iter().find(|item
| item
.filename
== name
);
129 None
=> bail
!("manifest does not contain file '{}'", name
),
130 Some(info
) => Ok(info
),
134 pub fn verify_file(&self, name
: &str, csum
: &[u8; 32], size
: u64) -> Result
<(), Error
> {
136 let info
= self.lookup_file_info(name
)?
;
138 if size
!= info
.size
{
139 bail
!("wrong size for file '{}' ({} != {})", name
, info
.size
, size
);
142 if csum
!= &info
.csum
{
143 bail
!("wrong checksum for file '{}'", name
);
149 // Generate canonical json
150 fn to_canonical_json(value
: &Value
) -> Result
<Vec
<u8>, Error
> {
151 let mut data
= Vec
::new();
152 Self::write_canonical_json(value
, &mut data
)?
;
156 fn write_canonical_json(value
: &Value
, output
: &mut Vec
<u8>) -> Result
<(), Error
> {
158 Value
::Null
=> bail
!("got unexpected null value"),
159 Value
::String(_
) | Value
::Number(_
) | Value
::Bool(_
) => {
160 serde_json
::to_writer(output
, &value
)?
;
162 Value
::Array(list
) => {
164 let mut iter
= list
.iter();
165 if let Some(item
) = iter
.next() {
166 Self::write_canonical_json(item
, output
)?
;
169 Self::write_canonical_json(item
, output
)?
;
174 Value
::Object(map
) => {
176 let mut keys
: Vec
<&str> = map
.keys().map(String
::as_str
).collect();
178 let mut iter
= keys
.into_iter();
179 if let Some(key
) = iter
.next() {
180 serde_json
::to_writer(&mut *output
, &key
)?
;
182 Self::write_canonical_json(&map
[key
], output
)?
;
185 serde_json
::to_writer(&mut *output
, &key
)?
;
187 Self::write_canonical_json(&map
[key
], output
)?
;
196 /// Compute manifest signature
198 /// By generating a HMAC SHA256 over the canonical json
199 /// representation, The 'unpreotected' property is excluded.
200 pub fn signature(&self, crypt_config
: &CryptConfig
) -> Result
<[u8; 32], Error
> {
201 Self::json_signature(&serde_json
::to_value(&self)?
, crypt_config
)
204 fn json_signature(data
: &Value
, crypt_config
: &CryptConfig
) -> Result
<[u8; 32], Error
> {
206 let mut signed_data
= data
.clone();
208 signed_data
.as_object_mut().unwrap().remove("unprotected"); // exclude
209 signed_data
.as_object_mut().unwrap().remove("signature"); // exclude
211 let canonical
= Self::to_canonical_json(&signed_data
)?
;
213 let sig
= crypt_config
.compute_auth_tag(&canonical
);
218 /// Converts the Manifest into json string, and add a signature if there is a crypt_config.
219 pub fn to_string(&self, crypt_config
: Option
<&CryptConfig
>) -> Result
<String
, Error
> {
221 let mut manifest
= serde_json
::to_value(&self)?
;
223 if let Some(crypt_config
) = crypt_config
{
224 let sig
= self.signature(crypt_config
)?
;
225 manifest
["signature"] = proxmox
::tools
::digest_to_hex(&sig
).into();
228 let manifest
= serde_json
::to_string_pretty(&manifest
).unwrap().into();
232 /// Try to read the manifest. This verifies the signature if there is a crypt_config.
233 pub fn from_data(data
: &[u8], crypt_config
: Option
<&CryptConfig
>) -> Result
<BackupManifest
, Error
> {
234 let json
: Value
= serde_json
::from_slice(data
)?
;
235 let signature
= json
["signature"].as_str().map(String
::from
);
237 if let Some(ref crypt_config
) = crypt_config
{
238 if let Some(signature
) = signature
{
239 let expected_signature
= proxmox
::tools
::digest_to_hex(&Self::json_signature(&json
, crypt_config
)?
);
240 if signature
!= expected_signature
{
241 bail
!("wrong signature in manifest");
244 // not signed: warn/fail?
248 let manifest
: BackupManifest
= serde_json
::from_value(json
)?
;
254 impl TryFrom
<super::DataBlob
> for BackupManifest
{
257 fn try_from(blob
: super::DataBlob
) -> Result
<Self, Error
> {
258 // no expected digest available
259 let data
= blob
.decode(None
, None
)
260 .map_err(|err
| format_err
!("decode backup manifest blob failed - {}", err
))?
;
261 let json
: Value
= serde_json
::from_slice(&data
[..])
262 .map_err(|err
| format_err
!("unable to parse backup manifest json - {}", err
))?
;
263 let manifest
: BackupManifest
= serde_json
::from_value(json
)?
;
270 fn test_manifest_signature() -> Result
<(), Error
> {
272 use crate::backup
::{KeyDerivationConfig}
;
276 let kdf
= KeyDerivationConfig
::Scrypt
{
283 let testkey
= kdf
.derive_key(pw
)?
;
285 let crypt_config
= CryptConfig
::new(testkey
)?
;
287 let snapshot
: BackupDir
= "host/elsa/2020-06-26T13:56:05Z".parse()?
;
289 let mut manifest
= BackupManifest
::new(snapshot
);
291 manifest
.add_file("test1.img.fidx".into(), 200, [1u8; 32], CryptMode
::Encrypt
)?
;
292 manifest
.add_file("abc.blob".into(), 200, [2u8; 32], CryptMode
::None
)?
;
294 manifest
.unprotected
["note"] = "This is not protected by the signature.".into();
296 let text
= manifest
.to_string(Some(&crypt_config
))?
;
298 let manifest
: Value
= serde_json
::from_str(&text
)?
;
299 let signature
= manifest
["signature"].as_str().unwrap().to_string();
301 assert_eq
!(signature
, "d7b446fb7db081662081d4b40fedd858a1d6307a5aff4ecff7d5bf4fd35679e9");
303 let manifest
: BackupManifest
= serde_json
::from_value(manifest
)?
;
304 let expected_signature
= proxmox
::tools
::digest_to_hex(&manifest
.signature(&crypt_config
)?
);
306 assert_eq
!(signature
, expected_signature
);