proxy_header/
v1.rs

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
use std::io::Write;
use std::net::SocketAddr;
use std::str::from_utf8;
use std::{
    net::{Ipv4Addr, Ipv6Addr},
    str::FromStr,
};

use crate::util::{read_until, AddressFamily};
use crate::{
    Error::{self, *},
    Protocol, ProxiedAddress, ProxyHeader,
};

const MAX_LENGTH: usize = 107;
const GREETING: &[u8] = b"PROXY";

fn parse_addr<T: AddressFamily>(buf: &[u8], pos: &mut usize) -> Result<T, Error> {
    let Some(address) = read_until(&buf[*pos..], b' ') else {
        return Err(BufferTooShort);
    };

    let addr = from_utf8(address)
        .map_err(|_| Invalid)
        .and_then(|s| T::from_str(s).map_err(|_| Invalid))?;
    *pos += address.len() + 1;

    Ok(addr)
}

fn parse_port(buf: &[u8], pos: &mut usize, terminator: u8) -> Result<u16, Error> {
    let Some(port) = read_until(&buf[*pos..], terminator) else {
        return Err(BufferTooShort);
    };

    let p = from_utf8(port)
        .map_err(|_| Invalid)
        .and_then(|s| u16::from_str(s).map_err(|_| Invalid))?;
    *pos += port.len() + 1;

    Ok(p)
}

fn parse_addrs<T: AddressFamily>(buf: &[u8], pos: &mut usize) -> Result<ProxiedAddress, Error> {
    let src_addr: T = parse_addr(buf, pos)?;
    let dst_addr: T = parse_addr(buf, pos)?;
    let src_port = parse_port(buf, pos, b' ')?;
    let dst_port = parse_port(buf, pos, b'\r')?;

    Ok(ProxiedAddress {
        protocol: Protocol::Stream, // v1 header only supports TCP
        source: SocketAddr::new(src_addr.to_ip_addr(), src_port),
        destination: SocketAddr::new(dst_addr.to_ip_addr(), dst_port),
    })
}

fn decode_inner(buf: &[u8]) -> Result<(ProxyHeader, usize), Error> {
    let mut pos = 0;

    if buf.len() < b"PROXY UNKNOWN\r\n".len() {
        // All other valid PROXY headers are longer than this.
        return Err(BufferTooShort);
    }
    if !buf.starts_with(GREETING) {
        return Err(Invalid);
    }
    pos += GREETING.len() + 1;

    let addrs = if buf[pos..].starts_with(b"UNKNOWN") {
        let Some(rest) = read_until(&buf[pos..], b'\r') else {
            return Err(BufferTooShort);
        };
        pos += rest.len() + 1;

        None
    } else {
        let proto = &buf[pos..pos + 5];
        pos += 5;

        match proto {
            b"TCP4 " => Some(parse_addrs::<Ipv4Addr>(buf, &mut pos)?),
            b"TCP6 " => Some(parse_addrs::<Ipv6Addr>(buf, &mut pos)?),
            _ => return Err(Invalid),
        }
    };

    match buf.get(pos) {
        Some(b'\n') => pos += 1,
        None => return Err(BufferTooShort),
        _ => return Err(Invalid),
    }

    Ok((ProxyHeader(addrs, Default::default()), pos))
}

/// Decode a version 1 PROXY header from a buffer.
///
/// Returns the decoded header and the number of bytes consumed from the buffer.
pub fn decode(buf: &[u8]) -> Result<(ProxyHeader, usize), Error> {
    // Guard against a malicious client sending a very long header, since it is a
    // delimited protocol.

    match decode_inner(buf) {
        Err(Error::BufferTooShort) if buf.len() >= MAX_LENGTH => Err(Error::Invalid),
        other => other,
    }
}

