Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Handshake::forwarded_addr() to get a trusted forwarded address #295

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,32 @@ impl Handshake {
}
}))
}

/// Get a forwarded IP address of the remote connection.
///
/// This is the preferred method of obtaining the client's trusted IP address.
/// It will attempt to retrieve the forwarded IP address for `trusted` depth
/// of reverse-proxies based on request headers, `trusted=0` returns the direct
/// address of the peer.
///
/// # Note
/// This assumes that the peer is a client. If you are implementing a
/// WebSocket client and want to obtain the address of the server, use
/// `Handshake::peer_addr` instead.
///
/// This method does not ensure that the address is a valid IP address.
#[allow(dead_code)]
fn forwarded_addr(&self, trusted: usize) -> Result<Option<String>> {
Comment on lines +124 to +125

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function would be helpful, if it was accessible.

Github stops me from suggesting, so I just write it out.
The #[allow(dead_code)] is not nessesary when the function gets a pub

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is modelled exactly along the existing functions and API. I'd rather have this merged with no fuss than propose an new API.

if trusted == 0 {
if let Some(addr) = self.peer_addr {
Ok(Some(addr.ip().to_string()))
} else {
Ok(None)
}
} else {
Ok(self.request.forwarded_addr(trusted)?.map(String::from))
}
}
}

/// The handshake request.
Expand Down Expand Up @@ -323,6 +349,45 @@ impl Request {
Ok(None)
}

/// Get the trusted IP address of the client.
///
/// This method will attempt to retrieve a specific forwarded IP address of the requester
/// in the following manner:
///
/// If the `X-Forwarded-For` header exists, this method will return the `trusted` right most

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should not it say "left most address", or I am understanding it wrong ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The n'th (with n=trusted) address from the right end. Usually an address farther to the left (front) can't be trusted -- it's an arbitrary value from a proxy /client farther away from the server. E.g. if I only trust my own proxy, I want the last (right most) entry.

If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#Directives

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huge thanks for the explanation. Also, I must be blind, cos I did not notice rsplit instead of split. So, apologies, my bad.

/// address in the list.
///
/// If the [Forwarded HTTP Header Field](https://tools.ietf.org/html/rfc7239) exits,
/// this method will return the `trusted` right most address indicated by the `for` parameter,
/// if it exists.
///
/// # Note
/// This method does not ensure that the address is a valid IP address.
#[allow(dead_code)]
fn forwarded_addr(&self, trusted: usize) -> Result<Option<&str>> {
if trusted == 0 {
return Ok(None);
}
if let Some(x_forward) = self.header("x-forwarded-for") {
return Ok(from_utf8(x_forward)?.rsplit(',').nth(trusted - 1));
}

// We only care about the first forwarded header, so header is ok
if let Some(forward) = self.header("forwarded") {
if let Some(_for) = from_utf8(forward)?
.split(';')
.find(|f| f.trim().starts_with("for"))
{
if let Some(_for_eq) = _for.trim().rsplit(',').nth(trusted - 1) {
let mut it = _for_eq.split('=');
it.next();
return Ok(it.next());
}
}
}
Ok(None)
}

/// Attempt to parse an HTTP request from a buffer. If the buffer does not contain a complete
/// request, this will return `Ok(None)`.
pub fn parse(buf: &[u8]) -> Result<Option<Request>> {
Expand Down