Struct apple_xar::reader::XarReader

source ·
pub struct XarReader<R: Read + Seek + Sized + Debug> { /* private fields */ }
Expand description

Read-only interface to a single XAR archive.

Implementations§

Construct a new XAR reader from a stream reader.

Obtain the inner reader.

Obtain the parsed XarHeader file header.

Examples found in repository?
src/signing.rs (line 193)
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
    pub fn sign<W: Write>(
        &mut self,
        writer: &mut W,
        signing_key: &dyn KeyInfoSigner,
        signing_cert: &CapturedX509Certificate,
        time_stamp_url: Option<&Url>,
        certificates: impl Iterator<Item = CapturedX509Certificate>,
    ) -> XarResult<()> {
        let extra_certificates = certificates.collect::<Vec<_>>();

        // Base64 encoding of all public certificates.
        let chain = std::iter::once(signing_cert)
            .chain(extra_certificates.iter())
            .collect::<Vec<_>>();

        // Sending the same content to the Time-Stamp Server on every invocation might
        // raise suspicions. So randomize the input and thus the digest.
        let mut random = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut random);
        let empty_digest = self.checksum_type.digest_data(&random)?;
        let digest_size = empty_digest.len() as u64;

        info!("performing empty RSA signature to calculate signature length");
        let rsa_signature_len = signing_key.try_sign(&empty_digest)?.as_ref().len();

        info!("performing empty CMS signature to calculate data length");
        let signer =
            SignerBuilder::new(signing_key, signing_cert.clone()).message_id_content(empty_digest);

        let signer = if let Some(time_stamp_url) = time_stamp_url {
            info!("using time-stamp server {}", time_stamp_url);
            signer.time_stamp_url(time_stamp_url.clone())?
        } else {
            signer
        };

        let cms_signature_len = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.clone())
            .certificates(extra_certificates.iter().cloned())
            .build_der()?
            .len();

        // Pad it a little because CMS signatures are variable size.
        let cms_signature_len = cms_signature_len + 512;

        // Now build up a new table of contents to sign.
        let mut toc = self.reader.table_of_contents().clone();
        toc.checksum = Checksum {
            style: self.checksum_type,
            offset: 0,
            size: digest_size,
        };

        let rsa_signature = Signature {
            style: SignatureStyle::Rsa,
            // The RSA signature goes right after the digest data.
            offset: digest_size,
            size: rsa_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let cms_signature = Signature {
            style: SignatureStyle::Cms,
            // The CMS signature goes right after the RSA signature.
            offset: rsa_signature.offset + rsa_signature.size,
            size: cms_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let mut current_offset = cms_signature.offset + cms_signature.size;

        toc.signature = Some(rsa_signature);
        toc.x_signature = Some(cms_signature);

        // Now go through and update file offsets. Files are nested. So we do a pass up
        // front to calculate all the offsets then we recursively descend and update all
        // references.
        let mut ids_to_offsets = HashMap::new();

        for (_, file) in self.reader.files()? {
            if let Some(data) = &file.data {
                ids_to_offsets.insert(file.id, current_offset);
                current_offset += data.length;
            }
        }

        toc.visit_files_mut(&|file: &mut File| {
            if let Some(data) = &mut file.data {
                data.offset = *ids_to_offsets
                    .get(&file.id)
                    .expect("file should have offset recorded");
            }
        });

        // The TOC should be all set up now. Let's serialize it so we can produce
        // a valid signature.
        warn!("generating new XAR table of contents XML");
        let toc_data = toc.to_xml()?;
        info!("table of contents size: {}", toc_data.len());

        let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
        zlib.write_all(&toc_data)?;
        let toc_compressed = zlib.finish()?;

        let toc_digest = self.checksum_type.digest_data(&toc_compressed)?;

        // Sign it for real.
        let rsa_signature = signing_key.try_sign(&toc_digest)?;

        let mut cms_signature = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.message_id_content(toc_digest.clone()))
            .certificates(extra_certificates.iter().cloned())
            .build_der()?;

        match cms_signature.len().cmp(&cms_signature_len) {
            Ordering::Greater => {
                error!("real CMS signature overflowed allocated space for signature (please report this bug)");
                return Err(Error::Unsupported("CMS signature overflow"));
            }
            Ordering::Equal => {}
            Ordering::Less => {
                cms_signature
                    .extend_from_slice(&b"\0".repeat(cms_signature_len - cms_signature.len()));
            }
        }

        // Now let's write everything out.
        let mut header = *self.reader.header();
        header.checksum_algorithm_id = XarChecksum::from(self.checksum_type).into();
        header.toc_length_compressed = toc_compressed.len() as _;
        header.toc_length_uncompressed = toc_data.len() as _;

        writer.iowrite_with(header, scroll::BE)?;
        writer.write_all(&toc_compressed)?;
        writer.write_all(&toc_digest)?;
        writer.write_all(rsa_signature.as_ref())?;
        writer.write_all(&cms_signature)?;

        // And write all the files to the heap.
        for (path, file) in self.reader.files()? {
            if file.data.is_some() {
                info!("copying {} to output XAR", path);
                self.reader.write_file_data_heap_from_file(&file, writer)?;
            }
        }

        Ok(())
    }

