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
//! OpenPGP packet headers.
//!
//! An OpenPGP packet header contains packet meta-data.  Specifically,
//! it includes the [packet's type] (its so-called *tag*), and the
//! [packet's length].
//!
//! Decades ago, when OpenPGP was conceived, saving even a few bits
//! was considered important.  As such, OpenPGP uses very compact
//! encodings.  The encoding schemes have evolved so that there are
//! now two families: the so-called old format, and new format
//! encodings.
//!
//! [packet's type]: https://tools.ietf.org/html/rfc4880#section-4.3
//! [packet's length]: https://tools.ietf.org/html/rfc4880#section-4.2.1

use crate::{
    Error,
    Result,
};
use crate::packet::tag::Tag;
mod ctb;
pub use self::ctb::{
    CTB,
    CTBOld,
    CTBNew,
    PacketLengthType,
};

/// A packet's header.
///
/// See [Section 4.2 of RFC 4880] for details.
///
/// [Section 4.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-4.2
#[derive(Clone, Debug)]
pub struct Header {
    /// The packet's CTB.
    ctb: CTB,
    /// The packet's length.
    length: BodyLength,
}
assert_send_and_sync!(Header);

impl Header {
    /// Creates a new header.
    pub fn new(ctb: CTB, length: BodyLength) -> Self {
        Header { ctb, length }
    }

    /// Returns the header's CTB.
    pub fn ctb(&self) -> &CTB {
        &self.ctb
    }

    /// Returns the header's length.
    pub fn length(&self) -> &BodyLength {
        &self.length
    }

    /// Checks the header for validity.
    ///
    /// A header is consider invalid if:
    ///
    ///   - The tag is [`Tag::Reserved`].
    ///   - The tag is [`Tag::Unknown`] or [`Tag::Private`] and
    ///     `future_compatible` is false.
    ///   - The [length encoding] is invalid for the packet (e.g.,
    ///     partial body encoding may not be used for [`PKESK`] packets)
    ///   - The lengths are unreasonable for a packet (e.g., a
    ///     `PKESK` or [`SKESK`] larger than 10 KB).
    ///
    /// [`Tag::Reserved`]: super::Tag::Reserved
    /// [`Tag::Unknown`]: super::Tag::Unknown
    /// [`Tag::Private`]: super::Tag::Private
    /// [length encoding]: https://tools.ietf.org/html/rfc4880#section-4.2.2.4
    /// [`PKESK`]: super::PKESK
    /// [`SKESK`]: super::SKESK
    // Note: To check the packet's content, use
    //       `PacketParser::plausible`.
    pub fn valid(&self, future_compatible: bool) -> Result<()> {
        let tag = self.ctb.tag();

        match tag {
            // Reserved packets are never valid.
            Tag::Reserved =>
                return Err(Error::UnsupportedPacketType(tag).into()),
            // Unknown packets are not valid unless we want future compatibility.
            Tag::Unknown(_) | Tag::Private(_) if !future_compatible =>
                return Err(Error::UnsupportedPacketType(tag).into()),
            _ => (),
        }

        // An implementation MAY use Partial Body Lengths for data
        // packets, be they literal, compressed, or encrypted.  The
        // first partial length MUST be at least 512 octets long.
        // Partial Body Lengths MUST NOT be used for any other packet
        // types.
        //
        // https://tools.ietf.org/html/rfc4880#section-4.2.2.4
        if tag == Tag::Literal || tag == Tag::CompressedData
            || tag == Tag::SED || tag == Tag::SEIP
            || tag == Tag::AED
        {
            // Data packet.
            match self.length {
                BodyLength::Indeterminate => (),
                BodyLength::Partial(l) => {
                    if l < 512 {
                        return Err(Error::MalformedPacket(
                            format!("Partial body length must be \
                                     at least 512 (got: {})",
                                    l)).into());
                    }
                }
                BodyLength::Full(l) => {
                    // In the following block cipher length checks, we
                    // conservatively assume a block size of 8 bytes,
                    // because Twofish, TripleDES, IDEA, and CAST-5
                    // have a block size of 64 bits.
                    if tag == Tag::SED && (l < (8       // Random block.
                                                + 2     // Quickcheck bytes.
                                                + 6)) { // Smallest literal.
                        return Err(Error::MalformedPacket(
                            format!("{} packet's length must be \
                                     at least 16 bytes in length (got: {})",
                                    tag, l)).into());
                    } else if tag == Tag::SEIP
                        && (l < (1       // Version.
                                 + 8     // Random block.
                                 + 2     // Quickcheck bytes.
                                 + 6     // Smallest literal.
                                 + 20))  // MDC packet.
                    {
                        return Err(Error::MalformedPacket(
                            format!("{} packet's length minus 1 must be \
                                     at least 37 bytes in length (got: {})",
                                    tag, l)).into());
                    } else if tag == Tag::CompressedData && l == 0 {
                        // One byte header.
                        return Err(Error::MalformedPacket(
                            format!("{} packet's length must be \
                                     at least 1 byte (got ({})",
                                    tag, l)).into());
                    } else if tag == Tag::Literal && l < 6 {
                        // Smallest literal packet consists of 6 octets.
                        return Err(Error::MalformedPacket(
                            format!("{} packet's length must be \
                                     at least 6 bytes (got: ({})",
                                    tag, l)).into());
                    }
                }
            }
        } else {
            // Non-data packet.
            match self.length {
                BodyLength::Indeterminate =>
                    return Err(Error::MalformedPacket(
                        format!("Indeterminite length encoding \
                                 not allowed for {} packets",
                                tag)).into()),
                BodyLength::Partial(_) =>
                    return Err(Error::MalformedPacket(
                        format!("Partial Body Chunking not allowed \
                                 for {} packets",
                                tag)).into()),
                BodyLength::Full(l) => {
                    let valid = match tag {
                        Tag::Signature =>
                            // A V3 signature is 19 bytes plus the
                            // MPIs.  A V4 is 10 bytes plus the hash
                            // areas and the MPIs.
                            (10..(10  // Header, fixed sized fields.
                                    + 2 * 64 * 1024 // Hashed & Unhashed areas.
                                    + 64 * 1024 // MPIs.
                                   )).contains(&l),
                        Tag::SKESK =>
                            // 2 bytes of fixed header.  An s2k
                            // specification (at least 1 byte), an
                            // optional encryption session key.
                            (3..10 * 1024).contains(&l),
                        Tag::PKESK =>
                            // 10 bytes of fixed header, plus the
                            // encrypted session key.
                            10 < l && l < 10 * 1024,
                        Tag::OnePassSig if ! future_compatible => l == 13,
                        Tag::OnePassSig => l < 1024,
                        Tag::PublicKey | Tag::PublicSubkey
                            | Tag::SecretKey | Tag::SecretSubkey =>
                            // A V3 key is 8 bytes of fixed header
                            // plus MPIs.  A V4 key is 6 bytes of
                            // fixed headers plus MPIs.
                            6 < l && l < 1024 * 1024,
                        Tag::Trust => true,
                        Tag::UserID =>
                            // Avoid insane user ids.
                            l < 32 * 1024,
                        Tag::UserAttribute =>
                            // The header is at least 2 bytes.
                            2 <= l,
                        Tag::MDC => l == 20,

                        Tag::Literal | Tag::CompressedData
                            | Tag::SED | Tag::SEIP | Tag::AED =>
                            unreachable!("handled in the data-packet branch"),
                        Tag::Unknown(_) | Tag::Private(_) => true,

                        Tag::Marker => l == 3,
                        Tag::Reserved => true,
                    };

                    if ! valid {
                        return Err(Error::MalformedPacket(
                            format!("Invalid size ({} bytes) for a {} packet",
                                    l, tag)).into())
                    }
                }
            }
        }

        Ok(())
    }
}

