jkipsec 0.1.0

Userspace IKEv2/IPsec VPN responder for terminating iOS VPN tunnels and exposing the inner IP traffic. Pairs with jktcp for a fully userspace TCP/IP stack.
Documentation
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
//! Security Association payload (RFC 7296 §3.3) - proposals and transforms.
//!
//! Layout:
//!
//! ```text
//!   SA payload  = one or more Proposal substructures
//!   Proposal    = (last|reserved|length|num|protocol|spi_size|num_xforms|spi|transforms*)
//!   Transform   = (last|reserved|length|type|reserved|id|attributes*)
//!   Attribute   = (af|type|length-or-value|value*)
//! ```
//!
//! We keep the structure as plain owned data so the caller can hold it past
//! the lifetime of the original packet (we don't need to since key derivation
//! reads from `Message::raw`, but it makes ownership simpler).

#![allow(missing_docs)]

use super::ParseError;

/// Protocol Identifier values (RFC 7296 §3.3.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolId {
    Ike, // 1
    Ah,  // 2
    Esp, // 3
    Other(u8),
}

impl ProtocolId {
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Ike,
            2 => Self::Ah,
            3 => Self::Esp,
            other => Self::Other(other),
        }
    }
    pub fn as_u8(self) -> u8 {
        match self {
            Self::Ike => 1,
            Self::Ah => 2,
            Self::Esp => 3,
            Self::Other(v) => v,
        }
    }
}

/// Transform Type (RFC 7296 §3.3.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransformType {
    Encr,  // 1
    Prf,   // 2
    Integ, // 3
    Dh,    // 4
    Esn,   // 5
    Other(u8),
}

impl TransformType {
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Encr,
            2 => Self::Prf,
            3 => Self::Integ,
            4 => Self::Dh,
            5 => Self::Esn,
            other => Self::Other(other),
        }
    }
    pub fn as_u8(self) -> u8 {
        match self {
            Self::Encr => 1,
            Self::Prf => 2,
            Self::Integ => 3,
            Self::Dh => 4,
            Self::Esn => 5,
            Self::Other(v) => v,
        }
    }
}

/// Transform attribute. The IKEv2 attribute format is borrowed from IKEv1:
///
/// ```text
///   AF=1 (TV): 1 bit AF | 15-bit type | 16-bit value
///   AF=0 (TLV): 1 bit AF | 15-bit type | 16-bit length | <length> bytes value
/// ```
///
/// In practice, only `Key Length` (type 14) appears in real traffic, and it's
/// always TV-encoded.
#[derive(Debug, Clone)]
pub struct Attribute {
    pub attr_type: u16,
    pub value: AttrValue,
}

#[derive(Debug, Clone)]
pub enum AttrValue {
    /// 16-bit value carried inline in the AF=1 form.
    Tv(u16),
    /// Variable-length value carried in the AF=0 form.
    Tlv(Vec<u8>),
}

impl Attribute {
    pub const KEY_LENGTH: u16 = 14;

    /// Parse one attribute from `bytes`. Returns the attribute and the number
    /// of bytes consumed.
    fn parse(bytes: &[u8]) -> Result<(Self, usize), ParseError> {
        if bytes.len() < 4 {
            return Err(ParseError::Truncated {
                what: "transform attribute",
                need: 4,
                got: bytes.len(),
            });
        }
        let af_and_type = u16::from_be_bytes([bytes[0], bytes[1]]);
        let attr_type = af_and_type & 0x7FFF;
        let af = af_and_type & 0x8000 != 0;
        if af {
            let value = u16::from_be_bytes([bytes[2], bytes[3]]);
            Ok((
                Self {
                    attr_type,
                    value: AttrValue::Tv(value),
                },
                4,
            ))
        } else {
            let len = u16::from_be_bytes([bytes[2], bytes[3]]) as usize;
            let total = 4 + len;
            if bytes.len() < total {
                return Err(ParseError::Truncated {
                    what: "TLV attribute body",
                    need: total,
                    got: bytes.len(),
                });
            }
            Ok((
                Self {
                    attr_type,
                    value: AttrValue::Tlv(bytes[4..total].to_vec()),
                },
                total,
            ))
        }
    }

    pub fn write_into(&self, out: &mut Vec<u8>) {
        match &self.value {
            AttrValue::Tv(v) => {
                out.extend_from_slice(&(self.attr_type | 0x8000).to_be_bytes());
                out.extend_from_slice(&v.to_be_bytes());
            }
            AttrValue::Tlv(b) => {
                out.extend_from_slice(&(self.attr_type & 0x7FFF).to_be_bytes());
                out.extend_from_slice(&(b.len() as u16).to_be_bytes());
                out.extend_from_slice(b);
            }
        }
    }

