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
//! # The HAProxy PROXY protocol.
//!
//! This defines a library to serialize and deserialize HAProxy PROXY-protocol
//! headers.
//!
//! The protocol has been implemented per the specification available here:
//! <https://www.haproxy.org/download/2.4/doc/proxy-protocol.txt>

#![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
#![warn(clippy::all)]

pub mod version1;
pub mod version2;

use bytes::{Buf, BytesMut};
use snafu::{ensure, ResultExt as _, Snafu};

#[derive(Debug, Snafu)]
#[cfg_attr(not(feature = "always_exhaustive"), non_exhaustive)] // A new version may be added
#[cfg_attr(test, derive(PartialEq, Eq))]
pub enum ParseError {
    /// This is not a PROXY header at all.
    #[snafu(display("the given data is not a PROXY header"))]
    NotProxyHeader,

    /// This version of the PROXY protocol is unsupported or impossible.
    #[snafu(display("the version {} is invalid", version))]
    InvalidVersion { version: u32 },

    /// An error occurred while parsing version 1.
    #[snafu(display("there was an error while parsing the v1 header: {}", source))]
    Version1 { source: version1::ParseError },

    /// An error occurred while parsing version 2.
    #[snafu(display("there was an error while parsing the v2 header: {}", source))]
    Version2 { source: version2::ParseError },
}

#[derive(Debug, Snafu)]
#[cfg_attr(not(feature = "always_exhaustive"), non_exhaustive)] // A new version may be added
pub enum EncodeError {
    /// An error occurred while encoding version 1.
    #[snafu(display("there was an error while encoding the v1 header: {}", source))]
    WriteVersion1 { source: version1::EncodeError },
}

/// The PROXY header emitted at most once at the start of a new connection.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(feature = "always_exhaustive"), non_exhaustive)] // A new version may be added
pub enum ProxyHeader {
    /// This defines the first version specification, known as the
    /// "human-readable header format" (section 2.1), and consists of (at most)
    /// 107 bytes of data on the wire.
    Version1 {
        /// The addresses used to connect to the proxy.
        addresses: version1::ProxyAddresses,
    },

    /// This defines the second version specification, known as the
    /// "binary header format" (section 2.2), and consists of a dynamic amount
    /// of bytes on the wire, depending on what information the sender wishes to
    /// convey.
    Version2 {
        /// The command of this header.
        command: version2::ProxyCommand,

        /// The protocol over which the information was transferred originally.
        transport_protocol: version2::ProxyTransportProtocol,

        /// The addresses used to connect to the proxy.
        addresses: version2::ProxyAddresses,
    },
}

fn parse_version(buf: &mut impl Buf) -> Result<u32, ParseError> {
    // There is a 6 byte header to v1, 12 byte to all binary versions.
    ensure!(buf.remaining() >= 6, NotProxyHeader);

    // V1 is the only version that starts with "PROXY" (0x50 0x52 0x4F 0x58
    // 0x59), and we can therefore decide version based on that.
    //
    // We use ::chunk to not advance any bytes unnecessarily.
    if buf.chunk()[..6] == [b'P', b'R', b'O', b'X', b'Y', b' '] {
        buf.advance(6);
        return Ok(1);
    }

    // Now we require 13: 12 for the prefix, 1 for the version + command
    ensure!(buf.remaining() >= 13, NotProxyHeader);
    ensure!(
        buf.chunk()[..12]
            == [0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A],
        NotProxyHeader
    );
    buf.advance(12);

    // Note that we will now not advance the version byte on purpose, as it also
    // contains the command.
    //
    // PANIC: This is safe because we've already checked we had 13 bytes
    // available to us above, and we've only read 12 so far.
    let version = buf.chunk()[0];

    // Excerpt:
    //
    // > The next byte (the 13th one) is the protocol version and command.
    // >
    // > The highest four bits contains the version. As of this specification,
    // > it must always be sent as \x2 and the receiver must only accept this
    // > value.
    let version = version >> 4;

    // Interesting edge-case! This is the only time version 1 would be invalid.
    if version == 1 {
        return InvalidVersion { version: 1u32 }.fail();
    }

    Ok(version as u32)
}

/// Parse a PROXY header from the given buffer.
///
/// NOTE: The buffer must have a continuous representation of the inner data
/// available through [Buf::chunk], at the very least for the header. Data that
/// follows may be chunked as you wish.
pub fn parse(buf: &mut impl Buf) -> Result<ProxyHeader, ParseError> {
    let version = match parse_version(buf) {
        Ok(ver) => ver,
        Err(e) => return Err(e),
    };

    Ok(match version {
        1 => self::version1::parse(buf).context(Version1)?,
        2 => self::version2::parse(buf).context(Version2)?,
        _ => return InvalidVersion { version }.fail(),
    })
}

