haproxy-protocol 0.0.4

HAProxy Protocol
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
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
use crate::{Address, Command, Protocol, ProxyHdrV1, ProxyHdrV2};
use nom::{Parser, combinator::map_opt, number::streaming::be_u8};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::str::FromStr;
use tracing::debug;

impl Protocol {
    fn new(input: u8) -> Option<Self> {
        match input {
            0x00 | 0x31 | 0x32 => Some(Self::Unspec),
            0x11 => Some(Self::TcpV4),
            0x12 => Some(Self::UdpV4),
            0x21 => Some(Self::TcpV6),
            0x22 => Some(Self::UdpV6),
            // 0x31 => Some(Self::UnixStream),
            // 0x32 => Some(Self::UnixDgram),
            _ => None,
        }
    }
}

impl Command {
    fn new(input: u8) -> Option<Self> {
        match input {
            0x00 => Some(Self::Local),
            0x01 => Some(Self::Proxy),
            _ => None,
        }
    }
}

fn parse_bits(input: &[u8]) -> nom::IResult<&[u8], (u8, Command)> {
    // Turns the thing to bits, then back to bytes, you stuff all your bit parsers in here
    nom::bits::bits::<_, _, nom::error::Error<(&[u8], usize)>, _, _>((
        nom::bits::streaming::tag(0x02, 4usize),
        map_opt(nom::bits::streaming::take(4usize), Command::new),
    ))(input)
}

fn parse_addr_v4(input: &[u8]) -> nom::IResult<&[u8], Address> {
    let (input, src_addr) = nom::number::complete::be_u32(input)?;
    let (input, dst_addr) = nom::number::complete::be_u32(input)?;
    let (input, src_port) = nom::number::complete::be_u16(input)?;
    let (input, dst_port) = nom::number::complete::be_u16(input)?;

    let src = SocketAddrV4::new(Ipv4Addr::from_bits(src_addr), src_port);
    let dst = SocketAddrV4::new(Ipv4Addr::from_bits(dst_addr), dst_port);

    Ok((input, Address::V4 { src, dst }))
}

fn parse_addr_v6(input: &[u8]) -> nom::IResult<&[u8], Address> {
    let (input, src_addr) = nom::number::complete::be_u128(input)?;
    let (input, dst_addr) = nom::number::complete::be_u128(input)?;
    let (input, src_port) = nom::number::complete::be_u16(input)?;
    let (input, dst_port) = nom::number::complete::be_u16(input)?;

    let src = SocketAddrV6::new(Ipv6Addr::from_bits(src_addr), src_port, 0, 0);
    let dst = SocketAddrV6::new(Ipv6Addr::from_bits(dst_addr), dst_port, 0, 0);

    Ok((input, Address::V6 { src, dst }))
}

/// This is the signature that start a v2 proxy protocol header.
const SIGNATURE_V2: &[u8; 12] = b"\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A";

pub(crate) fn parse_proxy_hdr_v2(input_data: &[u8]) -> nom::IResult<&[u8], ProxyHdrV2> {
    let (input, _magic) = nom::bytes::streaming::tag(&SIGNATURE_V2[..])(input_data)
        .inspect_err(|err| debug!(error=%err, "Missing Proxy v2 signature"))?;

    let (input, (version, command)) = parse_bits(input)?;
    if version != 2 {
        debug!(version = version, "Invalid version expected 2");
        return Err(nom::Err::Failure(nom::error::Error {
            input,
            code: nom::error::ErrorKind::Tag,
        }));
    }

    let (input, protocol) = map_opt(be_u8, Protocol::new).parse(input)?;

    let (input, length) = nom::number::streaming::be_u16(input)?;
    let (remainder, input) = nom::bytes::streaming::take(length)(input)?;

    // Parse the address now based on what protocol was chosen.
    // FROM HERE we use bytes complete, because we have everything we need!
    let (_input, address) = match protocol {
        Protocol::Unspec => (input, Address::None),
        Protocol::TcpV4 | Protocol::UdpV4 => parse_addr_v4(input)?,
        Protocol::TcpV6 | Protocol::UdpV6 => parse_addr_v6(input)?,
    };

    Ok((
        remainder,
        ProxyHdrV2 {
            command,
            protocol,
            // length,
            address,
        },
    ))
}

#[cfg(any(feature = "tokio", test))]
pub const V1_MIN_LEN: usize = 32; // `PROXY TCP4 1.1.1.1 2.2.2.2 1 1rn`
pub const V1_MAX_LEN: usize = 107;
const V1_MAX_WORK_LEN: usize = V1_MAX_LEN - 6; // 6 is the length of "PROXY "

fn bytes_to_str(input: &[u8]) -> nom::IResult<&[u8], &str> {
    str::from_utf8(input).map(|s| (input, s)).map_err(|_| {
        nom::Err::Failure(nom::error::Error {
            input,
            code: nom::error::ErrorKind::AlphaNumeric,
        })
    })
}