The start offset of the heap.

Obtain the table of contents for this archive.

Examples found in repository?
src/signing.rs (line 50)
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
    pub fn new(reader: XarReader<R>) -> Self {
        let checksum_type = reader.table_of_contents().checksum.style;

        Self {
            reader,
            checksum_type,
        }
    }

    /// Sign a XAR file using signing parameters.
    ///
    /// The `signing_key` and `signing_cert` form the certificate to use for signing.
    /// `time_stamp_url` is an optional Time-Stamp Protocol server URL to use for the CMS
    /// signature.
    /// `certificates` is an iterable of X.509 certificates to attach to the signature.
    pub fn sign<W: Write>(
        &mut self,
        writer: &mut W,
        signing_key: &dyn KeyInfoSigner,
        signing_cert: &CapturedX509Certificate,
        time_stamp_url: Option<&Url>,
        certificates: impl Iterator<Item = CapturedX509Certificate>,
    ) -> XarResult<()> {
        let extra_certificates = certificates.collect::<Vec<_>>();

        // Base64 encoding of all public certificates.
        let chain = std::iter::once(signing_cert)
            .chain(extra_certificates.iter())
            .collect::<Vec<_>>();

        // Sending the same content to the Time-Stamp Server on every invocation might
        // raise suspicions. So randomize the input and thus the digest.
        let mut random = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut random);
        let empty_digest = self.checksum_type.digest_data(&random)?;
        let digest_size = empty_digest.len() as u64;

        info!("performing empty RSA signature to calculate signature length");
        let rsa_signature_len = signing_key.try_sign(&empty_digest)?.as_ref().len();

        info!("performing empty CMS signature to calculate data length");
        let signer =
            SignerBuilder::new(signing_key, signing_cert.clone()).message_id_content(empty_digest);

        let signer = if let Some(time_stamp_url) = time_stamp_url {
            info!("using time-stamp server {}", time_stamp_url);
            signer.time_stamp_url(time_stamp_url.clone())?
        } else {
            signer
        };

        let cms_signature_len = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.clone())
            .certificates(extra_certificates.iter().cloned())
            .build_der()?
            .len();

        // Pad it a little because CMS signatures are variable size.
        let cms_signature_len = cms_signature_len + 512;

        // Now build up a new table of contents to sign.
        let mut toc = self.reader.table_of_contents().clone();
        toc.checksum = Checksum {
            style: self.checksum_type,
            offset: 0,
            size: digest_size,
        };

        let rsa_signature = Signature {
            style: SignatureStyle::Rsa,
            // The RSA signature goes right after the digest data.
            offset: digest_size,
            size: rsa_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let cms_signature = Signature {
            style: SignatureStyle::Cms,
            // The CMS signature goes right after the RSA signature.
            offset: rsa_signature.offset + rsa_signature.size,
            size: cms_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let mut current_offset = cms_signature.offset + cms_signature.size;

        toc.signature = Some(rsa_signature);
        toc.x_signature = Some(cms_signature);

        // Now go through and update file offsets. Files are nested. So we do a pass up
        // front to calculate all the offsets then we recursively descend and update all
        // references.
        let mut ids_to_offsets = HashMap::new();

        for (_, file) in self.reader.files()? {
            if let Some(data) = &file.data {
                ids_to_offsets.insert(file.id, current_offset);
                current_offset += data.length;
            }
        }

        toc.visit_files_mut(&|file: &mut File| {
            if let Some(data) = &mut file.data {
                data.offset = *ids_to_offsets
                    .get(&file.id)
                    .expect("file should have offset recorded");
            }
        });

        // The TOC should be all set up now. Let's serialize it so we can produce
        // a valid signature.
        warn!("generating new XAR table of contents XML");
        let toc_data = toc.to_xml()?;
        info!("table of contents size: {}", toc_data.len());

        let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
        zlib.write_all(&toc_data)?;
        let toc_compressed = zlib.finish()?;

        let toc_digest = self.checksum_type.digest_data(&toc_compressed)?;

        // Sign it for real.
        let rsa_signature = signing_key.try_sign(&toc_digest)?;

        let mut cms_signature = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.message_id_content(toc_digest.clone()))
            .certificates(extra_certificates.iter().cloned())
            .build_der()?;

        match cms_signature.len().cmp(&cms_signature_len) {
            Ordering::Greater => {
                error!("real CMS signature overflowed allocated space for signature (please report this bug)");
                return Err(Error::Unsupported("CMS signature overflow"));
            }
            Ordering::Equal => {}
            Ordering::Less => {
                cms_signature
                    .extend_from_slice(&b"\0".repeat(cms_signature_len - cms_signature.len()));
            }
        }

        // Now let's write everything out.
        let mut header = *self.reader.header();
        header.checksum_algorithm_id = XarChecksum::from(self.checksum_type).into();
        header.toc_length_compressed = toc_compressed.len() as _;
        header.toc_length_uncompressed = toc_data.len() as _;

        writer.iowrite_with(header, scroll::BE)?;
        writer.write_all(&toc_compressed)?;
        writer.write_all(&toc_digest)?;
        writer.write_all(rsa_signature.as_ref())?;
        writer.write_all(&cms_signature)?;

        // And write all the files to the heap.
        for (path, file) in self.reader.files()? {
            if file.data.is_some() {
                info!("copying {} to output XAR", path);
                self.reader.write_file_data_heap_from_file(&file, writer)?;
            }
        }

        Ok(())
    }

