Add support for IP-based bans (#1703)

* Add support for IP-based bans. Closes #1534

* Linter cleanup
This commit is contained in:
Gabe Kangas
2022-03-06 20:34:49 -08:00
committed by GitHub
parent 78c27ddbdd
commit 19b9a8bdf6
21 changed files with 488 additions and 98 deletions

View File

@@ -44,6 +44,9 @@ func Start(getStatusFunc func() models.Status) error {
// GetClientsForUser will return chat connections that are owned by a specific user.
func GetClientsForUser(userID string) ([]*Client, error) {
_server.mu.Lock()
defer _server.mu.Unlock()
clients := map[string][]*Client{}
for _, client := range _server.clients {
@@ -175,7 +178,7 @@ func HandleClientConnection(w http.ResponseWriter, r *http.Request) {
_server.HandleClientConnection(w, r)
}
// DisconnectUser will forcefully disconnect all clients belonging to a user by ID.
func DisconnectUser(userID string) {
_server.DisconnectUser(userID)
// DisconnectClients will forcefully disconnect all clients belonging to a user by ID.
func DisconnectClients(clients []*Client) {
_server.DisconnectClients(clients)
}

View File

@@ -22,7 +22,7 @@ type Client struct {
conn *websocket.Conn
User *user.User `json:"user"`
server *Server
ipAddress string `json:"-"`
IPAddress string `json:"-"`
// Buffered channel of outbound messages.
send chan []byte
rateLimiter *rate.Limiter
@@ -94,7 +94,6 @@ func (c *Client) readPump() {
c.conn.SetPongHandler(func(string) error { _ = c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
c.close()
@@ -176,7 +175,7 @@ func (c *Client) handleEvent(data []byte) {
}
func (c *Client) close() {
log.Traceln("client closed:", c.User.DisplayName, c.id, c.ipAddress)
log.Traceln("client closed:", c.User.DisplayName, c.id, c.IPAddress)
_ = c.conn.Close()
c.server.unregister <- c.id

View File

@@ -22,6 +22,7 @@ const (
func setupPersistence() {
_datastore = data.GetDatastore()
data.CreateMessagesTable(_datastore.DB)
data.CreateBanIPTable(_datastore.DB)
chatDataPruner := time.NewTicker(5 * time.Minute)
go func() {
@@ -332,7 +333,7 @@ func saveMessageVisibility(messageIDs []string, visible bool) error {
return err
}
//nolint:gosec
// nolint:gosec
stmt, err := tx.Prepare("UPDATE messages SET hidden_at=? WHERE id IN (?" + strings.Repeat(",?", len(messageIDs)-1) + ")")
if err != nil {
return err

View File

@@ -83,7 +83,7 @@ func (s *Server) Addclient(conn *websocket.Conn, user *user.User, accessToken st
server: s,
conn: conn,
User: user,
ipAddress: ipAddress,
IPAddress: ipAddress,
accessToken: accessToken,
send: make(chan []byte, 256),
UserAgent: userAgent,
@@ -160,6 +160,22 @@ func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request)
return
}
ipAddress := utils.GetIPAddressFromRequest(r)
// Check if this client's IP address is banned. If so send a rejection.
if blocked, err := data.IsIPAddressBanned(ipAddress); blocked {
log.Debugln("Client ip address has been blocked. Rejecting.")
event := events.UserDisabledEvent{}
event.SetDefaults()
w.WriteHeader(http.StatusForbidden)
// Send this disabled event specifically to this single connected client
// to let them know they've been banned.
// _server.Send(event.GetBroadcastPayload(), client)
return
} else if err != nil {
log.Errorln("error determining if IP address is blocked: ", err)
}
// Limit concurrent chat connections
if int64(len(s.clients)) >= s.maxSocketConnectionLimit {
log.Warnln("rejecting incoming client connection as it exceeds the max client count of", s.maxSocketConnectionLimit)
@@ -203,7 +219,6 @@ func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request)
}
userAgent := r.UserAgent()
ipAddress := utils.GetIPAddressFromRequest(r)
s.Addclient(conn, user, accessToken, userAgent, ipAddress)
}
@@ -245,17 +260,8 @@ func (s *Server) Send(payload events.EventPayload, client *Client) {
client.send <- data
}
// DisconnectUser will forcefully disconnect all clients belonging to a user by ID.
func (s *Server) DisconnectUser(userID string) {
s.mu.Lock()
clients, err := GetClientsForUser(userID)
s.mu.Unlock()
if err != nil || clients == nil || len(clients) == 0 {
log.Debugln("Requested to disconnect user", userID, err)
return
}
// DisconnectClients will forcefully disconnect all clients belonging to a user by ID.
func (s *Server) DisconnectClients(clients []*Client) {
for _, client := range clients {
log.Traceln("Disconnecting client", client.User.ID, "owned by", client.User.DisplayName)