pub(crate) fn parse_proxy_hdr_v1(input_data: &[u8]) -> nom::IResult<&[u8], ProxyHdrV1> {
    // Do we have the correct header? If not, no point trying to continue.
    let (input_data, _magic) = nom::bytes::streaming::tag("PROXY ")(input_data)
        .inspect_err(|err| debug!(error=%err, "Missing Proxy v1 signature"))?;

    let data_complete = input_data.len() > V1_MAX_WORK_LEN;

    tracing::trace!(?data_complete, ?input_data);

    // First, limit the input data to the maximum length of the header. We have to setup our
    // "return" array here that defines how much data we are actually taking from the input
    let (ignore_crlf, working_data) = if data_complete {
        // Limit the input length.
        let working_data = &input_data[..V1_MAX_WORK_LEN];

        // Note that we use COMPLETE here so that we don't return that we need more data.
        nom::character::complete::not_line_ending(working_data)?
    } else {
        // Note that we use STREAMING here so that we MAY return that we need more data.
        nom::character::streaming::not_line_ending(input_data)?
    };
    // Check that we HAVE the crlf - this is because not line ending also matches on \n.
    let (_excess, ignore_crlf) = if data_complete {
        nom::character::complete::crlf(ignore_crlf)?
    } else {
        nom::character::streaming::crlf(ignore_crlf)?
    };

    // This MUST hold true as both ignore_crlf and working_data are subslices of the
    // original input_data.
    debug_assert!((ignore_crlf.len() + working_data.len()) <= input_data.len());
    // Setup the "remainder" for us to return that indicates where we STOPPED processing
    // bytes. This way higher level callers can advance their buffers properly.
    let remainder = &input_data[(2 + working_data.len())..];

    // THE INPUT IS COMPLETE - don't use the streaming types from this point onward!

    // Now we are looking for one of the protocol indicators.
    let (input, protocol) = nom::bytes::complete::take_till(|c| c == 0x20)(working_data)?;

    let protocol = if protocol == b"UNKNOWN" {
        Protocol::Unspec
    } else if protocol == b"TCP4" {
        Protocol::TcpV4
    } else if protocol == b"TCP6" {
        Protocol::TcpV6
    } else {
        return Err(nom::Err::Failure(nom::error::Error {
            input: protocol,
            code: nom::error::ErrorKind::Tag,
        }));
    };

    // If there are no more bytes, then we are done.
    if input.is_empty() {
        return Ok((
            remainder,
            ProxyHdrV1 {
                protocol,
                address: Address::None,
            },
        ));
    }

    let (input, _discard) = nom::character::complete::space1(input)?;

    let (input, src_addr_bytes) = nom::bytes::complete::take_till(|c| c == 0x20)(input)?;
    let (_ignore, src_addr_str) = bytes_to_str(src_addr_bytes)?;

    let (input, _discard) = nom::character::complete::space1(input)?;

    let (input, dest_addr_bytes) = nom::bytes::complete::take_till(|c| c == 0x20)(input)?;
    let (_ignore, dest_addr_str) = bytes_to_str(dest_addr_bytes)?;

    let (input, _discard) = nom::character::complete::space1(input)?;

    let (input, src_port_bytes) = nom::bytes::complete::take_till(|c| c == 0x20)(input)?;
    let (_ignore, src_port_str) = bytes_to_str(src_port_bytes)?;

    let (dest_port_bytes, _discard) = nom::character::complete::space1(input)?;
    let (_ignore, dest_port_str) = bytes_to_str(dest_port_bytes)?;

    // If we got all the needed bytes and they are valid strs, we now attempt to parse them.

    let src_addr = IpAddr::from_str(src_addr_str).map_err(|_| {
        nom::Err::Failure(nom::error::Error {
            input: src_addr_bytes,
            code: nom::error::ErrorKind::Satisfy,
        })
    })?;

    let src_port = u16::from_str(src_port_str).map_err(|_| {
        nom::Err::Failure(nom::error::Error {
            input: src_port_bytes,
            code: nom::error::ErrorKind::Satisfy,
        })
    })?;

    let dest_addr = IpAddr::from_str(dest_addr_str).map_err(|_| {
        nom::Err::Failure(nom::error::Error {
            input: dest_addr_bytes,
            code: nom::error::ErrorKind::Satisfy,
        })
    })?;

    let dest_port = u16::from_str(dest_port_str).map_err(|_| {
        nom::Err::Failure(nom::error::Error {
            input: dest_port_bytes,
            code: nom::error::ErrorKind::Satisfy,
        })
    })?;

    let src_sock_addr = SocketAddr::new(src_addr, src_port);
    let dest_sock_addr = SocketAddr::new(dest_addr, dest_port);

    let address = match (src_sock_addr, dest_sock_addr) {
        (SocketAddr::V4(src), SocketAddr::V4(dst)) => Address::V4 { src, dst },
        (SocketAddr::V6(src), SocketAddr::V6(dst)) => Address::V6 { src, dst },
        _ => Address::None,
    };

    Ok((remainder, ProxyHdrV1 { protocol, address }))
}

#[cfg(test)]
mod tests {
    use crate::*;
    use std::net::{SocketAddrV4, SocketAddrV6};
    use std::str::FromStr;

