1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! XAR XML table of contents data structure.

use {
    crate::XarResult,
    chrono::{DateTime, Utc},
    serde::{Deserialize, Serialize},
    std::{
        io::Read,
        ops::{Deref, DerefMut},
    },
    x509_certificate::{CapturedX509Certificate, X509CertificateError},
};

/// An XML table of contents in a XAR file.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TableOfContents {
    toc: XarToC,
}

impl Deref for TableOfContents {
    type Target = XarToC;

    fn deref(&self) -> &Self::Target {
        &self.toc
    }
}

impl DerefMut for TableOfContents {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.toc
    }
}

impl TableOfContents {
    /// Parse XML table of contents from a reader.
    pub fn from_reader(reader: impl Read) -> XarResult<Self> {
        Ok(serde_xml_rs::from_reader(reader)?)
    }

    /// Resolve the complete list of files.
    ///
    /// Files are sorted by their numerical ID, which should hopefully also
    /// be the order that file data occurs in the heap. Each elements consists of
    /// the full filename and the <file> record.
    pub fn files(&self) -> Vec<(String, File)> {
        let mut files = self
            .toc
            .files
            .iter()
            .flat_map(|f| f.files(None))
            .collect::<Vec<_>>();

        files.sort_by(|a, b| a.1.id.cmp(&b.1.id));

        files
    }
}

/// The main data structure inside a table of contents.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct XarToC {
    pub creation_time: String,
    pub checksum: Checksum,
    #[serde(rename = "file")]
    pub files: Vec<File>,
    pub signature: Option<Signature>,
    pub x_signature: Option<Signature>,
}

impl XarToC {
    /// Signatures present in the table of contents.
    pub fn signatures(&self) -> Vec<&Signature> {
        let mut res = vec![];
        if let Some(sig) = &self.signature {
            res.push(sig);
        }
        if let Some(sig) = &self.x_signature {
            res.push(sig);
        }

        res
    }

    /// Attempt to find a signature given a signature style.
    pub fn find_signature(&self, style: SignatureStyle) -> Option<&Signature> {
        self.signatures().into_iter().find(|sig| sig.style == style)
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Checksum {
    /// The digest format used.
    pub style: ChecksumType,

    /// Offset within heap of the checksum data.
    pub offset: u64,

    /// Size of checksum data.
    pub size: u64,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ChecksumType {
    None,
    Sha1,
    Sha256,
    Sha512,
    Md5,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct File {
    pub id: u64,
    pub ctime: Option<DateTime<Utc>>,
    pub mtime: Option<DateTime<Utc>>,
    pub atime: Option<DateTime<Utc>>,
    pub name: String,
    #[serde(rename = "type")]
    pub file_type: FileType,
    pub mode: Option<u32>,
    pub deviceno: Option<u32>,
    pub inode: Option<u64>,
    pub uid: Option<u32>,
    pub gid: Option<u32>,
    pub user: Option<String>,
    pub group: Option<String>,
    pub size: Option<u64>,
    pub data: Option<FileData>,
    pub ea: Option<Ea>,
    #[serde(rename = "FinderCreateTime")]
    pub finder_create_time: Option<FinderCreateTime>,
    #[serde(default, rename = "file")]
    pub files: Vec<File>,
}

impl File {
    pub fn files(&self, directory: Option<&str>) -> Vec<(String, File)> {
        let full_path = if let Some(d) = directory {
            format!("{}/{}", d, self.name)
        } else {
            self.name.clone()
        };

        let mut files = vec![(full_path.clone(), self.clone())];

        for f in &self.files {
            files.extend(f.files(Some(&full_path)));
        }

        files
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FileType {
    File,
    Directory,
    HardLink,
    Link,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct FileData {
    pub offset: u64,
    pub size: u64,
    pub length: u64,
    pub extracted_checksum: FileChecksum,
    pub archived_checksum: FileChecksum,
    pub encoding: FileEncoding,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileChecksum {
    pub style: ChecksumType,
    #[serde(rename = "$value")]
    pub checksum: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileEncoding {
    pub style: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Ea {
    pub name: String,
    pub offset: u64,
    pub size: u64,
    pub length: u64,
    pub extracted_checksum: FileChecksum,
    pub archived_checksum: FileChecksum,
    pub encoding: FileEncoding,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FinderCreateTime {
    pub nanoseconds: u64,
    pub time: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Signature {
    pub style: SignatureStyle,
    pub offset: u64,
    pub size: u64,
    #[serde(rename = "KeyInfo")]
    pub key_info: KeyInfo,
}

impl Signature {
    /// Obtained parsed X.509 certificates.
    pub fn x509_certificates(&self) -> XarResult<Vec<CapturedX509Certificate>> {
        self.key_info.x509_certificates()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SignatureStyle {
    /// Cryptographic message syntax.
    Cms,

    /// RSA signature.
    Rsa,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct KeyInfo {
    #[serde(rename = "X509Data")]
    pub x509_data: X509Data,
}

impl KeyInfo {
    /// Obtain parsed X.509 certificates.
    pub fn x509_certificates(&self) -> XarResult<Vec<CapturedX509Certificate>> {
        self.x509_data.x509_certificates()
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct X509Data {
    #[serde(rename = "X509Certificate")]
    pub x509_certificate: Vec<String>,
}

impl X509Data {
    /// Obtain parsed X.509 certificates.
    pub fn x509_certificates(&self) -> XarResult<Vec<CapturedX509Certificate>> {
        Ok(self
            .x509_certificate
            .iter()
            .map(|data| {
                // The data in the XML isn't armored. So we add armoring so it can
                // be decoded by the pem crate.
                let data = format!(
                    "-----BEGIN CERTIFICATE-----\r\n{}\r\n-----END CERTIFICATE-----\r\n",
                    data
                );

                CapturedX509Certificate::from_pem(data)
            })
            .collect::<Result<Vec<_>, X509CertificateError>>()?)
    }
}