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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use std::io::{self, BufRead, Read};
use bytes::{Buf, BytesMut};
use log::debug;
use super::PacketBodyReader;
use crate::{
composed::{Message, MessageReader, RingResult, TheRing},
errors::{bail, ensure_eq, Error, Result},
packet::{
OpsVersionSpecific, Packet, PacketTrait, Signature, SignatureType, SignatureVersionSpecific,
},
util::{fill_buffer_bytes, NormalizingHasher},
};
const BUFFER_SIZE: usize = 8 * 1024;
/// A signature packet before reading the full message
#[derive(Debug)]
pub enum SignaturePacket {
Ops {
signature: crate::packet::OnePassSignature,
},
Signature {
signature: Signature,
},
}
/// A signature packet after reading the full message
#[derive(Debug)]
pub enum FullSignaturePacket {
Ops {
ops: crate::packet::OnePassSignature,
signature: Signature,
},
Signature {
signature: Signature,
},
}
impl FullSignaturePacket {
pub fn signature(&self) -> &Signature {
match self {
Self::Ops { signature, .. } => signature,
Self::Signature { signature } => signature,
}
}
}
impl SignaturePacket {
fn new_hasher(&self) -> Result<Option<NormalizingHasher>> {
let hasher = match self {
Self::Ops { signature } => {
let mut hasher = signature.hash_algorithm().new_hasher().ok();
if let Some(ref mut hasher) = hasher {
if let OpsVersionSpecific::V6 { salt, .. } = signature.version_specific() {
// Salt size must match the expected length for the hash algorithm that is used
//
// See: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3-2.10.2.1.1
ensure_eq!(
signature.hash_algorithm().salt_len(),
Some(salt.len()),
"Illegal salt length {} for a V6 Signature using {:?}",
salt.len(),
signature.hash_algorithm(),
);
hasher.update(salt.as_ref());
}
}
hasher
}
Self::Signature { signature } => {
if let Some(config) = signature.config() {
let mut hasher = config.hash_alg.new_hasher()?;
if let SignatureVersionSpecific::V6 { ref salt, .. } = config.version_specific {
// Salt size must match the expected length for the hash algorithm that is used
//
// See: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2.3-2.10.2.1.1
ensure_eq!(
config.hash_alg.salt_len(),
Some(salt.len()),
"Illegal salt length {} for a V6 Signature using {:?}",
salt.len(),
config.hash_alg,
);
hasher.update(salt.as_ref());
}
Some(hasher)
} else {
None
}
}
};
let text_mode = match self {
Self::Ops { signature } => signature.typ() == SignatureType::Text,
Self::Signature { signature } => signature.typ() == Some(SignatureType::Text),
};
let hasher = hasher.map(|hasher| NormalizingHasher::new(hasher, text_mode));
Ok(hasher)
}
}
#[derive(derive_more::Debug)]
pub enum SignatureManyReader<'a> {
Init {
/// Signature packets
packets: Vec<SignaturePacket>,
/// Running hasher
hashers: Vec<Option<NormalizingHasher>>,
/// Data source
source: Box<Message<'a>>,
},
Body {
/// Signature packets
packets: Vec<SignaturePacket>,
/// Running hasher
hashers: Vec<Option<NormalizingHasher>>,
/// Data source
source: Box<Message<'a>>,
#[debug("{}", hex::encode(buffer))]
buffer: BytesMut,
},
Done {
/// Finalized hashes
hashes: Vec<Option<Box<[u8]>>>,
/// Data source
source: Box<Message<'a>>,
/// Final signatures
signatures: Vec<FullSignaturePacket>,
},
Error,
}
impl<'a> SignatureManyReader<'a> {
pub(crate) fn new(packets: Vec<SignaturePacket>, source: Box<Message<'a>>) -> Result<Self> {
let hashers = packets
.iter()
.map(|p| p.new_hasher())
.collect::<Result<Vec<_>>>()?;
Ok(Self::Init {
packets,
hashers,
source,
})
}
pub fn num_signatures(&self) -> usize {
match self {
Self::Init { packets, .. } => packets.len(),
Self::Body { packets, .. } => packets.len(),
Self::Done { hashes, .. } => hashes.len(),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn num_one_pass_signatures(&self) -> usize {
match self {
Self::Init { packets, .. } | Self::Body { packets, .. } => packets
.iter()
.filter(|p| matches!(p, SignaturePacket::Ops { .. }))
.count(),
Self::Done { signatures, .. } => signatures
.iter()
.filter(|p| matches!(p, FullSignaturePacket::Ops { .. }))
.count(),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn num_regular_signatures(&self) -> usize {
match self {
Self::Init { packets, .. } | Self::Body { packets, .. } => packets
.iter()
.filter(|p| matches!(p, SignaturePacket::Signature { .. }))
.count(),
Self::Done { signatures, .. } => signatures
.iter()
.filter(|p| matches!(p, FullSignaturePacket::Signature { .. }))
.count(),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn hash(&self, index: usize) -> Option<&[u8]> {
match self {
Self::Init { .. } => None,
Self::Body { .. } => None,
Self::Done { hashes, .. } => hashes.get(index).and_then(|h| h.as_deref()),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn signature(&self, index: usize) -> Option<&Signature> {
match self {
Self::Init { .. } => None,
Self::Body { .. } => None,
Self::Done { signatures, .. } => signatures.get(index).map(|s| s.signature()),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn signatures(&self) -> Option<&[FullSignaturePacket]> {
match self {
Self::Init { .. } => None,
Self::Body { .. } => None,
Self::Done { signatures, .. } => Some(signatures),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn get_ref(&self) -> &Message<'a> {
match self {
Self::Init { source, .. } => source,
Self::Body { source, .. } => source,
Self::Done { source, .. } => source,
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn get_mut(&mut self) -> &mut Message<'a> {
match self {
Self::Init { source, .. } => source,
Self::Body { source, .. } => source,
Self::Done { source, .. } => source,
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
pub fn into_inner(self) -> PacketBodyReader<MessageReader<'a>> {
match self {
Self::Init { source, .. } => source.into_inner(),
Self::Body { source, .. } => source.into_inner(),
Self::Done { source, .. } => source.into_inner(),
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
fn fill_inner(&mut self) -> io::Result<()> {
if matches!(self, Self::Done { .. }) {
return Ok(());
}
loop {
match std::mem::replace(self, Self::Error) {
Self::Init {
packets,
mut hashers,
mut source,
} => {
debug!("SignatureOnePassManyReader init");
let mut buffer = BytesMut::with_capacity(BUFFER_SIZE);
let read = fill_buffer_bytes(&mut source, &mut buffer, BUFFER_SIZE)?;
if read == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"missing signature",
));
}
for hasher in hashers.iter_mut().filter_map(|h| h.as_mut()) {
hasher.hash_buf(&buffer[..read]);
}
*self = Self::Body {
packets,
hashers,
source,
buffer,
};
}
Self::Body {
packets,
mut hashers,
mut source,
mut buffer,
} => {
debug!("SignatureOnePassManyReader body");
if buffer.has_remaining() {
*self = Self::Body {
packets,
hashers,
source,
buffer,
};
return Ok(());
}
let read = fill_buffer_bytes(&mut source, &mut buffer, BUFFER_SIZE)?;
for hasher in hashers.iter_mut().filter_map(|h| h.as_mut()) {
hasher.hash_buf(&buffer[..read]);
}
if read == 0 {
debug!("SignatureOnePassManyReader finish");
let hashers: Vec<_> =
hashers.into_iter().map(|h| h.map(|h| h.done())).collect();
let (reader, parts) = source.into_parts();
let mut packet_parser = crate::packet::PacketParser::new(reader);
// Find the signatures (skip padding and non-critical packets along the way)
let num_ops = packets
.iter()
.filter(|p| matches!(p, SignaturePacket::Ops { .. }))
.count();
let mut one_pass_signatures = Vec::with_capacity(num_ops);
while one_pass_signatures.len() < num_ops {
// read next packet from stream, if any
let Some(res) = packet_parser.next() else {
// no more packets
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"missing signature packet",
));
};
// skip marker and padding packets (and read next packet)
if matches!(res, Ok(Packet::Marker(_))) {
debug!("skipping marker packet");
continue;
}
if matches!(res, Ok(Packet::Padding(_))) {
debug!("skipping padding packet");
continue;
}
// skip soft packet parser errors (e.g. unknown non-critical packets)
// and read the next packet
if let Err(Error::InvalidPacketContent { ref source }) = res {
let err: &Error = source; // unbox
if let Error::Unsupported { message, .. } = err {
debug!("skipping unsupported packet: {res:?} ({message})");
continue;
}
}
// bubble up any other errors
let packet =
res.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
if let Packet::Signature(signature) = packet {
one_pass_signatures.push(signature);
} else {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"missing signature packet, found {:?} instead",
packet.tag()
),
));
};
}
// calculate final hashes
let mut hashes = Vec::with_capacity(packets.len());
let mut signatures = Vec::with_capacity(packets.len());
for (hasher, packet) in hashers.into_iter().zip(packets.into_iter()) {
if let Some(mut hasher) = hasher {
match packet {
SignaturePacket::Ops { signature: ops } => {
let Some(signature) = one_pass_signatures.pop() else {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"missing signature packet",
));
};
if !ops.matches(&signature) {
debug!(
"Ops and Signature don't match, rejecting this signature"
);
// If Ops and Signature don't match, we consider the signature invalid.
// Return an empty hash to model this.
hashes.push(None);
} else if let Some(config) = signature.config() {
debug!("calculating final hash");
let len = config
.hash_signature_data(&mut hasher)
.map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, e)
})?;
hasher.update(&config.trailer(len).map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, e)
})?);
hashes.push(Some(hasher.finalize()));
} else {
hashes.push(None);
}
signatures
.push(FullSignaturePacket::Ops { ops, signature });
}
SignaturePacket::Signature { signature } => {
// regular signature
let config = signature.config().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"inconsistent signature state",
)
})?;
// calculate final hash
let len = config.hash_signature_data(&mut hasher).map_err(
|e| io::Error::new(io::ErrorKind::InvalidData, e),
)?;
hasher.update(&config.trailer(len).map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, e)
})?);
hashes.push(Some(hasher.finalize()));
signatures
.push(FullSignaturePacket::Signature { signature });
}
}
} else {
hashes.push(None);
}
}
// reconstruct message source
let reader = packet_parser.into_inner();
let source = parts.into_message(reader);
*self = Self::Done {
signatures,
hashes,
source: Box::new(source),
};
} else {
*self = Self::Body {
packets,
hashers,
source,
buffer,
}
}
return Ok(());
}
Self::Done {
hashes,
source,
signatures,
} => {
*self = Self::Done {
hashes,
source,
signatures,
};
return Ok(());
}
Self::Error => return Err(io::Error::other("SignatureOnePassManyReader errored")),
}
}
}
pub fn is_done(&self) -> bool {
matches!(self, Self::Done { .. })
}
pub(crate) fn decompress(self) -> Result<Self> {
match self {
Self::Init {
packets,
hashers,
source,
} => {
let source = source.decompress()?;
Ok(Self::Init {
packets,
hashers,
source: Box::new(source),
})
}
_ => {
bail!("cannot decompress message that has already been read from");
}
}
}
pub(crate) fn decrypt_the_ring(
self,
ring: TheRing<'_>,
abort_early: bool,
) -> Result<(Self, RingResult)> {
match self {
Self::Init {
packets,
hashers,
source,
} => {
let (source, fps) = source.decrypt_the_ring(ring, abort_early)?;
Ok((
Self::Init {
packets,
hashers,
source: Box::new(source),
},
fps,
))
}
_ => {
bail!("cannot decrypt message that has already been read from");
}
}
}
}
impl BufRead for SignatureManyReader<'_> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
self.fill_inner()?;
match self {
Self::Init { .. } => unreachable!("invalid state"),
Self::Body { buffer, .. } => Ok(&buffer[..]),
Self::Done { .. } => Ok(&[][..]),
Self::Error => Err(io::Error::other("SignatureOnePassManyReader errored")),
}
}
fn consume(&mut self, amt: usize) {
match self {
Self::Init { .. } => panic!("must not be called before fill_buf"),
Self::Body { buffer, .. } => {
buffer.advance(amt);
}
Self::Done { .. } => {}
Self::Error => panic!("SignatureOnePassManyReader errored"),
}
}
}
impl Read for SignatureManyReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.fill_inner()?;
match self {
Self::Init { .. } => unreachable!("invalid state"),
Self::Body { buffer, .. } => {
let to_write = buffer.remaining().min(buf.len());
buffer.copy_to_slice(&mut buf[..to_write]);
Ok(to_write)
}
Self::Done { .. } => Ok(0),
Self::Error => Err(io::Error::other("SignatureOnePassManyReader errored")),
}
}
}