Obtain the decoded content of the table of contents.

Obtain the raw bytes holding the checksum.

Digest the table of contents content with the specified algorithm.

Examples found in repository?
src/reader.rs (line 320)
318
319
320
321
322
323
324
    pub fn verify_table_of_contents_checksum(&mut self) -> XarResult<bool> {
        let format = ChecksumType::try_from(XarChecksum::from(self.header.checksum_algorithm_id))?;
        let actual_digest = self.digest_table_of_contents_with(format)?;
        let recorded_digest = self.checksum()?.1;

        Ok(actual_digest == recorded_digest)
    }

Obtain the file entries in this archive.

Examples found in repository?
src/signing.rs (line 144)
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
    pub fn sign<W: Write>(
        &mut self,
        writer: &mut W,
        signing_key: &dyn KeyInfoSigner,
        signing_cert: &CapturedX509Certificate,
        time_stamp_url: Option<&Url>,
        certificates: impl Iterator<Item = CapturedX509Certificate>,
    ) -> XarResult<()> {
        let extra_certificates = certificates.collect::<Vec<_>>();

        // Base64 encoding of all public certificates.
        let chain = std::iter::once(signing_cert)
            .chain(extra_certificates.iter())
            .collect::<Vec<_>>();

        // Sending the same content to the Time-Stamp Server on every invocation might
        // raise suspicions. So randomize the input and thus the digest.
        let mut random = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut random);
        let empty_digest = self.checksum_type.digest_data(&random)?;
        let digest_size = empty_digest.len() as u64;

        info!("performing empty RSA signature to calculate signature length");
        let rsa_signature_len = signing_key.try_sign(&empty_digest)?.as_ref().len();

        info!("performing empty CMS signature to calculate data length");
        let signer =
            SignerBuilder::new(signing_key, signing_cert.clone()).message_id_content(empty_digest);

        let signer = if let Some(time_stamp_url) = time_stamp_url {
            info!("using time-stamp server {}", time_stamp_url);
            signer.time_stamp_url(time_stamp_url.clone())?
        } else {
            signer
        };

        let cms_signature_len = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.clone())
            .certificates(extra_certificates.iter().cloned())
            .build_der()?
            .len();

        // Pad it a little because CMS signatures are variable size.
        let cms_signature_len = cms_signature_len + 512;

        // Now build up a new table of contents to sign.
        let mut toc = self.reader.table_of_contents().clone();
        toc.checksum = Checksum {
            style: self.checksum_type,
            offset: 0,
            size: digest_size,
        };

        let rsa_signature = Signature {
            style: SignatureStyle::Rsa,
            // The RSA signature goes right after the digest data.
            offset: digest_size,
            size: rsa_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let cms_signature = Signature {
            style: SignatureStyle::Cms,
            // The CMS signature goes right after the RSA signature.
            offset: rsa_signature.offset + rsa_signature.size,
            size: cms_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let mut current_offset = cms_signature.offset + cms_signature.size;

        toc.signature = Some(rsa_signature);
        toc.x_signature = Some(cms_signature);

        // Now go through and update file offsets. Files are nested. So we do a pass up
        // front to calculate all the offsets then we recursively descend and update all
        // references.
        let mut ids_to_offsets = HashMap::new();

        for (_, file) in self.reader.files()? {
            if let Some(data) = &file.data {
                ids_to_offsets.insert(file.id, current_offset);
                current_offset += data.length;
            }
        }

        toc.visit_files_mut(&|file: &mut File| {
            if let Some(data) = &mut file.data {
                data.offset = *ids_to_offsets
                    .get(&file.id)
                    .expect("file should have offset recorded");
            }
        });

        // The TOC should be all set up now. Let's serialize it so we can produce
        // a valid signature.
        warn!("generating new XAR table of contents XML");
        let toc_data = toc.to_xml()?;
        info!("table of contents size: {}", toc_data.len());

        let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
        zlib.write_all(&toc_data)?;
        let toc_compressed = zlib.finish()?;

        let toc_digest = self.checksum_type.digest_data(&toc_compressed)?;

        // Sign it for real.
        let rsa_signature = signing_key.try_sign(&toc_digest)?;

        let mut cms_signature = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.message_id_content(toc_digest.clone()))
            .certificates(extra_certificates.iter().cloned())
            .build_der()?;

        match cms_signature.len().cmp(&cms_signature_len) {
            Ordering::Greater => {
                error!("real CMS signature overflowed allocated space for signature (please report this bug)");
                return Err(Error::Unsupported("CMS signature overflow"));
            }
            Ordering::Equal => {}
            Ordering::Less => {
                cms_signature
                    .extend_from_slice(&b"\0".repeat(cms_signature_len - cms_signature.len()));
            }
        }

        // Now let's write everything out.
        let mut header = *self.reader.header();
        header.checksum_algorithm_id = XarChecksum::from(self.checksum_type).into();
        header.toc_length_compressed = toc_compressed.len() as _;
        header.toc_length_uncompressed = toc_data.len() as _;

        writer.iowrite_with(header, scroll::BE)?;
        writer.write_all(&toc_compressed)?;
        writer.write_all(&toc_digest)?;
        writer.write_all(rsa_signature.as_ref())?;
        writer.write_all(&cms_signature)?;

        // And write all the files to the heap.
        for (path, file) in self.reader.files()? {
            if file.data.is_some() {
                info!("copying {} to output XAR", path);
                self.reader.write_file_data_heap_from_file(&file, writer)?;
            }
        }

        Ok(())
    }