/// Encodes a PROXY header from the given header definition.
///
/// This will perform heap allocations; they're kept to a minimum, but there is
/// no guarantee there will be only one.
pub fn encode(header: ProxyHeader) -> Result<BytesMut, EncodeError> {
    Ok(match header {
        ProxyHeader::Version1 { addresses, .. } => {
            version1::encode(addresses).context(WriteVersion1)?
        }
        ProxyHeader::Version2 {
            command,
            transport_protocol,
            addresses,
        } => version2::encode(command, transport_protocol, addresses),

        #[allow(unreachable_patterns)] // May be required to be exhaustive.
        _ => unimplemented!("Unimplemented version?"),
    })
}

#[cfg(test)]
mod parse_tests {
    use super::*;
    use crate::ProxyHeader;
    use bytes::Bytes;
    use pretty_assertions::assert_eq;
    use rand::prelude::*;
    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};

    #[test]
    fn test_version1() {
        let unknown = Ok(ProxyHeader::Version1 {
            addresses: version1::ProxyAddresses::Unknown,
        });
        assert_eq!(parse(&mut &b"PROXY UNKNOWN\r\n"[..]), unknown);
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN this is bogus data!\r\r\r\n"[..]),
            unknown,
        );
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN 192.168.0.1 192.168.1.1 123 321\r\n"[..]),
            unknown,
        );

        let mut random = [0u8; 128];
        rand::thread_rng().fill_bytes(&mut random);
        let mut header = b"PROXY UNKNOWN ".to_vec();
        header.extend(&random[..]);
        header.extend(b"\r\n");
        let mut buf = Bytes::from(header);
        assert_eq!(parse(&mut buf), unknown);
        assert!(!buf.has_remaining()); // Consume the ENTIRE header!

        fn valid_v4(
            (a, b, c, d): (u8, u8, u8, u8),
            e: u16,
            (f, g, h, i): (u8, u8, u8, u8),
            j: u16,
        ) -> ProxyHeader {
            ProxyHeader::Version1 {
                addresses: version1::ProxyAddresses::Ipv4 {
                    source: SocketAddrV4::new(Ipv4Addr::new(a, b, c, d), e),
                    destination: SocketAddrV4::new(Ipv4Addr::new(f, g, h, i), j),
                },
            }
        }

        assert_eq!(
            parse(&mut &b"PROXY TCP4 192.168.201.102 1.2.3.4 0 65535\r\n"[..]),
            Ok(valid_v4((192, 168, 201, 102), 0, (1, 2, 3, 4), 65535)),
        );
        assert_eq!(
            parse(&mut &b"PROXY TCP4 0.0.0.0 0.0.0.0 0 0\r\n"[..]),
            Ok(valid_v4((0, 0, 0, 0), 0, (0, 0, 0, 0), 0)),
        );
        assert_eq!(
            parse(&mut &b"PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n"[..]),
            Ok(valid_v4(
                (255, 255, 255, 255),
                65535,
                (255, 255, 255, 255),
                65535,
            )),
        );

        fn valid_v6(
            (a, b, c, d, e, f, g, h): (u16, u16, u16, u16, u16, u16, u16, u16),
            i: u16,
            (j, k, l, m, n, o, p, q): (u16, u16, u16, u16, u16, u16, u16, u16),
            r: u16,
        ) -> ProxyHeader {
            ProxyHeader::Version1 {
                addresses: version1::ProxyAddresses::Ipv6 {
                    source: SocketAddrV6::new(Ipv6Addr::new(a, b, c, d, e, f, g, h), i, 0, 0),
                    destination: SocketAddrV6::new(Ipv6Addr::new(j, k, l, m, n, o, p, q), r, 0, 0),
                },
            }
        }
        assert_eq!(
            parse(&mut &b"PROXY TCP6 ab:ce:ef:01:23:45:67:89 ::1 0 65535\r\n"[..]),
            Ok(valid_v6(
                (0xAB, 0xCE, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89),
                0,
                (0, 0, 0, 0, 0, 0, 0, 1),
                65535,
            )),
        );
        assert_eq!(
            parse(&mut &b"PROXY TCP6 :: :: 0 0\r\n"[..]),
            Ok(valid_v6(
                (0, 0, 0, 0, 0, 0, 0, 0),
                0,
                (0, 0, 0, 0, 0, 0, 0, 0),
                0,
            )),
        );
        assert_eq!(
            parse(
                &mut &b"PROXY TCP6 ff:ff:ff:ff:ff:ff:ff:ff ff:ff:ff:ff:ff:ff:ff:ff 65535 65535\r\n"
                    [..],
            ),
            Ok(valid_v6(
                (0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
                65535,
                (0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
                65535,
            )),
        );

        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN \r"[..]),
            Err(ParseError::Version1 {
                source: version1::ParseError::UnexpectedEof,
            }),
        );
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN \r\t\t\r"[..]),
            Err(ParseError::Version1 {
                source: version1::ParseError::UnexpectedEof,
            }),
        );
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN\r\r\r\r\rHello, world!"[..]),
            Err(ParseError::Version1 {
                source: version1::ParseError::UnexpectedEof,
            }),
        );
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN\nGET /index.html HTTP/1.0"[..]),
            Err(ParseError::Version1 {
                source: version1::ParseError::UnexpectedEof,
            }),
        );
        assert_eq!(
            parse(&mut &b"PROXY UNKNOWN\n"[..]),
            Err(ParseError::Version1 {
                source: version1::ParseError::UnexpectedEof,
            }),
        );
    }

    #[test]
    fn test_version2() {
        const PREFIX_LOCAL: [u8; 13] = [
            0x0D,
            0x0A,
            0x0D,
            0x0A,
            0x00,
            0x0D,
            0x0A,
            0x51,
            0x55,
            0x49,
            0x54,
            0x0A,
            (2 << 4) | 0,
        ];
        const PREFIX_PROXY: [u8; 13] = [
            0x0D,
            0x0A,
            0x0D,
            0x0A,
            0x00,
            0x0D,
            0x0A,
            0x51,
            0x55,
            0x49,
            0x54,
            0x0A,
            (2 << 4) | 1,
        ];

        assert_eq!(
            parse(&mut [&PREFIX_LOCAL[..], &[0u8; 16][..]].concat().as_slice()),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Local,
                addresses: version2::ProxyAddresses::Unspec,
                transport_protocol: version2::ProxyTransportProtocol::Unspec,
            }),
        );
        assert_eq!(
            parse(&mut [&PREFIX_PROXY[..], &[0u8; 16][..]].concat().as_slice()),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Proxy,
                addresses: version2::ProxyAddresses::Unspec,
                transport_protocol: version2::ProxyTransportProtocol::Unspec,
            }),
        );

        assert_eq!(
            parse(
                &mut [
                    &PREFIX_PROXY[..],
                    &[
                        // Inet << 4 | Stream
                        (1 << 4) | 1,
                        // Length beyond this: 12
                        // Let's throw in a TLV with no data; 3 bytes.
                        0,
                        15,
                        // Source IP
                        127,
                        0,
                        0,
                        1,
                        // Destination IP
                        192,
                        168,
                        0,
                        1,
                        // Source port
                        // 65535 = [255, 255]
                        255,
                        255,
                        // Destination port
                        // 257 = [1, 1]
                        1,
                        1,
                        // TLV
                        69,
                        0,
                        0,
                    ][..]
                ]
                .concat()
                .as_slice(),
            ),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Proxy,
                transport_protocol: version2::ProxyTransportProtocol::Stream,
                addresses: version2::ProxyAddresses::Ipv4 {
                    source: SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 65535),
                    destination: SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 257),
                },
            })
        );

        let mut data = Bytes::from(
            [
                &PREFIX_LOCAL[..],
                &[
                    // Inet << 4 | Datagram
                    (1 << 4) | 2,
                    // Length beyond this: 12
                    0,
                    12,
                    // Source IP
                    0,
                    0,
                    0,
                    0,
                    // Destination IP
                    255,
                    255,
                    255,
                    255,
                    // Source port
                    0,
                    0,
                    // Destination port
                    255,
                    0,
                    // Extra data
                    1,
                    2,
                    3,
                    4,
                ][..],
            ]
            .concat(),
        );
        assert_eq!(
            parse(&mut data),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Local,
                transport_protocol: version2::ProxyTransportProtocol::Datagram,
                addresses: version2::ProxyAddresses::Ipv4 {
                    source: SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0),
                    destination: SocketAddrV4::new(Ipv4Addr::new(255, 255, 255, 255), 255 << 8),
                },
            })
        );
        assert!(data.remaining() == 4); // Consume the entire header

        assert_eq!(
            parse(
                &mut [
                    &PREFIX_PROXY[..],
                    &[
                        // Inet6 << 4 | Datagram
                        (2 << 4) | 2,
                        // Length beyond this: 12
                        // Let's throw in a TLV with no data; 3 bytes.
                        0,
                        39,
                        // Source IP
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        255,
                        // Destination IP
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        // Source port
                        // 65535 = [255, 255]
                        255,
                        255,
                        // Destination port
                        // 257 = [1, 1]
                        1,
                        1,
                        // TLV
                        69,
                        0,
                        0,
                    ][..],
                ]
                .concat()
                .as_slice(),
            ),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Proxy,
                transport_protocol: version2::ProxyTransportProtocol::Datagram,
                addresses: version2::ProxyAddresses::Ipv6 {
                    source: SocketAddrV6::new(
                        Ipv6Addr::new(65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535),
                        65535,
                        0,
                        0,
                    ),
                    destination: SocketAddrV6::new(
                        Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0),
                        257,
                        0,
                        0,
                    )
                },
            })
        );

        let mut data = Bytes::from(
            [
                &PREFIX_LOCAL[..],
                &[
                    // Inet6 << 4 | Stream
                    (2 << 4) | 1,
                    // Length beyond this: 12
                    0,
                    36,
                    // Source IP
                    81,
                    92,
                    0,
                    52,
                    83,
                    12,
                    255,
                    68,
                    19,
                    5,
                    111,
                    200,
                    54,
                    90,
                    55,
                    66,
                    // Destination IP
                    255,
                    255,
                    255,
                    255,
                    0,
                    0,
                    0,
                    0,
                    123,
                    123,
                    69,
                    69,
                    21,
                    21,
                    42,
                    42,
                    // Source port
                    123,
                    0,
                    // Destination port
                    255,
                    255,
                    // Extra data
                    1,
                    2,
                    3,
                    4,
                ][..],
            ]
            .concat(),
        );
        assert_eq!(
            parse(&mut data),
            Ok(ProxyHeader::Version2 {
                command: version2::ProxyCommand::Local,
                transport_protocol: version2::ProxyTransportProtocol::Stream,
                addresses: version2::ProxyAddresses::Ipv6 {
                    source: SocketAddrV6::new(
                        Ipv6Addr::new(20828, 52, 21260, 65348, 4869, 28616, 13914, 14146),
                        31488,
                        0,
                        0,
                    ),
                    destination: SocketAddrV6::new(
                        Ipv6Addr::new(65535, 65535, 0, 0, 31611, 17733, 5397, 10794),
                        65535,
                        0,
                        0,
                    ),
                },
            })
        );
        assert!(data.remaining() == 4); // Consume the entire header

        let mut data = [0u8; 200];
        rand::thread_rng().fill_bytes(&mut data);
        data[0] = 99; // Make 100% sure it's invalid.
        assert!(parse(&mut &data[..]).is_err());

        assert_eq!(
            parse(&mut &PREFIX_LOCAL[..]),
            Err(ParseError::Version2 {
                source: version2::ParseError::UnexpectedEof,
            }),
        );

        assert_eq!(
            parse(
                &mut [
                    &PREFIX_PROXY[..],
                    &[
                        // Inet << 4 | Stream
                        (1 << 4) | 1,
                        // Length beyond this: 12
                        // 3 bytes is clearly too few if we expect 2 IPv4s and ports
                        0,
                        3,
                    ][..],
                ]
                .concat()
                .as_slice(),
            ),
            Err(ParseError::Version2 {
                source: version2::ParseError::InsufficientLengthSpecified {
                    given: 3,
                    needs: 4 * 2 + 2 * 2,
                },
            }),
        );
    }

    #[test]
    fn test_unknown_version() {
        assert_eq!(
            parse_version(
                &mut &[
                    0x0D,
                    0x0A,
                    0x0D,
                    0x0A,
                    0x00,
                    0x0D,
                    0x0A,
                    0x51,
                    0x55,
                    0x49,
                    0x54,
                    0x0A,
                    1 << 4, // Version goes in upper half of the byte
                ][..],
            ),
            Err(ParseError::InvalidVersion { version: 1 }),
        );
    }

    #[test]
    fn test_version_parsing_correct() {
        assert_eq!(
            parse_version(&mut &[b'P', b'R', b'O', b'X', b'Y', b' '][..]),
            Ok(1),
        );
        assert_eq!(
            parse_version(
                &mut &[
                    0x0D,
                    0x0A,
                    0x0D,
                    0x0A,
                    0x00,
                    0x0D,
                    0x0A,
                    0x51,
                    0x55,
                    0x49,
                    0x54,
                    0x0A,
                    15 << 4, // Version goes in upper half of the byte
                ][..],
            ),
            Ok(15),
        );
    }

    #[test]
    fn test_version_parsing_errors() {
        assert_eq!(
            parse_version(&mut &b"Proximyst"[..]),
            Err(ParseError::NotProxyHeader)
        );
    }
}