Parse X-Forwarded-For header if provided

Parse the X-Forwarded-For header if it exists in the connection.  This
will allow bans to work if the server is sitting behind an Nginx
reverse proxy (that has been configured to add the header).

Also added a safe-guard to disallow bans for localhost so you cannot
accidentally ban everybody from connecting if the server is behind a
reverse proxy.

This should resolve #49
This commit is contained in:
Zorchenhimer 2019-03-20 16:57:29 -04:00
parent 7164f26f4e
commit f7b362519d
4 changed files with 24 additions and 8 deletions

View File

@ -3,7 +3,6 @@ package main
import (
"fmt"
"html"
"net"
"strings"
"unicode"
@ -150,11 +149,7 @@ func (cl *Client) Unmod() {
}
func (cl *Client) Host() string {
host, _, err := net.SplitHostPort(cl.conn.RemoteAddr().String())
if err != nil {
host = "err"
}
return host
return cl.conn.Host()
}
var dumbSpaces = []string{

View File

@ -1,6 +1,7 @@
package main
import (
"net"
"sync"
"github.com/gorilla/websocket"
@ -8,7 +9,8 @@ import (
type chatConnection struct {
*websocket.Conn
mutex sync.Mutex
mutex sync.Mutex
forwardedFor string
}
func (cc *chatConnection) ReadData(data interface{}) error {
@ -24,3 +26,15 @@ func (cc *chatConnection) WriteData(data interface{}) error {
return cc.WriteJSON(data)
}
func (cc *chatConnection) Host() string {
if len(cc.forwardedFor) > 0 {
return cc.forwardedFor
}
host, _, err := net.SplitHostPort(cc.RemoteAddr().String())
if err != nil {
return cc.RemoteAddr().String()
}
return host
}

View File

@ -96,7 +96,10 @@ func wsHandler(w http.ResponseWriter, r *http.Request) {
}
chatConn := &chatConnection{
Conn: conn,
Conn: conn,
// If the server is behind a reverse proxy (eg, Nginx), look
// for this header to get the real IP address of the client.
forwardedFor: r.Header.Get("X-Forwarded-For"),
}
go func() {

View File

@ -107,6 +107,10 @@ func (s *Settings) Save() error {
}
func (s *Settings) AddBan(host string, names []string) error {
if host == "127.0.0.1" {
return fmt.Errorf("Cannot add a ban for localhost.")
}
b := BanInfo{
Names: names,
IP: host,