Add support for the Forwarded HTTP header

This is the standard replacing X-Forwarded-*.
This commit is contained in:
Simon Ser 2021-03-18 12:08:25 +01:00
parent 5b7205c9c1
commit 9046fda283

View File

@ -3,6 +3,7 @@ package soju
import ( import (
"fmt" "fmt"
"log" "log"
"mime"
"net" "net"
"net/http" "net/http"
"strings" "strings"
@ -214,11 +215,26 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Only trust X-Forwarded-* header fields if this is a trusted proxy IP // Only trust X-Forwarded-* header fields if this is a trusted proxy IP
// to prevent users from spoofing the remote address // to prevent users from spoofing the remote address
remoteAddr := req.RemoteAddr remoteAddr := req.RemoteAddr
if isProxy {
forwarded := parseForwarded(req.Header)
forwardedHost := req.Header.Get("X-Forwarded-For") forwardedHost := req.Header.Get("X-Forwarded-For")
forwardedPort := req.Header.Get("X-Forwarded-Port") forwardedPort := req.Header.Get("X-Forwarded-Port")
if isProxy && forwardedHost != "" && forwardedPort != "" { if forwarded["for"] != "" && forwarded["port"] != "" {
remoteAddr = net.JoinHostPort(forwarded["for"], forwarded["port"])
} else if forwardedHost != "" && forwardedPort != "" {
remoteAddr = net.JoinHostPort(forwardedHost, forwardedPort) remoteAddr = net.JoinHostPort(forwardedHost, forwardedPort)
} }
}
s.handle(newWebsocketIRCConn(conn, remoteAddr)) s.handle(newWebsocketIRCConn(conn, remoteAddr))
} }
func parseForwarded(h http.Header) map[string]string {
forwarded := h.Get("Forwarded")
if forwarded == "" {
return nil
}
// Hack to easily parse header parameters
_, params, _ := mime.ParseMediaType("hack; " + forwarded)
return params
}