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
use std::fmt;
use std::hash::{Hash, Hasher};

#[cfg(any(test, feature = "quickcheck"))]
use quickcheck::{Arbitrary, Gen};

/// Describes features supported by an OpenPGP implementation.
///
/// The features are defined in [Section 5.2.3.24 of RFC 4880], and
/// [Section 5.2.3.25 of RFC 4880bis].
///
/// [Section 5.2.3.24 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.24
/// [Section 5.2.3.25 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-5.2.3.25
///
/// # A note on equality
///
/// `PartialEq` is implements semantic equality, i.e. it ignores
/// padding.
///
/// # Examples
///
/// ```
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #     .generate()?;
/// match cert.with_policy(p, None)?.primary_userid()?.features() {
///     Some(features) => {
///         println!("Certificate holder's supported features:");
///         assert!(features.supports_mdc());
///         assert!(!features.supports_aead());
///     }
///     None => {
///         println!("Certificate Holder did not specify any features.");
/// #       unreachable!();
///     }
/// }
/// # Ok(()) }
/// ```
#[derive(Clone)]
pub struct Features{
    mdc: bool,
    aead: bool,
    unknown: Box<[u8]>,
    /// Original length, including trailing zeros.
    pad_to: usize,
}

impl Default for Features {
    fn default() -> Self {
        Features{
            mdc: false,
            aead: false,
            unknown: Default::default(),
            pad_to: 0,
        }
    }
}

impl fmt::Debug for Features {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut dirty = false;
        if self.supports_mdc() {
            f.write_str("MDC")?;
            dirty = true;
        }
        if self.supports_aead() {
            if dirty { f.write_str(", ")?; }
            f.write_str("AEAD")?;
            dirty = true;
        }
        if ! self.unknown.is_empty() {
            if dirty { f.write_str(", ")?; }
            f.write_str("+0x")?;
            f.write_str(
                &crate::fmt::hex::encode_pretty(&self.unknown))?;
            dirty = true;
        }
        if self.pad_to > FEATURE_FLAGS_N_KNOWN_BYTES + self.unknown.len() {
            if dirty { f.write_str(", ")?; }
            write!(f, "+padding({} bytes)", self.pad_to - self.unknown.len())?;
        }

        Ok(())
    }
}

impl PartialEq for Features {
    fn eq(&self, other: &Self) -> bool {
        self.mdc == other.mdc
            && self.aead == other.aead
            && self.unknown == other.unknown
    }
}

impl Eq for Features {}

impl Hash for Features {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.mdc.hash(state);
        self.aead.hash(state);
        self.unknown.hash(state);
    }
}

impl Features {
    /// Creates a new instance from `bits`.
    pub fn new<B: AsRef<[u8]>>(bits: B) -> Self {
        let bits = bits.as_ref();
        let mut pad_to = 0;

        let mdc = bits.get(0)
            .map(|x| x & FEATURE_FLAG_MDC != 0).unwrap_or(false);
        let aead = bits.get(0)
            .map(|x| x & FEATURE_FLAG_AEAD != 0).unwrap_or(false);
        let unk = if bits.is_empty() {
            Box::default()
        } else {
            let mut cpy = Vec::from(bits);

            cpy[0] &= (FEATURE_FLAG_MDC | FEATURE_FLAG_AEAD) ^ 0xff;

            pad_to = crate::types::bitfield_remove_padding(&mut cpy);
            cpy.into_boxed_slice()
        };

        Features{
            mdc, aead, unknown: unk, pad_to,
        }
    }

    /// Returns an feature set describing Sequoia.
    pub fn sequoia() -> Self {
        Features{
            mdc: true,
            aead: false,
            unknown: Default::default(),
            pad_to: 0,
        }
    }

    /// Returns a slice referencing the raw values.
    pub(crate) fn to_vec(&self) -> Vec<u8> {
        let mut ret = if self.unknown.is_empty() {
            vec![0]
        } else {
            self.unknown.clone().into()
        };

        if self.mdc { ret[0] |= FEATURE_FLAG_MDC; }
        if self.aead { ret[0] |= FEATURE_FLAG_AEAD; }

        // Corner case: empty flag field.  We initialized ret to
        // vec![0] for easy setting of flags.  See if any of the above
        // was set.
        if ret.len() == 1 && ret[0] == 0 {
            // Nope.  Trim this byte.
            ret.pop();
        }

        for _ in ret.len()..self.pad_to {
            ret.push(0);
        }

        ret
    }

    /// Whether or not MDC is supported.
    pub fn supports_mdc(&self) -> bool {
        self.mdc
    }

    /// Sets whether or not MDC is supported.
    pub fn set_mdc(mut self, v: bool) -> Self {
        self.mdc = v;
        self
    }

    /// Whether or not AEAD is supported.
    ///
    /// This feature is [experimental](../index.html#experimental-features).
    pub fn supports_aead(&self) -> bool {
        self.aead
    }

    /// Sets whether or not AEAD is supported.
    ///
    /// This feature is [experimental](../index.html#experimental-features).
    pub fn set_aead(mut self, v: bool) -> Self {
        self.aead = v;
        self
    }
}

/// Modification Detection (packets 18 and 19).
const FEATURE_FLAG_MDC: u8 = 0x01;

/// AEAD Encrypted Data Packet (packet 20) and version 5 Symmetric-Key
/// Encrypted Session Key Packets (packet 3).
const FEATURE_FLAG_AEAD: u8 = 0x02;

/// Number of bytes with known flags.
const FEATURE_FLAGS_N_KNOWN_BYTES: usize = 1;

#[cfg(any(test, feature = "quickcheck"))]
impl Arbitrary for Features {
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        Self::new(Vec::arbitrary(g))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    quickcheck! {
        fn roundtrip(val: Features) -> bool {
            let q = Features::new(&val.to_vec());
            assert_eq!(val, q);

            // Check that equality ignores padding.
            let mut val_without_padding = val.clone();
            val_without_padding.pad_to = val.unknown.len();
            assert_eq!(val, val_without_padding);

            true
        }
    }
}