Attempt to find the File entry for a given path in the archive.

Examples found in repository?
src/reader.rs (line 267)
266
267
268
269
270
271
272
273
274
275
    pub fn get_file_data_from_path(&mut self, path: &str) -> XarResult<Option<Vec<u8>>> {
        if let Some(file) = self.find_file(path)? {
            let mut buffer = Vec::<u8>::with_capacity(file.size.unwrap_or(0) as _);
            self.write_file_data_decoded_from_file(&file, &mut buffer)?;

            Ok(Some(buffer))
        } else {
            Ok(None)
        }
    }

Write heap file data for a given file record to a writer.

This will write the raw data backing a file as stored in the heap. There’s a good chance the raw data is encoded/compressed.

Returns the number of bytes written.

Examples found in repository?
src/reader.rs (line 213)
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
    pub fn write_file_data_heap_from_id(
        &mut self,
        id: u64,
        writer: &mut impl Write,
    ) -> XarResult<usize> {
        let file = self
            .toc
            .files()?
            .into_iter()
            .find(|(_, f)| f.id == id)
            .ok_or(Error::InvalidFileId)?
            .1;

        self.write_file_data_heap_from_file(&file, writer)
    }

    /// Write decoded file data for a given file record to a writer.
    ///
    /// This will call [Self::write_file_data_heap_from_file] and will decode
    /// that data stream, if the file data is encoded.
    pub fn write_file_data_decoded_from_file(
        &mut self,
        file: &File,
        writer: &mut impl Write,
    ) -> XarResult<usize> {
        let data = file.data.as_ref().ok_or(Error::FileNoData)?;

        let mut writer = match data.encoding.style.as_str() {
            "application/octet-stream" => Box::new(writer) as Box<dyn Write>,
            "application/x-bzip2" => {
                Box::new(bzip2::write::BzDecoder::new(writer)) as Box<dyn Write>
            }
            // The media type is arguably wrong, as there is no gzip header.
            "application/x-gzip" => {
                Box::new(flate2::write::ZlibDecoder::new(writer)) as Box<dyn Write>
            }
            "application/x-lzma" => Box::new(xz2::write::XzDecoder::new(writer)) as Box<dyn Write>,
            encoding => {
                return Err(Error::UnimplementedFileEncoding(encoding.to_string()));
            }
        };

        self.write_file_data_heap_from_file(file, &mut writer)
    }
