Add support for IP-based bans (#1703)
* Add support for IP-based bans. Closes #1534 * Linter cleanup
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ func SetupPersistence(file string) error {
|
||||
if !utils.DoesFileExists(file) {
|
||||
log.Traceln("Creating new database at", file)
|
||||
|
||||
_, err := os.Create(file) //nolint: gosec
|
||||
_, err := os.Create(file) //nolint:gosec
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/owncast/owncast/db"
|
||||
"github.com/owncast/owncast/models"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -52,3 +55,58 @@ func GetMessagesCount() int64 {
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// CreateBanIPTable will create the IP ban table if needed.
|
||||
func CreateBanIPTable(db *sql.DB) {
|
||||
createTableSQL := ` CREATE TABLE IF NOT EXISTS ip_bans (
|
||||
"ip_address" TEXT NOT NULL PRIMARY KEY,
|
||||
"notes" TEXT,
|
||||
"created_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);`
|
||||
|
||||
stmt, err := db.Prepare(createTableSQL)
|
||||
if err != nil {
|
||||
log.Fatal("error creating ip ban table", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
if _, err := stmt.Exec(); err != nil {
|
||||
log.Fatal("error creating ip ban table", err)
|
||||
}
|
||||
}
|
||||
|
||||
// BanIPAddress will persist a new IP address ban to the datastore.
|
||||
func BanIPAddress(address, note string) error {
|
||||
return _datastore.GetQueries().BanIPAddress(context.Background(), db.BanIPAddressParams{
|
||||
IpAddress: address,
|
||||
Notes: sql.NullString{String: note, Valid: true},
|
||||
})
|
||||
}
|
||||
|
||||
// IsIPAddressBanned will return if an IP address has been previously blocked.
|
||||
func IsIPAddressBanned(address string) (bool, error) {
|
||||
blocked, error := _datastore.GetQueries().IsIPAddressBlocked(context.Background(), address)
|
||||
return blocked > 0, error
|
||||
}
|
||||
|
||||
// GetIPAddressBans will return all the banned IP addresses.
|
||||
func GetIPAddressBans() ([]models.IPAddress, error) {
|
||||
result, err := _datastore.GetQueries().GetIPAddressBans(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response := []models.IPAddress{}
|
||||
for _, ip := range result {
|
||||
response = append(response, models.IPAddress{
|
||||
IPAddress: ip.IpAddress,
|
||||
Notes: ip.Notes.String,
|
||||
CreatedAt: ip.CreatedAt.Time,
|
||||
})
|
||||
}
|
||||
return response, err
|
||||
}
|
||||
|
||||
// RemoveIPAddressBan will remove a previously banned IP address.
|
||||
func RemoveIPAddressBan(address string) error {
|
||||
return _datastore.GetQueries().RemoveIPAddressBan(context.Background(), address)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ import "os"
|
||||
|
||||
// WritePlaylist writes the playlist to disk.
|
||||
func WritePlaylist(data string, filePath string) error {
|
||||
f, err := os.Create(filePath) //nolint:gosec
|
||||
// nolint:gosec
|
||||
f, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user