/// A packet's size.
///
/// A packet's size can be expressed in three different ways.  Either
/// the size of the packet is fully known (`Full`), the packet is
/// chunked using OpenPGP's partial body encoding (`Partial`), or the
/// packet extends to the end of the file (`Indeterminate`).  See
/// [Section 4.2 of RFC 4880] for more details.
///
///   [Section 4.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-4.2
#[derive(Debug)]
// We need PartialEq so that assert_eq! works.
#[derive(PartialEq)]
#[derive(Clone, Copy)]
pub enum BodyLength {
    /// The packet's size is known.
    Full(u32),
    /// The parameter is the number of bytes in the current chunk.
    ///
    /// This type is only used with new format packets.
    Partial(u32),
    /// The packet extends until an EOF is encountered.
    ///
    /// This type is only used with old format packets.
    Indeterminate,
}
assert_send_and_sync!(BodyLength);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::packet::Packet;
    use crate::parse::{
        Cookie, Dearmor, PacketParserBuilder, PacketParserResult, Parse,
    };
    use crate::serialize::SerializeInto;

    quickcheck! {
        /// Checks alignment of Header::parse-then-Header::valid, the
        /// PacketParser, and Arbitrary::arbitrary.
        fn parser_alignment(p: Packet) -> bool {
            let verbose = false;
            let buf = p.to_vec().expect("Failed to serialize packet");

            // First, check Header::parse and Header::valid.
            let mut reader = buffered_reader::Memory::with_cookie(
                &buf, Cookie::default());
            let header = Header::parse(&mut reader).unwrap();
            if verbose {
                eprintln!("header parsed: {:?}", header);
            }
            header.valid(true).unwrap();
            header.valid(false).unwrap();

            // Now check the packet parser.  Be careful to disable the
            // armor detection because that in turn relies on
            // Header::valid, and we want to test the behavior of the
            // packet parser.
            let ppr =
                PacketParserBuilder::from_bytes(&buf).unwrap()
                .dearmor(Dearmor::Disabled)
                .buffer_unread_content()
                .build().unwrap();

            let (p, ppr) = match ppr {
                PacketParserResult::Some(pp) => {
                    pp.next().unwrap()
                },
                PacketParserResult::EOF(eof) =>
                    panic!("no packet found: {:?}", eof),
            };
            if verbose {
                eprintln!("packet parser parsed: {:?}", p);
            }

            if let PacketParserResult::Some(pp) = ppr {
                panic!("Excess data after packet: {:?}", pp)
            }

            true
        }
    }
}