More examples
Hide additional examples
src/signing.rs (line 208)
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
    pub fn sign<W: Write>(
        &mut self,
        writer: &mut W,
        signing_key: &dyn KeyInfoSigner,
        signing_cert: &CapturedX509Certificate,
        time_stamp_url: Option<&Url>,
        certificates: impl Iterator<Item = CapturedX509Certificate>,
    ) -> XarResult<()> {
        let extra_certificates = certificates.collect::<Vec<_>>();

        // Base64 encoding of all public certificates.
        let chain = std::iter::once(signing_cert)
            .chain(extra_certificates.iter())
            .collect::<Vec<_>>();

        // Sending the same content to the Time-Stamp Server on every invocation might
        // raise suspicions. So randomize the input and thus the digest.
        let mut random = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut random);
        let empty_digest = self.checksum_type.digest_data(&random)?;
        let digest_size = empty_digest.len() as u64;

        info!("performing empty RSA signature to calculate signature length");
        let rsa_signature_len = signing_key.try_sign(&empty_digest)?.as_ref().len();

        info!("performing empty CMS signature to calculate data length");
        let signer =
            SignerBuilder::new(signing_key, signing_cert.clone()).message_id_content(empty_digest);

        let signer = if let Some(time_stamp_url) = time_stamp_url {
            info!("using time-stamp server {}", time_stamp_url);
            signer.time_stamp_url(time_stamp_url.clone())?
        } else {
            signer
        };

        let cms_signature_len = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.clone())
            .certificates(extra_certificates.iter().cloned())
            .build_der()?
            .len();

        // Pad it a little because CMS signatures are variable size.
        let cms_signature_len = cms_signature_len + 512;

        // Now build up a new table of contents to sign.
        let mut toc = self.reader.table_of_contents().clone();
        toc.checksum = Checksum {
            style: self.checksum_type,
            offset: 0,
            size: digest_size,
        };

        let rsa_signature = Signature {
            style: SignatureStyle::Rsa,
            // The RSA signature goes right after the digest data.
            offset: digest_size,
            size: rsa_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let cms_signature = Signature {
            style: SignatureStyle::Cms,
            // The CMS signature goes right after the RSA signature.
            offset: rsa_signature.offset + rsa_signature.size,
            size: cms_signature_len as _,
            key_info: KeyInfo::from_certificates(chain.iter().copied())?,
        };

        let mut current_offset = cms_signature.offset + cms_signature.size;

        toc.signature = Some(rsa_signature);
        toc.x_signature = Some(cms_signature);

        // Now go through and update file offsets. Files are nested. So we do a pass up
        // front to calculate all the offsets then we recursively descend and update all
        // references.
        let mut ids_to_offsets = HashMap::new();

        for (_, file) in self.reader.files()? {
            if let Some(data) = &file.data {
                ids_to_offsets.insert(file.id, current_offset);
                current_offset += data.length;
            }
        }

        toc.visit_files_mut(&|file: &mut File| {
            if let Some(data) = &mut file.data {
                data.offset = *ids_to_offsets
                    .get(&file.id)
                    .expect("file should have offset recorded");
            }
        });

        // The TOC should be all set up now. Let's serialize it so we can produce
        // a valid signature.
        warn!("generating new XAR table of contents XML");
        let toc_data = toc.to_xml()?;
        info!("table of contents size: {}", toc_data.len());

        let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
        zlib.write_all(&toc_data)?;
        let toc_compressed = zlib.finish()?;

        let toc_digest = self.checksum_type.digest_data(&toc_compressed)?;

        // Sign it for real.
        let rsa_signature = signing_key.try_sign(&toc_digest)?;

        let mut cms_signature = SignedDataBuilder::default()
            .content_type(Oid(OID_ID_DATA.as_ref().into()))
            .signer(signer.message_id_content(toc_digest.clone()))
            .certificates(extra_certificates.iter().cloned())
            .build_der()?;

        match cms_signature.len().cmp(&cms_signature_len) {
            Ordering::Greater => {
                error!("real CMS signature overflowed allocated space for signature (please report this bug)");
                return Err(Error::Unsupported("CMS signature overflow"));
            }
            Ordering::Equal => {}
            Ordering::Less => {
                cms_signature
                    .extend_from_slice(&b"\0".repeat(cms_signature_len - cms_signature.len()));
            }
        }

        // Now let's write everything out.
        let mut header = *self.reader.header();
        header.checksum_algorithm_id = XarChecksum::from(self.checksum_type).into();
        header.toc_length_compressed = toc_compressed.len() as _;
        header.toc_length_uncompressed = toc_data.len() as _;

        writer.iowrite_with(header, scroll::BE)?;
        writer.write_all(&toc_compressed)?;
        writer.write_all(&toc_digest)?;
        writer.write_all(rsa_signature.as_ref())?;
        writer.write_all(&cms_signature)?;

        // And write all the files to the heap.
        for (path, file) in self.reader.files()? {
            if file.data.is_some() {
                info!("copying {} to output XAR", path);
                self.reader.write_file_data_heap_from_file(&file, writer)?;
            }
        }

        Ok(())
    }