    pub fn encoded_len(&self) -> usize {
        match &self.value {
            AttrValue::Tv(_) => 4,
            AttrValue::Tlv(b) => 4 + b.len(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Transform {
    pub transform_type: TransformType,
    pub transform_id: u16,
    pub attributes: Vec<Attribute>,
}

impl Transform {
    /// Convenience: the negotiated key length attribute, if present.
    pub fn key_length(&self) -> Option<u16> {
        self.attributes.iter().find_map(|a| {
            if a.attr_type == Attribute::KEY_LENGTH
                && let AttrValue::Tv(v) = a.value
            {
                return Some(v);
            }
            None
        })
    }

    /// Parse one transform substructure from `bytes`. Returns the transform,
    /// `last_substruc` (0=last, 3=more), and bytes consumed.
    fn parse(bytes: &[u8]) -> Result<(Self, u8, usize), ParseError> {
        if bytes.len() < 8 {
            return Err(ParseError::Truncated {
                what: "transform header",
                need: 8,
                got: bytes.len(),
            });
        }
        let last = bytes[0];
        let length = u16::from_be_bytes([bytes[2], bytes[3]]) as usize;
        if length < 8 || bytes.len() < length {
            return Err(ParseError::Truncated {
                what: "transform body",
                need: length,
                got: bytes.len(),
            });
        }
        let transform_type = TransformType::from_u8(bytes[4]);
        let transform_id = u16::from_be_bytes([bytes[6], bytes[7]]);

        let mut attrs = Vec::new();
        let mut cur = 8;
        while cur < length {
            let (attr, used) = Attribute::parse(&bytes[cur..length])?;
            attrs.push(attr);
            cur += used;
        }

        Ok((
            Self {
                transform_type,
                transform_id,
                attributes: attrs,
            },
            last,
            length,
        ))
    }

    /// Serialise this transform with the given `last_substruc` marker
    /// (3 = more transforms follow, 0 = last).
    pub fn write_into(&self, out: &mut Vec<u8>, last_substruc: u8) {
        let attr_len: usize = self.attributes.iter().map(|a| a.encoded_len()).sum();
        let total = 8 + attr_len;
        out.push(last_substruc);
        out.push(0); // reserved
        out.extend_from_slice(&(total as u16).to_be_bytes());
        out.push(self.transform_type.as_u8());
        out.push(0); // reserved
        out.extend_from_slice(&self.transform_id.to_be_bytes());
        for a in &self.attributes {
            a.write_into(out);
        }
    }
}

#[derive(Debug, Clone)]
pub struct Proposal {
    pub proposal_num: u8,
    pub protocol: ProtocolId,
    /// SPI (empty for IKE_SA_INIT, 4 bytes for ESP/AH).
    pub spi: Vec<u8>,
    pub transforms: Vec<Transform>,
}

impl Proposal {
    /// Parse one proposal substructure from `bytes`. Returns the proposal,
    /// `last_substruc` (0=last, 2=more), and bytes consumed.
    fn parse(bytes: &[u8]) -> Result<(Self, u8, usize), ParseError> {
        if bytes.len() < 8 {
            return Err(ParseError::Truncated {
                what: "proposal header",
                need: 8,
                got: bytes.len(),
            });
        }
        let last = bytes[0];
        let length = u16::from_be_bytes([bytes[2], bytes[3]]) as usize;
        let proposal_num = bytes[4];
        let protocol = ProtocolId::from_u8(bytes[5]);
        let spi_size = bytes[6] as usize;
        let num_xforms = bytes[7] as usize;

        if length < 8 + spi_size || bytes.len() < length {
            return Err(ParseError::Truncated {
                what: "proposal body",
                need: length,
                got: bytes.len(),
            });
        }
        let spi = bytes[8..8 + spi_size].to_vec();

        let mut transforms = Vec::with_capacity(num_xforms);
        let mut cur = 8 + spi_size;
        for _ in 0..num_xforms {
            if cur >= length {
                return Err(ParseError::BadLength {
                    what: "proposal transforms exceed proposal length",
                    value: length,
                });
            }
            let (xform, _last, used) = Transform::parse(&bytes[cur..length])?;
            transforms.push(xform);
            cur += used;
        }

        Ok((
            Self {
                proposal_num,
                protocol,
                spi,
                transforms,
            },
            last,
            length,
        ))
    }

    pub fn encoded_len(&self) -> usize {
        let xform_len: usize = self
            .transforms
            .iter()
            .map(|t| 8 + t.attributes.iter().map(|a| a.encoded_len()).sum::<usize>())
            .sum();
        8 + self.spi.len() + xform_len
    }

    pub fn write_into(&self, out: &mut Vec<u8>, last_substruc: u8) {
        let total = self.encoded_len();
        out.push(last_substruc);
        out.push(0);
        out.extend_from_slice(&(total as u16).to_be_bytes());
        out.push(self.proposal_num);
        out.push(self.protocol.as_u8());
        out.push(self.spi.len() as u8);
        out.push(self.transforms.len() as u8);
        out.extend_from_slice(&self.spi);
        for (i, t) in self.transforms.iter().enumerate() {
            let last = if i + 1 == self.transforms.len() { 0 } else { 3 };
            t.write_into(out, last);
        }
    }
}

#[derive(Debug, Clone)]
pub struct SaPayload {
    pub proposals: Vec<Proposal>,
}

impl SaPayload {
    pub fn parse(body: &[u8]) -> Result<Self, ParseError> {
        let mut proposals = Vec::new();
        let mut cur = 0;
        loop {
            if cur >= body.len() {
                break;
            }
            let (prop, last, used) = Proposal::parse(&body[cur..])?;
            proposals.push(prop);
            cur += used;
            if last == 0 {
                break;
            }
        }
        Ok(Self { proposals })
    }

    pub fn encoded_len(&self) -> usize {
        self.proposals.iter().map(|p| p.encoded_len()).sum()
    }

    /// Serialise into the *body* of an SA payload (no generic 4-byte payload
    /// header - that's the caller's job).
    pub fn write_body(&self, out: &mut Vec<u8>) {
        for (i, p) in self.proposals.iter().enumerate() {
            let last = if i + 1 == self.proposals.len() { 0 } else { 2 };
            p.write_into(out, last);
        }
    }
}

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

    /// Real SA body from the iOS IKE_SA_INIT (offset 4 in the SA payload).
    const SA_BODY_HEX: &str = "
        02 00 00 2C 01 01 00 04 03 00 00 0C 01 00 00 14
        80 0E 01 00 03 00 00 08 02 00 00 05 03 00 00 08
        06 00 00 24 00 00 00 08 04 00 00 13 02 00 00 2C
        02 01 00 04 03 00 00 0C 01 00 00 14 80 0E 01 00
        03 00 00 08 02 00 00 05 03 00 00 08 06 00 00 24
        00 00 00 08 04 00 00 0E 02 00 00 34 03 01 00 05
        03 00 00 0C 01 00 00 0C 80 0E 01 00 03 00 00 08
        03 00 00 0C 03 00 00 08 02 00 00 05 03 00 00 08
        06 00 00 24 00 00 00 08 04 00 00 13 02 00 00 34
        04 01 00 05 03 00 00 0C 01 00 00 0C 80 0E 01 00
        03 00 00 08 03 00 00 0C 03 00 00 08 02 00 00 05
        03 00 00 08 06 00 00 24 00 00 00 08 04 00 00 0E
        02 00 00 24 05 01 00 03 03 00 00 0C 01 00 00 14
        80 0E 01 00 03 00 00 08 02 00 00 05 00 00 00 08
        04 00 00 13 02 00 00 24 06 01 00 03 03 00 00 0C
        01 00 00 14 80 0E 01 00 03 00 00 08 02 00 00 05
        00 00 00 08 04 00 00 0E 02 00 00 2C 07 01 00 04
        03 00 00 0C 01 00 00 0C 80 0E 01 00 03 00 00 08
        03 00 00 0C 03 00 00 08 02 00 00 05 00 00 00 08
        04 00 00 13 00 00 00 2C 08 01 00 04 03 00 00 0C
        01 00 00 0C 80 0E 01 00 03 00 00 08 03 00 00 0C
        03 00 00 08 02 00 00 05 00 00 00 08 04 00 00 0E
    ";

    fn from_hex(s: &str) -> Vec<u8> {
        s.split_ascii_whitespace()
            .map(|h| u8::from_str_radix(h, 16).unwrap())
            .collect()
    }

    #[test]
    fn parse_real_ios_sa_body() {
        let body = from_hex(SA_BODY_HEX);
        let sa = SaPayload::parse(&body).expect("parse");
        // iOS sends 8 proposals.
        assert_eq!(sa.proposals.len(), 8);
        // Proposal 1: AES-GCM-256 + PRF SHA-256 + DH 19 (P-256) + one extra.
        let p1 = &sa.proposals[0];
        assert_eq!(p1.proposal_num, 1);
        assert_eq!(p1.protocol, ProtocolId::Ike);
        assert_eq!(p1.spi.len(), 0);
        assert_eq!(p1.transforms.len(), 4);
        assert_eq!(p1.transforms[0].transform_type, TransformType::Encr);
        assert_eq!(p1.transforms[0].transform_id, 20); // AES-GCM-16
        assert_eq!(p1.transforms[0].key_length(), Some(256));
        assert_eq!(p1.transforms[1].transform_type, TransformType::Prf);
        assert_eq!(p1.transforms[1].transform_id, 5); // PRF_HMAC_SHA2_256
        // Transforms[2] is the unknown type-6 sentinel iOS includes.
        assert_eq!(p1.transforms[3].transform_type, TransformType::Dh);
        assert_eq!(p1.transforms[3].transform_id, 19); // ECP_256
    }

    #[test]
    fn round_trip_real_ios_sa_body() {
        let body = from_hex(SA_BODY_HEX);
        let sa = SaPayload::parse(&body).expect("parse");
        let mut buf = Vec::new();
        sa.write_body(&mut buf);
        assert_eq!(buf, body);
    }
}