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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
|
//! OpenPGP Message support.
//!
//! An OpenPGP message is a sequence of OpenPGP packets that
//! corresponds to an optionally signed, optionally encrypted,
//! optionally compressed literal data packet. The exact format of an
//! OpenPGP message is described in [Section 11.3 of RFC 4880].
//!
//! This module provides support for validating and working with
//! OpenPGP messages.
//!
//! [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
use std::fmt;
use std::io;
use std::path::Path;
use failure;
use Result;
use Error;
use Packet;
use PacketPile;
use Message;
use packet::Literal;
use packet::Tag;
use parse::Parse;
mod lexer;
mod grammar;
use self::lexer::{Lexer, LexicalError};
pub use self::lexer::Token;
use lalrpop_util::ParseError;
use self::grammar::MessageParser;
/// Errors that MessageValidator::check may return.
#[derive(Debug, Clone)]
pub enum MessageParserError {
/// A parser error.
Parser(ParseError<usize, Token, LexicalError>),
/// An OpenPGP error.
OpenPGP(Error),
}
impl From<MessageParserError> for failure::Error {
fn from(err: MessageParserError) -> Self {
match err {
MessageParserError::Parser(p) => p.into(),
MessageParserError::OpenPGP(p) => p.into(),
}
}
}
/// Whether a packet sequence is a valid OpenPGP Message.
#[derive(Debug)]
pub enum MessageValidity {
/// The packet sequence is a valid OpenPGP message.
Message,
/// The packet sequence appears to be a valid OpenPGP message that
/// has been truncated, i.e., the packet sequence is a valid
/// prefix of an OpenPGP message.
MessagePrefix,
/// The message is definitely not valid.
Error(failure::Error),
}
impl MessageValidity {
/// Returns whether the packet sequence is a valid message.
///
/// Note: a `MessageValidator` will only return this after
/// `MessageValidator::finish` has been called.
pub fn is_message(&self) -> bool {
if let MessageValidity::Message = self {
true
} else {
false
}
}
/// Returns whether the packet sequence forms a valid message
/// prefix.
///
/// Note: a `MessageValidator` will only return this before
/// `MessageValidator::finish` has been called.
pub fn is_message_prefix(&self) -> bool {
if let MessageValidity::MessagePrefix = self {
true
} else {
false
}
}
/// Returns whether the packet sequence is definitely not a valid
/// OpenPGP Message.
pub fn is_err(&self) -> bool {
if let MessageValidity::Error(_) = self {
true
} else {
false
}
}
}
/// Used to help validate a packet sequence is a valid OpenPGP message.
#[derive(Debug)]
pub struct MessageValidator {
tokens: Vec<Token>,
finished: bool,
// Once a raw token is pushed, this is set to None and pushing
// packet Tags is no longer supported.
depth: Option<isize>,
// If we know that the packet sequence is invalid.
error: Option<MessageParserError>,
}
impl Default for MessageValidator {
fn default() -> Self {
MessageValidator::new()
}
}
impl MessageValidator {
/// Instantiates a new `MessageValidator`.
pub fn new() -> Self {
MessageValidator {
tokens: vec![],
finished: false,
depth: Some(0),
error: None,
}
}
/// Returns whether the packet sequence is a valid message.
///
/// Note: a `MessageValidator` will only return this after
/// `MessageValidator::finish` has been called.
pub fn is_message(&self) -> bool {
self.check().is_message()
}
/// Returns whether the packet sequence forms a valid message
/// prefix.
///
/// Note: a `MessageValidator` will only return this before
/// `MessageValidator::finish` has been called.
pub fn is_message_prefix(&self) -> bool {
self.check().is_message_prefix()
}
/// Returns whether the packet sequence is definitely not a valid
/// OpenPGP Message.
pub fn is_err(&self) -> bool {
self.check().is_err()
}
/// Adds a token to the token stream.
#[cfg(test)]
pub(crate) fn push_raw(&mut self, token: Token) {
assert!(!self.finished);
if self.error.is_some() {
return;
}
self.depth = None;
self.tokens.push(token);
}
/// Add the token `token` at depth `depth` to the token stream.
///
/// Note: top-level packets are at depth 0, their immediate
/// children are a depth 1, etc.
///
/// The token *must* correspond to a packet; this function will
/// panic if `token` is Token::Pop.
pub fn push_token(&mut self, token: Token, depth: isize) {
assert!(!self.finished);
assert!(self.depth.is_some());
assert!(token != Token::Pop);
if self.error.is_some() {
return;
}
// We popped one or more containers.
if self.depth.unwrap() > depth {
for _ in 1..self.depth.unwrap() - depth + 1 {
self.tokens.push(Token::Pop);
}
}
self.depth = Some(depth);
self.tokens.push(token);
}
/// Add a packet of type `tag` at depth `depth` to the token
/// stream.
///
/// Note: top-level packets are at depth 0.
pub fn push(&mut self, tag: Tag, depth: isize) {
let token = match tag {
Tag::Literal => Token::Literal,
Tag::CompressedData => Token::CompressedData,
Tag::SKESK => Token::SKESK,
Tag::PKESK => Token::PKESK,
Tag::SEIP => Token::SEIP,
Tag::MDC => Token::MDC,
Tag::AED => Token::AED,
Tag::OnePassSig => Token::OPS,
Tag::Signature => Token::SIG,
Tag::Marker => {
// "[Marker packets] MUST be ignored when received.",
// section 5.8 of RFC4880.
return;
},
_ => {
// Unknown token.
self.error = Some(MessageParserError::OpenPGP(
Error::MalformedMessage(
format!("Invalid OpenPGP message: unexpected packet: {:?}",
tag).into())));
self.tokens.clear();
return;
}
};
self.push_token(token, depth)
}
/// Note that the entire message has been seen.
pub fn finish(&mut self) {
assert!(!self.finished);
if let Some(depth) = self.depth {
// Pop any containers.
for _ in 0..depth {
self.tokens.push(Token::Pop);
}
}
self.finished = true;
}
/// Returns whether the token stream corresponds to a valid
/// OpenPGP message.
///
/// This returns a tri-state: if the message is valid, it returns
/// MessageValidity::Message, if the message is invalid, then it
/// returns MessageValidity::Error. If the message could be
/// valid, then it returns MessageValidity::MessagePrefix.
///
/// Note: if MessageValidator::finish() *hasn't* been called, then
/// this function will only ever return either
/// MessageValidity::MessagePrefix or MessageValidity::Error. Once
/// MessageValidity::finish() has been called, then only
/// MessageValidity::Message or MessageValidity::Bad will be called.
pub fn check(&self) -> MessageValidity {
if let Some(ref err) = self.error {
return MessageValidity::Error((*err).clone().into());
}
let r = MessageParser::new().parse(
Lexer::from_tokens(&self.tokens[..]));
if self.finished {
match r {
Ok(_) => MessageValidity::Message,
Err(ref err) =>
MessageValidity::Error(
MessageParserError::Parser((*err).clone()).into()),
}
} else {
match r {
Ok(_) => MessageValidity::MessagePrefix,
Err(ParseError::UnrecognizedToken { token: None, .. }) =>
MessageValidity::MessagePrefix,
Err(ref err) =>
MessageValidity::Error(
MessageParserError::Parser((*err).clone()).into()),
}
}
}
}
impl fmt::Debug for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Message")
.field("pile", &self.pile)
.finish()
}
}
impl<'a> Parse<'a, Message> for Message {
/// Reads a `Message` from the specified reader.
///
/// See [`Message::from_packet_pile`] for more details.
///
/// [`Message::from_packet_pile`]: #method.from_packet_pile
fn from_reader<R: 'a + io::Read>(reader: R) -> Result<Self> {
Self::from_packet_pile(PacketPile::from_reader(reader)?)
}
/// Reads a `Message` from the specified file.
///
/// See [`Message::from_packet_pile`] for more details.
///
/// [`Message::from_packet_pile`]: #method.from_packet_pile
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::from_packet_pile(PacketPile::from_file(path)?)
}
/// Reads a `Message` from `buf`.
///
/// See [`Message::from_packet_pile`] for more details.
///
/// [`Message::from_packet_pile`]: #method.from_packet_pile
fn from_bytes(buf: &'a [u8]) -> Result<Self> {
Self::from_packet_pile(PacketPile::from_bytes(buf)?)
}
}
impl Message {
/// Converts the `PacketPile` to a `Message`.
///
/// Converting a `PacketPile` to a `Message` doesn't change the
/// packets; it asserts that the packet sequence is an optionally
/// encrypted, optionally signed, optionally compressed literal
/// data packet. The exact grammar is defined in [Section 11.3 of
/// RFC 4880].
///
/// Caveats: this function assumes that any still encrypted parts
/// or still compressed parts are valid messages.
///
/// [Section 11.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-11.3
pub fn from_packet_pile(pile: PacketPile) -> Result<Self> {
let mut v = MessageValidator::new();
for (path, packet) in pile.descendants().paths() {
match packet {
Packet::Unknown(ref u) =>
return Err(MessageParserError::OpenPGP(
Error::MalformedMessage(
format!("Invalid OpenPGP message: \
malformed {:?} packet: {}",
u.tag(), u.error()).into())).into()),
_ => v.push(packet.tag(), path.len() as isize - 1),
}
match packet {
Packet::CompressedData(_) | Packet::SEIP(_) | Packet::AED(_) =>
{
// If a container's content is not unpacked, then
// we treat the content as an opaque message.
if packet.children.is_none() && packet.body.is_some() {
v.push_token(Token::OpaqueContent,
path.len() as isize - 1 + 1);
}
}
_ => {}
}
}
v.finish();
match v.check() {
MessageValidity::Message => Ok(Message { pile: pile }),
MessageValidity::MessagePrefix => unreachable!(),
// We really want to squash the lexer's error: it is an
// internal detail that may change, and meaningless even
// to an immediate user of this crate.
MessageValidity::Error(e) => Err(e.into()),
}
}
/// Converts the vector of `Packets` to a `Message`.
///
/// See [`Message::from_packet_pile`] for more details.
///
/// [`Message::from_packet_pile`]: #method.from_packet_pile
pub fn from_packets(packets: Vec<Packet>) -> Result<Self> {
Self::from_packet_pile(PacketPile::from(packets))
}
/// Returns the body of the message.
///
/// Returns `None` if no literal data packet is found. This
/// happens if a SEIP container has not been decrypted.
pub fn body(&self) -> Option<&Literal> {
for packet in self.pile.descendants() {
if let &Packet::Literal(ref l) = packet {
return Some(l);
}
}
// No literal data packet found.
None
}
}
impl From<Message> for PacketPile {
fn from(m: Message) -> Self {
m.pile
}
}
impl ::std::ops::Deref for Message {
type Target = PacketPile;
fn deref(&self) -> &Self::Target {
&self.pile
}
}
#[cfg(test)]
mod tests {
use super::*;
use constants::DataFormat::Text;
use HashAlgorithm;
use constants::CompressionAlgorithm;
use SymmetricAlgorithm;
use PublicKeyAlgorithm;
use SignatureType;
use crypto::KeyPair;
use crypto::s2k::S2K;
use crypto::mpis::{Ciphertext, MPI};
use packet::prelude::*;
use KeyID;
use Container;
#[test]
fn tokens() {
use self::lexer::{Token, Lexer};
use self::lexer::Token::*;
use self::grammar::MessageParser;
struct TestVector<'a> {
s: &'a [Token],
result: bool,
}
let test_vectors = [
TestVector {
s: &[Literal][..],
result: true,
},
TestVector {
s: &[CompressedData, Literal, Pop],
result: true,
},
TestVector {
s: &[CompressedData, CompressedData, Literal,
Pop, Pop],
result: true,
},
TestVector {
s: &[SEIP, Literal, MDC, Pop],
result: true,
},
TestVector {
s: &[CompressedData, SEIP, Literal, MDC, Pop, Pop],
result: true,
},
TestVector {
s: &[CompressedData, SEIP, CompressedData, Literal,
Pop, MDC, Pop, Pop],
result: true,
},
TestVector {
s: &[SEIP, MDC, Pop],
result: false,
},
TestVector {
s: &[SKESK, SEIP, Literal, MDC, Pop],
result: true,
},
TestVector {
s: &[PKESK, SEIP, Literal, MDC, Pop],
result: true,
},
TestVector {
s: &[SKESK, SKESK, SEIP, Literal, MDC, Pop],
result: true,
},
TestVector {
s: &[AED, Literal, Pop],
result: true,
},
TestVector {
s: &[CompressedData, AED, Literal, Pop, Pop],
result: true,
},
TestVector {
s: &[CompressedData, AED, CompressedData, Literal,
Pop, Pop, Pop],
result: true,
},
TestVector {
s: &[AED, Pop],
result: false,
},
TestVector {
s: &[SKESK, AED, Literal, Pop],
result: true,
},
TestVector {
s: &[PKESK, AED, Literal, Pop],
result: true,
},
TestVector {
s: &[SKESK, SKESK, AED, Literal, Pop],
result: true,
},
TestVector {
s: &[OPS, Literal, SIG],
result: true,
},
TestVector {
s: &[OPS, OPS, Literal, SIG, SIG],
result: true,
},
TestVector {
s: &[OPS, OPS, Literal, SIG],
result: false,
},
TestVector {
s: &[OPS, OPS, SEIP, OPS, SEIP, Literal, MDC, Pop,
SIG, MDC, Pop, SIG, SIG],
result: true,
},
TestVector {
s: &[CompressedData, OpaqueContent],
result: false,
},
TestVector {
s: &[CompressedData, OpaqueContent, Pop],
result: true,
},
TestVector {
s: &[CompressedData, CompressedData, OpaqueContent, Pop, Pop],
result: true,
},
TestVector {
s: &[SEIP, CompressedData, OpaqueContent, Pop, MDC, Pop],
result: true,
},
TestVector {
s: &[SEIP, OpaqueContent, Pop],
result: true,
},
];
for v in test_vectors.into_iter() {
if v.result {
let mut l = MessageValidator::new();
for token in v.s.iter() {
l.push_raw(*token);
assert_match!(MessageValidity::MessagePrefix = l.check());
}
l.finish();
assert_match!(MessageValidity::Message = l.check());
}
match MessageParser::new().parse(Lexer::from_tokens(v.s)) {
Ok(r) => assert!(v.result, "Parsing: {:?} => {:?}", v.s, r),
Err(e) => assert!(! v.result, "Parsing: {:?} => {:?}", v.s, e),
}
}
}
#[test]
fn tags() {
use packet::Tag::*;
struct TestVector<'a> {
s: &'a [(Tag, isize)],
result: bool,
}
let test_vectors = [
TestVector {
s: &[(Literal, 0)][..],
result: true,
},
TestVector {
s: &[(CompressedData, 0), (Literal, 1)],
result: true,
},
TestVector {
s: &[(CompressedData, 0), (CompressedData, 1), (Literal, 2)],
result: true,
},
TestVector {
s: &[(SEIP, 0), (Literal, 1), (MDC, 1)],
result: true,
},
TestVector {
s: &[(CompressedData, 0), (SEIP, 1), (Literal, 2), (MDC, 2)],
result: true,
},
TestVector {
s: &[(CompressedData, 0), (SEIP, 1),
(CompressedData, 2), (Literal, 3), (MDC, 2)],
result: true,
},
TestVector {
s: &[(CompressedData, 0), (SEIP, 1),
(CompressedData, 2), (Literal, 3), (MDC, 3)],
result: false,
},
TestVector {
s: &[(SEIP, 0), (MDC, 0)],
result: false,
},
TestVector {
s: &[(SKESK, 0), (SEIP, 0), (Literal, 1), (MDC, 1)],
result: true,
},
TestVector {
s: &[(PKESK, 0), (SEIP, 0), (Literal, 1), (MDC, 1)],
result: true,
},
TestVector {
s: &[(PKESK, 0), (SEIP, 0), (CompressedData, 1), (Literal, 2),
(MDC, 1)],
result: true,
},
TestVector {
s: &[(SKESK, 0), (SKESK, 0), (SEIP, 0), (Literal, 1), (MDC, 1)],
result: true,
},
TestVector {
s: &[(OnePassSig, 0), (Literal, 0), (Signature, 0)],
result: true,
},
TestVector {
s: &[(OnePassSig, 0), (CompressedData, 0), (Literal, 1),
(Signature, 0)],
result: true,
},
TestVector {
s: &[(OnePassSig, 0), (OnePassSig, 0), (Literal, 0),
(Signature, 0), (Signature, 0)],
result: true,
},
TestVector {
s: &[(OnePassSig, 0), (OnePassSig, 0), (Literal, 0),
(Signature, 0)],
result: false,
},
TestVector {
s: &[(OnePassSig, 0), (OnePassSig, 0), (SEIP, 0),
(OnePassSig, 1), (SEIP, 1), (Literal, 2), (MDC, 2),
(Signature, 1), (MDC, 1), (Signature, 0), (Signature, 0)],
result: true,
},
// "[A Marker packet] MUST be ignored when received. It
// may be placed at the beginning of a message that uses
// features not available in PGP 2.6.x in order to cause
// that version to report that newer software is necessary
// to process the message.", section 5.8 of RFC4880.
TestVector {
s: &[(Marker, 0),
(OnePassSig, 0), (Literal, 0), (Signature, 0)],
result: true,
},
];
for v in test_vectors.into_iter() {
let mut l = MessageValidator::new();
for (token, depth) in v.s.iter() {
l.push(*token, *depth);
if v.result {
assert_match!(MessageValidity::MessagePrefix = l.check());
}
}
l.finish();
if v.result {
assert_match!(MessageValidity::Message = l.check());
} else {
assert_match!(MessageValidity::Error(_) = l.check());
}
}
}
#[test]
fn basic() {
// Empty.
// => bad.
let message = Message::from_packets(vec![]);
assert!(message.is_err(), "{:?}", message);
// 0: Literal
// => good.
let mut packets = Vec::new();
let mut lit = Literal::new(Text);
lit.set_body(b"data".to_vec());
packets.push(lit.into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
}
#[test]
fn compressed_part() {
let mut lit = Literal::new(Text);
lit.set_body(b"data".to_vec());
// 0: CompressedData
// 0: Literal
// => good.
let mut packets = Vec::new();
packets.push(
CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(lit.clone().into())
.into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
// 0: CompressedData
// 0: Literal
// 1: Literal
// => bad.
let mut packets = Vec::new();
packets.push(
CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(lit.clone().into())
.push(lit.clone().into())
.into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: CompressedData
// 0: Literal
// 1: Literal
// => bad.
let mut packets = Vec::new();
packets.push(
CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(lit.clone().into())
.into());
packets.push(lit.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: CompressedData
// 0: CompressedData
// 0: Literal
// => good.
let mut packets = Vec::new();
packets.push(
CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(lit.clone()
.into())
.into())
.into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
}
#[test]
fn one_pass_sig_part() {
let mut lit = Literal::new(Text);
lit.set_body(b"data".to_vec());
let hash = ::constants::HashAlgorithm::SHA512;
let key: Key =
::packet::key::Key4::generate_ecc(true, ::constants::Curve::Ed25519)
.unwrap().into();
let sec =
if let Some(SecretKey::Unencrypted { ref mpis }) = key.secret() {
mpis.clone()
} else {
panic!()
};
let sig = ::packet::signature::Builder::new(SignatureType::Binary)
.sign_hash(&mut KeyPair::new(key, sec).unwrap(),
hash, hash.context().unwrap()).unwrap();
// 0: OnePassSig
// => bad.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: OnePassSig
// 1: Literal
// => bad.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(lit.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: OnePassSig
// 1: Literal
// 2: Signature
// => good.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(lit.clone().into());
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
// 0: OnePassSig
// 1: Literal
// 2: Signature
// 3: Signature
// => bad.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(lit.clone().into());
packets.push(sig.clone().into());
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: OnePassSig
// 1: OnePassSig
// 2: Literal
// 3: Signature
// 4: Signature
// => good.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(lit.clone().into());
packets.push(sig.clone().into());
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
// 0: OnePassSig
// 1: OnePassSig
// 2: Literal
// 3: Literal
// 4: Signature
// 5: Signature
// => bad.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(lit.clone().into());
packets.push(lit.clone().into());
packets.push(sig.clone().into());
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: OnePassSig
// 1: OnePassSig
// 2: CompressedData
// 0: Literal
// 3: Signature
// 4: Signature
// => good.
let mut packets : Vec<Packet> = Vec::new();
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(OnePassSig3::new(SignatureType::Binary).into());
packets.push(
CompressedData::new(CompressionAlgorithm::Uncompressed)
.push(lit.clone().into())
.into());
packets.push(sig.clone().into());
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
}
#[test]
fn signature_part() {
let mut lit = Literal::new(Text);
lit.set_body(b"data".to_vec());
let hash = ::constants::HashAlgorithm::SHA512;
let key: Key =
::packet::key::Key4::generate_ecc(true, ::constants::Curve::Ed25519)
.unwrap().into();
let sec =
if let Some(SecretKey::Unencrypted { ref mpis }) = key.secret() {
mpis.clone()
} else {
panic!()
};
let sig = ::packet::signature::Builder::new(SignatureType::Binary)
.sign_hash(&mut KeyPair::new(key, sec).unwrap(),
hash, hash.context().unwrap()).unwrap();
// 0: Signature
// => bad.
let mut packets : Vec<Packet> = Vec::new();
packets.push(sig.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_err(), "{:?}", message);
// 0: Signature
// 1: Literal
// => good.
let mut packets : Vec<Packet> = Vec::new();
packets.push(sig.clone().into());
packets.push(lit.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
// 0: Signature
// 1: Signature
// 2: Literal
// => good.
let mut packets : Vec<Packet> = Vec::new();
packets.push(sig.clone().into());
packets.push(sig.clone().into());
packets.push(lit.clone().into());
let message = Message::from_packets(packets);
assert!(message.is_ok(), "{:?}", message);
}
#[test]
fn encrypted_part() {
// There are no simple constructors for SEIP packets: they are
// interleaved with SK-ESK and PK-ESK packets. And, the
// session key needs to be managed. Instead, we use some
// internal iterfaces to progressively build up more
// complicated messages.
let mut lit = Literal::new(Text);
lit.set_body(b"data".to_vec());
// 0: SK-ESK
// => bad.
let mut packets : Vec<Packet> = Vec::new();
let sk = ::crypto::SessionKey::new(&mut Default::default(), 8);
packets.push(SKESK4::with_password(
SymmetricAlgorithm::AES256,
S2K::Simple { hash: HashAlgorithm::SHA256 },
&sk,
&"12345678".into()).unwrap().into());
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:?}", message);
// 0: SK-ESK
// 1: Literal
// => bad.
packets.push(lit.clone().into());
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::Literal ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:?}", message);
// 0: SK-ESK
// 1: SEIP
// 0: Literal
// 1: MDC
// => good.
let mut seip = SEIP1::new();
seip.common.children = Some(Container::new());
seip.common.children.as_mut().unwrap().push(
lit.clone().into());
seip.common.children.as_mut().unwrap().push(
MDC::from([0u8; 20]).into());
packets[1] = seip.into();
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SEIP ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_ok(), "{:#?}", message);
// 0: SK-ESK
// 1: SEIP
// 0: Literal
// 1: MDC
// 2: SK-ESK
// => bad.
let skesk = packets[0].clone();
packets.push(skesk);
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SEIP, Tag::SKESK ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:#?}", message);
// 0: SK-ESK
// 1: SK-ESK
// 2: SEIP
// 0: Literal
// 1: MDC
// => good.
packets.swap(1, 2);
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SKESK, Tag::SEIP ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_ok(), "{:#?}", message);
// 0: SK-ESK
// 1: SK-ESK
// 2: SEIP
// 0: Literal
// 1: MDC
// 3: SEIP
// 0: Literal
// 1: MDC
// => bad.
let seip = packets[2].clone();
packets.push(seip);
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SKESK, Tag::SEIP, Tag::SEIP ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:#?}", message);
// 0: SK-ESK
// 1: SK-ESK
// 2: SEIP
// 0: Literal
// 1: MDC
// 3: Literal
// => bad.
packets[3] = lit.clone().into();
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SKESK, Tag::SEIP, Tag::Literal ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:#?}", message);
// 0: SK-ESK
// 1: SK-ESK
// 2: SEIP
// 0: Literal
// 1: MDC
// 2: Literal
// => bad.
packets.remove(3);
packets[2].children.as_mut().unwrap().push(lit.clone().into());
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::SKESK, Tag::SEIP ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_err(), "{:#?}", message);
// 0: SK-ESK
// 2: PK-ESK
// 1: SK-ESK
// 2: SEIP
// 0: Literal
// => good.
packets[2].children.as_mut().unwrap().packets.pop().unwrap();
#[allow(deprecated)]
packets.insert(
1,
PKESK3::new(
KeyID::from_hex("0000111122223333").unwrap(),
PublicKeyAlgorithm::RSAEncrypt,
Ciphertext::RSA { c: MPI::new(&[]) }).unwrap().into());
assert!(packets.iter().map(|p| p.tag()).collect::<Vec<Tag>>()
== [ Tag::SKESK, Tag::PKESK, Tag::SKESK, Tag::SEIP ]);
let message = Message::from_packets(packets.clone());
assert!(message.is_ok(), "{:#?}", message);
}
}
|