Write heap file data for a given file ID to a writer.

This is a wrapper around Self::write_file_data_heap_from_file that resolves the File given a file ID.

Write decoded file data for a given file record to a writer.

This will call Self::write_file_data_heap_from_file and will decode that data stream, if the file data is encoded.

Examples found in repository?
src/reader.rs (line 262)
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    pub fn write_file_data_decoded_from_id(
        &mut self,
        id: u64,
        writer: &mut impl Write,
    ) -> XarResult<usize> {
        let file = self
            .toc
            .files()?
            .into_iter()
            .find(|(_, f)| f.id == id)
            .ok_or(Error::InvalidFileId)?
            .1;

        self.write_file_data_decoded_from_file(&file, writer)
    }

    /// Resolve data for a given path.
    pub fn get_file_data_from_path(&mut self, path: &str) -> XarResult<Option<Vec<u8>>> {
        if let Some(file) = self.find_file(path)? {
            let mut buffer = Vec::<u8>::with_capacity(file.size.unwrap_or(0) as _);
            self.write_file_data_decoded_from_file(&file, &mut buffer)?;

            Ok(Some(buffer))
        } else {
            Ok(None)
        }
    }

    /// Unpack the contents of the XAR archive to a given directory.
    pub fn unpack(&mut self, dest_dir: impl AsRef<Path>) -> XarResult<()> {
        let dest_dir = dest_dir.as_ref();

        for (path, file) in self.toc.files()? {
            let dest_path = dest_dir.join(path);

            match file.file_type {
                FileType::Directory => {
                    std::fs::create_dir(&dest_path)?;
                }
                FileType::File => {
                    let mut fh = std::fs::File::create(&dest_path)?;
                    self.write_file_data_decoded_from_file(&file, &mut fh)?;
                }
                FileType::HardLink => return Err(Error::Unsupported("writing hard links")),
                FileType::Link => return Err(Error::Unsupported("writing symlinks")),
            }
        }

        Ok(())
    }

Write decoded file data for a given file ID to a writer.

This is a wrapper for Self::write_file_data_decoded_from_file that locates the File entry given a file ID.

Resolve data for a given path.

Unpack the contents of the XAR archive to a given directory.

Obtain the archive checksum.

The checksum consists of a digest format and a raw digest.

