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 CLIENT_LOG_BLOB_NAME
: &str = "client.log.blob";
14 use serde
::{self, Deserialize, Serializer, Deserializer}
;
19 ) -> Result
<S
::Ok
, S
::Error
>
23 let s
= proxmox
::tools
::digest_to_hex(csum
);
24 serializer
.serialize_str(&s
)
27 pub fn deserialize
<'de
, D
>(
29 ) -> Result
<[u8; 32], D
::Error
>
33 let s
= String
::deserialize(deserializer
)?
;
34 proxmox
::tools
::hex_to_digest(&s
).map_err(serde
::de
::Error
::custom
)
38 #[derive(Serialize, Deserialize)]
39 #[serde(rename_all="kebab-case")]
42 pub crypt_mode
: CryptMode
,
44 #[serde(with = "hex_csum")]
48 #[derive(Serialize, Deserialize)]
49 #[serde(rename_all="kebab-case")]
50 pub struct BackupManifest
{
55 pub unprotected
: Value
,
59 pub enum ArchiveType
{
65 pub fn archive_type
<P
: AsRef
<Path
>>(
67 ) -> Result
<ArchiveType
, Error
> {
69 let archive_name
= archive_name
.as_ref();
70 let archive_type
= match archive_name
.extension().and_then(|ext
| ext
.to_str()) {
71 Some("didx") => ArchiveType
::DynamicIndex
,
72 Some("fidx") => ArchiveType
::FixedIndex
,
73 Some("blob") => ArchiveType
::Blob
,
74 _
=> bail
!("unknown archive type: {:?}", archive_name
),
82 pub fn new(snapshot
: BackupDir
) -> Self {
84 backup_type
: snapshot
.group().backup_type().into(),
85 backup_id
: snapshot
.group().backup_id().into(),
86 backup_time
: snapshot
.backup_time().timestamp(),
88 unprotected
: json
!({}
),
92 pub fn add_file(&mut self, filename
: String
, size
: u64, csum
: [u8; 32], crypt_mode
: CryptMode
) -> Result
<(), Error
> {
93 let _archive_type
= archive_type(&filename
)?
; // check type
94 self.files
.push(FileInfo { filename, size, csum, crypt_mode }
);
98 pub fn files(&self) -> &[FileInfo
] {
102 fn lookup_file_info(&self, name
: &str) -> Result
<&FileInfo
, Error
> {
104 let info
= self.files
.iter().find(|item
| item
.filename
== name
);
107 None
=> bail
!("manifest does not contain file '{}'", name
),
108 Some(info
) => Ok(info
),
112 pub fn verify_file(&self, name
: &str, csum
: &[u8; 32], size
: u64) -> Result
<(), Error
> {
114 let info
= self.lookup_file_info(name
)?
;
116 if size
!= info
.size
{
117 bail
!("wrong size for file '{}' ({} != {})", name
, info
.size
, size
);
120 if csum
!= &info
.csum
{
121 bail
!("wrong checksum for file '{}'", name
);
127 // Generate cannonical json
128 fn to_canonical_json(value
: &Value
, output
: &mut String
) -> Result
<(), Error
> {
130 Value
::Null
=> bail
!("got unexpected null value"),
131 Value
::String(_
) => {
132 output
.push_str(&serde_json
::to_string(value
)?
);
134 Value
::Number(_
) => {
135 output
.push_str(&serde_json
::to_string(value
)?
);
138 output
.push_str(&serde_json
::to_string(value
)?
);
140 Value
::Array(list
) => {
142 for (i
, item
) in list
.iter().enumerate() {
143 if i
!= 0 { output.push(','); }
144 Self::to_canonical_json(item
, output
)?
;
148 Value
::Object(map
) => {
150 let mut keys
: Vec
<String
> = map
.keys().map(|s
| s
.clone()).collect();
152 for (i
, key
) in keys
.iter().enumerate() {
153 let item
= map
.get(key
).unwrap();
154 if i
!= 0 { output.push(','); }
156 output
.push_str(&serde_json
::to_string(&Value
::String(key
.clone()))?
);
158 Self::to_canonical_json(item
, output
)?
;
166 /// Compute manifest signature
168 /// By generating a HMAC SHA256 over the canonical json
169 /// representation, The 'unpreotected' property is excluded.
170 pub fn signature(&self, crypt_config
: &CryptConfig
) -> Result
<[u8; 32], Error
> {
172 let mut signed_data
= serde_json
::to_value(&self)?
;
174 signed_data
.as_object_mut().unwrap().remove("unprotected"); // exclude
176 let mut canonical
= String
::new();
177 Self::to_canonical_json(&signed_data
, &mut canonical
)?
;
179 let sig
= crypt_config
.compute_auth_tag(canonical
.as_bytes());
184 /// Converts the Manifest into json string, and add a signature if there is a crypt_config.
185 pub fn into_string(self, crypt_config
: Option
<&CryptConfig
>) -> Result
<String
, Error
> {
187 let mut manifest
= serde_json
::to_value(&self)?
;
189 if let Some(crypt_config
) = crypt_config
{
190 let sig
= self.signature(crypt_config
)?
;
191 manifest
["signature"] = proxmox
::tools
::digest_to_hex(&sig
).into();
194 let manifest
= serde_json
::to_string_pretty(&manifest
).unwrap().into();
198 /// Try to read the manifest. This verifies the signature if there is a crypt_config.
199 pub fn from_data(data
: &[u8], crypt_config
: Option
<&CryptConfig
>) -> Result
<BackupManifest
, Error
> {
200 let json
: Value
= serde_json
::from_slice(data
)?
;
201 let signature
= json
["signature"].as_str().map(String
::from
);
202 let manifest
= BackupManifest
::try_from(json
)?
;
204 if let Some(ref crypt_config
) = crypt_config
{
205 if let Some(signature
) = signature
{
206 let expected_signature
= proxmox
::tools
::digest_to_hex(&manifest
.signature(crypt_config
)?
);
207 if signature
!= expected_signature
{
208 bail
!("wrong signature in manifest");
211 // not signed: warn/fail?
218 impl TryFrom
<super::DataBlob
> for BackupManifest
{
221 fn try_from(blob
: super::DataBlob
) -> Result
<Self, Error
> {
222 let data
= blob
.decode(None
)
223 .map_err(|err
| format_err
!("decode backup manifest blob failed - {}", err
))?
;
224 let json
: Value
= serde_json
::from_slice(&data
[..])
225 .map_err(|err
| format_err
!("unable to parse backup manifest json - {}", err
))?
;
226 BackupManifest
::try_from(json
)
230 impl TryFrom
<Value
> for BackupManifest
{
233 fn try_from(data
: Value
) -> Result
<Self, Error
> {
235 use crate::tools
::{required_string_property, required_integer_property, required_array_property}
;
237 proxmox
::try_block
!({
238 let backup_type
= required_string_property(&data
, "backup-type")?
;
239 let backup_id
= required_string_property(&data
, "backup-id")?
;
240 let backup_time
= required_integer_property(&data
, "backup-time")?
;
242 let snapshot
= BackupDir
::new(backup_type
, backup_id
, backup_time
);
244 let mut manifest
= BackupManifest
::new(snapshot
);
246 for item
in required_array_property(&data
, "files")?
.iter() {
247 let filename
= required_string_property(item
, "filename")?
.to_owned();
248 let csum
= required_string_property(item
, "csum")?
;
249 let csum
= proxmox
::tools
::hex_to_digest(csum
)?
;
250 let size
= required_integer_property(item
, "size")?
as u64;
252 let mut crypt_mode
= CryptMode
::None
;
254 if let Some(true) = item
["encrypted"].as_bool() { // compatible to < 0.8.0
255 crypt_mode
= CryptMode
::Encrypt
;
258 if let Some(mode
) = item
.get("crypt-mode") {
259 crypt_mode
= serde_json
::from_value(mode
.clone())?
;
262 manifest
.add_file(filename
, size
, csum
, crypt_mode
)?
;
265 if manifest
.files().is_empty() {
266 bail
!("manifest does not list any files.");
270 }).map_err(|err
: Error
| format_err
!("unable to parse backup manifest - {}", err
))
276 fn test_manifest_signature() -> Result
<(), Error
> {
278 use crate::backup
::{KeyDerivationConfig}
;
282 let kdf
= KeyDerivationConfig
::Scrypt
{
289 let testkey
= kdf
.derive_key(pw
)?
;
291 let crypt_config
= CryptConfig
::new(testkey
)?
;
293 let snapshot
: BackupDir
= "host/elsa/2020-06-26T13:56:05Z".parse()?
;
295 let mut manifest
= BackupManifest
::new(snapshot
);
297 manifest
.add_file("test1.img.fidx".into(), 200, [1u8; 32], CryptMode
::Encrypt
)?
;
298 manifest
.add_file("abc.blob".into(), 200, [2u8; 32], CryptMode
::None
)?
;
300 manifest
.unprotected
["note"] = "This is not protected by the signature.".into();
302 let text
= manifest
.into_string(Some(&crypt_config
))?
;
304 let manifest
: Value
= serde_json
::from_str(&text
)?
;
305 let signature
= manifest
["signature"].as_str().unwrap().to_string();
307 assert_eq
!(signature
, "d7b446fb7db081662081d4b40fedd858a1d6307a5aff4ecff7d5bf4fd35679e9");
309 let manifest
= BackupManifest
::try_from(manifest
)?
;
310 let expected_signature
= proxmox
::tools
::digest_to_hex(&manifest
.signature(&crypt_config
)?
);
312 assert_eq
!(signature
, expected_signature
);