    #[test]
    fn request_local() {
        let _ = tracing_subscriber::fmt::try_init();

        let sample =
            hex::decode("0d0a0d0a000d0a515549540a20000007030004a9b87e8f").expect("valid hex");

        let (took, hdr) = ProxyHdrV2::parse(sample.as_slice()).expect("should parse local addr");

        tracing::debug!(?hdr);

        assert_eq!(took, 23);
        assert_eq!(hdr.command, Command::Local);
        assert_eq!(hdr.protocol, Protocol::Unspec);
        assert_eq!(hdr.address, Address::None);
    }

    #[test]
    fn request_proxy_v4() {
        let _ = tracing_subscriber::fmt::try_init();

        let sample = hex::decode("0d0a0d0a000d0a515549540a2111000cac180c76ac180b8fcdcb027d")
            .expect("valid hex");

        let (took, hdr) = ProxyHdrV2::parse(sample.as_slice()).expect("should parse v4 addr");

        tracing::debug!(?hdr);

        assert_eq!(took, 28);
        assert_eq!(hdr.command, Command::Proxy);
        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("172.24.12.118:52683").expect("valid addr"),
                dst: SocketAddrV4::from_str("172.24.11.143:637").expect("valid addr"),
            }
        );
    }

    #[test]
    fn request_proxy_v6() {
        let _ = tracing_subscriber::fmt::try_init();

        let sample = hex::decode("0d0a0d0a000d0a515549540a212100242403580b7d88001200000000000001fe2403580b7d8800110000000000001043d34c027d").expect("valid hex");

        let (took, hdr) = ProxyHdrV2::parse(sample.as_slice()).expect("should parse v6 addr");

        tracing::debug!(?hdr);

        assert_eq!(took, 52);
        assert_eq!(hdr.command, Command::Proxy);
        assert_eq!(hdr.protocol, Protocol::TcpV6);
        assert_eq!(
            hdr.address,
            Address::V6 {
                src: SocketAddrV6::from_str("[2403:580b:7d88:12::1fe]:54092").expect("valid addr"),
                dst: SocketAddrV6::from_str("[2403:580b:7d88:11::1043]:637").expect("valid addr"),
            }
        );
    }

    #[test]
    fn request_proxyv1_v4_basic() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY TCP4 192.24.10.10 10.0.0.0 5789 80\r\nextra_data";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 42);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("192.24.10.10:5789").unwrap(),
                dst: SocketAddrV4::from_str("10.0.0.0:80").unwrap(),
            }
        );
    }
    #[test]
    fn request_proxyv1_v4_basic_nodata() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY TCP4 192.24.10.10 10.0.0.0 5789 80\r\n";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 42);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("192.24.10.10:5789").unwrap(),
                dst: SocketAddrV4::from_str("10.0.0.0:80").unwrap(),
            }
        );
    }

    #[test]
    fn request_proxyv1_v4_max() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n excess";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 56);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("255.255.255.255:65535").unwrap(),
                dst: SocketAddrV4::from_str("255.255.255.255:65535").unwrap(),
            }
        );
    }

    #[test]
    fn request_proxyv1_v6_max() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY TCP6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n more extra data";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 104);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV6);
        assert_eq!(
            hdr.address,
            Address::V6 {
                src: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                    .unwrap(),
                dst: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                    .unwrap(),
            }
        );
    }

    #[test]
    fn request_proxyv1_unknown() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY UNKNOWN\r\n";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 15);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::Unspec);
        assert_eq!(hdr.address, Address::None);
    }

    #[test]
    fn request_proxyv1_v6_unknown() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY UNKNOWN ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n add extra data for luls";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 107);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::Unspec);
        assert_eq!(
            hdr.address,
            Address::V6 {
                src: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                    .unwrap(),
                dst: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                    .unwrap(),
            }
        );
    }

    #[test]
    fn request_proxyv1_incomplete() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY UNKNO";

        let err = ProxyHdrV1::parse(data.as_bytes()).expect_err("Should fail!!!");

        tracing::debug!(?err);
        assert!(matches!(err, Error::Incomplete { .. }));
    }

    #[test]
    fn request_proxyv1_v6_too_long() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY UNKNOWN ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535 too long\r\n";

        let err = ProxyHdrV1::parse(data.as_bytes()).expect_err("Should fail!!!");

        assert!(matches!(err, Error::Invalid));
    }

    #[test]
    fn request_proxyv1_kanidm_4084() {
        let _ = tracing_subscriber::fmt::try_init();

        // hex
        // 50524f585920544350342039312e3232312e3133382e33332039312e3232312e3133382e313036203437373830203633360d0a

        let data = "PROXY TCP4 91.221.138.33 91.221.138.106 47780 636\r\n";

        let (took, hdr) = ProxyHdrV1::parse(data.as_bytes()).unwrap();
        assert_eq!(took, 51);

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("91.221.138.33:47780").unwrap(),
                dst: SocketAddrV4::from_str("91.221.138.106:636").unwrap(),
            }
        );
    }
}