Examples found in repository?
src/reader.rs (line 321)
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    pub fn verify_table_of_contents_checksum(&mut self) -> XarResult<bool> {
        let format = ChecksumType::try_from(XarChecksum::from(self.header.checksum_algorithm_id))?;
        let actual_digest = self.digest_table_of_contents_with(format)?;
        let recorded_digest = self.checksum()?.1;

        Ok(actual_digest == recorded_digest)
    }

    /// Obtain RSA signature data from this archive.
    ///
    /// The returned tuple contains the raw signature data and the embedded X.509 certificates.
    pub fn rsa_signature(&mut self) -> XarResult<Option<(Vec<u8>, Vec<CapturedX509Certificate>)>> {
        if let Some(sig) = self.toc.find_signature(SignatureStyle::Rsa).cloned() {
            let mut data = Vec::<u8>::with_capacity(sig.size as _);
            self.write_heap_slice(sig.offset, sig.size as _, &mut data)?;

            let certs = sig.x509_certificates()?;

            Ok(Some((data, certs)))
        } else {
            Ok(None)
        }
    }

    /// Verifies the RSA signature in the archive.
    ///
    /// This verifies that the RSA signature in the archive, if present, is a valid signature
    /// for the archive's checksum data.
    ///
    /// The boolean return value indicates if signature validation was performed.
    pub fn verify_rsa_checksum_signature(&mut self) -> XarResult<bool> {
        let signed_data = self.checksum()?.1;

        if let Some((signature, certificates)) = self.rsa_signature()? {
            // The first certificate is the signing certificate.
            if let Some(cert) = certificates.get(0) {
                cert.verify_signed_data(signed_data, signature)?;
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    /// Attempt to resolve a cryptographic message syntax (CMS) signature.
    ///
    /// The data signed by the CMS signature is the raw data returned by [Self::checksum].
    pub fn cms_signature(&mut self) -> XarResult<Option<SignedData>> {
        if let Some(sig) = self.toc.find_signature(SignatureStyle::Cms).cloned() {
            let mut data = Vec::<u8>::with_capacity(sig.size as _);
            self.write_heap_slice(sig.offset, sig.size as _, &mut data)?;

            Ok(Some(SignedData::parse_ber(&data)?))
        } else {
            Ok(None)
        }
    }

    /// Verifies the cryptographic message syntax (CMS) signature, if present.
    pub fn verify_cms_signature(&mut self) -> XarResult<bool> {
        let checksum = self.checksum()?.1;
        let mut checked = false;

        if let Some(signed_data) = self.cms_signature()? {
            for signer in signed_data.signers() {
                signer.verify_signature_with_signed_data(&signed_data)?;
                signer.verify_message_digest_with_content(&checksum)?;
                checked = true;
            }
        }

        Ok(checked)
    }

Validate the recorded checksum of the table of contents matches actual file state.

Will Err if an error occurs obtaining or computing the checksums. Returns Ok with a bool indicating if the checksums matched.

Obtain RSA signature data from this archive.

The returned tuple contains the raw signature data and the embedded X.509 certificates.

Examples found in repository?
src/reader.rs (line 351)
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
    pub fn verify_rsa_checksum_signature(&mut self) -> XarResult<bool> {
        let signed_data = self.checksum()?.1;

        if let Some((signature, certificates)) = self.rsa_signature()? {
            // The first certificate is the signing certificate.
            if let Some(cert) = certificates.get(0) {
                cert.verify_signed_data(signed_data, signature)?;
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

Verifies the RSA signature in the archive.

This verifies that the RSA signature in the archive, if present, is a valid signature for the archive’s checksum data.

The boolean return value indicates if signature validation was performed.

Attempt to resolve a cryptographic message syntax (CMS) signature.

The data signed by the CMS signature is the raw data returned by Self::checksum.

Examples found in repository?
src/reader.rs (line 383)
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    pub fn verify_cms_signature(&mut self) -> XarResult<bool> {
        let checksum = self.checksum()?.1;
        let mut checked = false;

        if let Some(signed_data) = self.cms_signature()? {
            for signer in signed_data.signers() {
                signer.verify_signature_with_signed_data(&signed_data)?;
                signer.verify_message_digest_with_content(&checksum)?;
                checked = true;
            }
        }

        Ok(checked)
    }

Verifies the cryptographic message syntax (CMS) signature, if present.

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more