pub fn encode<W: Write>(header: &ProxyHeader, writer: &mut W) -> Result<(), Error> {
    if !header.1.is_empty() {
        return Err(V1UnsupportedTlv);
    }
    writer.write_all(GREETING).map_err(|_| BufferTooShort)?;
    writer.write_all(b" ").map_err(|_| BufferTooShort)?;

    match header.0 {
        Some(ProxiedAddress {
            protocol: Protocol::Stream,
            source,
            destination,
        }) => match (source, destination) {
            (SocketAddr::V4(src), SocketAddr::V4(dst)) => {
                write!(
                    writer,
                    "TCP4 {} {} {} {}\r\n",
                    src.ip(),
                    dst.ip(),
                    src.port(),
                    dst.port()
                )
                .map_err(|_| BufferTooShort)?;
            }
            (SocketAddr::V6(src), SocketAddr::V6(dst)) => {
                write!(
                    writer,
                    "TCP6 {} {} {} {}\r\n",
                    src.ip(),
                    dst.ip(),
                    src.port(),
                    dst.port()
                )
                .map_err(|_| BufferTooShort)?;
            }
            _ => return Err(AddressFamilyMismatch),
        },
        None => {
            writer
                .write_all(b"UNKNOWN\r\n")
                .map_err(|_| BufferTooShort)?;
        }
        _ => return Err(V1UnsupportedProtocol),
    }

    Ok(())
}

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

    use super::*;

    #[test]
    fn test_encode_local() {
        let mut buf = [0u8; 1024];
        let header = ProxyHeader::with_local();

        let len = header.encode_to_slice_v1(&mut buf).unwrap();
        assert_eq!(&buf[..len], b"PROXY UNKNOWN\r\n");

        let decoded = decode(&buf).unwrap();
        assert_eq!(decoded.0, header);
        assert_eq!(decoded.1, len);
    }

    #[test]
    fn test_encode_ipv4() {
        let mut buf = [0u8; 1024];
        let header = ProxyHeader::with_address(ProxiedAddress {
            protocol: Protocol::Stream,
            source: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234)),
            destination: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(8, 8, 4, 4), 5678)),
        });

        let len = header.encode_to_slice_v1(&mut buf).unwrap();
        assert_eq!(&buf[..len], b"PROXY TCP4 127.0.0.1 8.8.4.4 1234 5678\r\n");

        let decoded = decode(&buf).unwrap();
        assert_eq!(decoded.0, header);
        assert_eq!(decoded.1, len);
    }

    #[test]
    fn test_encode_ipv6() {
        let mut buf = [0u8; 1024];
        let header = ProxyHeader::with_address(ProxiedAddress {
            protocol: Protocol::Stream,
            source: SocketAddr::V6(SocketAddrV6::new(
                Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1),
                1234,
                0,
                0,
            )),
            destination: SocketAddr::V6(SocketAddrV6::new(
                Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
                5678,
                0,
                0,
            )),
        });

        let len = header.encode_to_slice_v1(&mut buf).unwrap();
        assert_eq!(&buf[..len], b"PROXY TCP6 2001:db8::1 ::1 1234 5678\r\n");

        let decoded = decode(&buf).unwrap();
        assert_eq!(decoded.0, header);
        assert_eq!(decoded.1, len);
    }

    #[test]
    fn test_tlvs() {
        let mut buf = [0u8; 1024];
        let mut header = ProxyHeader::with_local();
        header.append_tlv(crate::Tlv::Noop(10));

        assert_eq!(header.encode_to_slice_v1(&mut buf), Err(V1UnsupportedTlv));
    }

    #[test]
    fn test_family_mismatch() {
        let mut buf = [0u8; 1024];
        let header = ProxyHeader::with_address(ProxiedAddress {
            protocol: Protocol::Stream,
            source: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234)),
            destination: SocketAddr::V6(SocketAddrV6::new(
                Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
                5678,
                0,
                0,
            )),
        });

        assert_eq!(
            header.encode_to_slice_v1(&mut buf),
            Err(AddressFamilyMismatch)
        );
    }

    #[test]
    fn test_buffer_too_short() {
        let mut buf = [0u8; 1024];
        let header = ProxyHeader::with_address(ProxiedAddress {
            protocol: Protocol::Stream,
            source: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234)),
            destination: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(8, 8, 4, 4), 5678)),
        });

        assert_eq!(
            header.encode_to_slice_v1(&mut buf[0..10]),
            Err(BufferTooShort)
        );
    }
}