3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-11 06:29:29 +01:00
ergo/irc/dline.go

308 lines
7.5 KiB
Go
Raw Normal View History

2017-03-27 14:15:02 +02:00
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
2016-11-04 03:42:58 +01:00
// released under the MIT license
package irc
2016-11-04 12:14:52 +01:00
import (
2019-01-22 11:01:01 +01:00
"encoding/json"
2016-11-04 12:14:52 +01:00
"fmt"
"net"
2019-01-22 11:01:01 +01:00
"strings"
"sync"
2016-11-04 12:14:52 +01:00
"time"
2019-01-22 11:01:01 +01:00
"github.com/oragono/oragono/irc/utils"
2016-11-04 12:14:52 +01:00
"github.com/tidwall/buntdb"
)
const (
2019-01-22 11:01:01 +01:00
keyDlineEntry = "bans.dlinev2 %s"
2016-11-04 12:14:52 +01:00
)
2016-11-04 03:42:58 +01:00
// IPBanInfo holds info about an IP/net ban.
type IPBanInfo struct {
// Reason is the ban reason.
Reason string `json:"reason"`
2016-11-04 03:42:58 +01:00
// OperReason is an oper ban reason.
2016-11-04 12:14:52 +01:00
OperReason string `json:"oper_reason"`
2017-11-19 01:27:40 +01:00
// OperName is the oper who set the ban.
OperName string `json:"oper_name"`
2019-01-22 11:01:01 +01:00
// time of ban creation
TimeCreated time.Time
// duration of the ban; 0 means "permanent"
Duration time.Duration
}
func (info IPBanInfo) timeLeft() time.Duration {
return time.Until(info.TimeCreated.Add(info.Duration))
2019-01-22 11:01:01 +01:00
}
func (info IPBanInfo) TimeLeft() string {
if info.Duration == 0 {
return "indefinite"
} else {
return info.timeLeft().Truncate(time.Second).String()
}
2016-11-04 03:42:58 +01:00
}
// BanMessage returns the ban message.
func (info IPBanInfo) BanMessage(message string) string {
message = fmt.Sprintf(message, info.Reason)
2019-01-22 11:01:01 +01:00
if info.Duration != 0 {
message += fmt.Sprintf(" [%s]", info.TimeLeft())
}
return message
}
2016-11-04 03:42:58 +01:00
// dLineNet contains the net itself and expiration time for a given network.
type dLineNet struct {
// Network is the network that is blocked.
2019-01-22 11:01:01 +01:00
// This is always an IPv6 CIDR; IPv4 CIDRs are translated with the 4-in-6 prefix,
// individual IPv4 and IPV6 addresses are translated to the relevant /128.
2016-11-04 03:42:58 +01:00
Network net.IPNet
// Info contains information on the ban.
Info IPBanInfo
}
// DLineManager manages and dlines.
type DLineManager struct {
2019-01-22 11:01:01 +01:00
sync.RWMutex // tier 1
persistenceMutex sync.Mutex // tier 2
// networks that are dlined:
// XXX: the keys of this map (which are also the database persistence keys)
// are the human-readable representations returned by NetToNormalizedString
networks map[string]dLineNet
// this keeps track of expiration timers for temporary bans
expirationTimers map[string]*time.Timer
server *Server
2016-11-04 03:42:58 +01:00
}
// NewDLineManager returns a new DLineManager.
2019-01-22 11:01:01 +01:00
func NewDLineManager(server *Server) *DLineManager {
2016-11-04 12:14:52 +01:00
var dm DLineManager
2019-01-22 11:01:01 +01:00
dm.networks = make(map[string]dLineNet)
dm.expirationTimers = make(map[string]*time.Timer)
dm.server = server
dm.loadFromDatastore()
2016-11-04 03:42:58 +01:00
return &dm
}
2016-11-06 02:05:29 +01:00
// AllBans returns all bans (for use with APIs, etc).
func (dm *DLineManager) AllBans() map[string]IPBanInfo {
allb := make(map[string]IPBanInfo)
dm.RLock()
defer dm.RUnlock()
2019-01-22 11:01:01 +01:00
// map keys are already the human-readable forms, just return a copy of the map
for key, info := range dm.networks {
allb[key] = info.Info
2016-11-06 02:05:29 +01:00
}
return allb
}
2016-11-04 03:42:58 +01:00
// AddNetwork adds a network to the blocked list.
2019-01-22 11:01:01 +01:00
func (dm *DLineManager) AddNetwork(network net.IPNet, duration time.Duration, reason, operReason, operName string) error {
dm.persistenceMutex.Lock()
defer dm.persistenceMutex.Unlock()
// assemble ban info
info := IPBanInfo{
Reason: reason,
OperReason: operReason,
OperName: operName,
TimeCreated: time.Now().UTC(),
2019-01-22 11:01:01 +01:00
Duration: duration,
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
id := dm.addNetworkInternal(network, info)
return dm.persistDline(id, info)
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
func (dm *DLineManager) addNetworkInternal(network net.IPNet, info IPBanInfo) (id string) {
network = utils.NormalizeNet(network)
id = utils.NetToNormalizedString(network)
var timeLeft time.Duration
if info.Duration != 0 {
timeLeft = info.timeLeft()
if timeLeft <= 0 {
return
}
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
dm.Lock()
2019-01-22 11:01:01 +01:00
defer dm.Unlock()
dm.networks[id] = dLineNet{
Network: network,
Info: info,
}
dm.cancelTimer(id)
if info.Duration == 0 {
return
}
// set up new expiration timer
timeCreated := info.TimeCreated
processExpiration := func() {
dm.Lock()
defer dm.Unlock()
netBan, ok := dm.networks[id]
if ok && netBan.Info.TimeCreated.Equal(timeCreated) {
delete(dm.networks, id)
// TODO(slingamn) here's where we'd remove it from the radix tree
delete(dm.expirationTimers, id)
2019-01-22 11:01:01 +01:00
}
}
dm.expirationTimers[id] = time.AfterFunc(timeLeft, processExpiration)
return
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
func (dm *DLineManager) cancelTimer(id string) {
oldTimer := dm.expirationTimers[id]
if oldTimer != nil {
oldTimer.Stop()
delete(dm.expirationTimers, id)
}
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
func (dm *DLineManager) persistDline(id string, info IPBanInfo) error {
// save in datastore
dlineKey := fmt.Sprintf(keyDlineEntry, id)
// assemble json from ban info
b, err := json.Marshal(info)
if err != nil {
dm.server.logger.Error("internal", "couldn't marshal d-line", err.Error())
return err
}
bstr := string(b)
var setOptions *buntdb.SetOptions
if info.Duration != 0 {
setOptions = &buntdb.SetOptions{Expires: true, TTL: info.Duration}
2016-11-04 03:42:58 +01:00
}
2019-01-22 11:01:01 +01:00
err = dm.server.store.Update(func(tx *buntdb.Tx) error {
_, _, err := tx.Set(dlineKey, bstr, setOptions)
return err
})
if err != nil {
dm.server.logger.Error("internal", "couldn't store d-line", err.Error())
}
return err
}
func (dm *DLineManager) unpersistDline(id string) error {
dlineKey := fmt.Sprintf(keyDlineEntry, id)
return dm.server.store.Update(func(tx *buntdb.Tx) error {
_, err := tx.Delete(dlineKey)
return err
})
}
// RemoveNetwork removes a network from the blocked list.
func (dm *DLineManager) RemoveNetwork(network net.IPNet) error {
dm.persistenceMutex.Lock()
defer dm.persistenceMutex.Unlock()
id := utils.NetToNormalizedString(utils.NormalizeNet(network))
present := func() bool {
dm.Lock()
defer dm.Unlock()
_, ok := dm.networks[id]
delete(dm.networks, id)
dm.cancelTimer(id)
return ok
}()
2016-11-04 03:42:58 +01:00
2019-01-22 11:01:01 +01:00
if !present {
return errNoExistingBan
}
return dm.unpersistDline(id)
}
// AddIP adds an IP address to the blocked list.
func (dm *DLineManager) AddIP(addr net.IP, duration time.Duration, reason, operReason, operName string) error {
return dm.AddNetwork(utils.NormalizeIPToNet(addr), duration, reason, operReason, operName)
}
// RemoveIP removes an IP address from the blocked list.
func (dm *DLineManager) RemoveIP(addr net.IP) error {
return dm.RemoveNetwork(utils.NormalizeIPToNet(addr))
}
// CheckIP returns whether or not an IP address was banned, and how long it is banned for.
func (dm *DLineManager) CheckIP(addr net.IP) (isBanned bool, info IPBanInfo) {
addr = addr.To16() // almost certainly unnecessary
2019-11-18 23:21:28 +01:00
if addr.IsLoopback() {
return // #671
}
2019-01-22 11:01:01 +01:00
dm.RLock()
defer dm.RUnlock()
2016-11-04 03:42:58 +01:00
2019-01-22 11:01:01 +01:00
// check networks
// TODO(slingamn) use a radix tree as the data plane for this
for _, netBan := range dm.networks {
if netBan.Network.Contains(addr) {
return true, netBan.Info
}
2016-11-04 03:42:58 +01:00
}
// no matches!
2019-01-22 11:01:01 +01:00
isBanned = false
return
2016-11-04 03:42:58 +01:00
}
2016-11-04 12:14:52 +01:00
2019-01-22 11:01:01 +01:00
func (dm *DLineManager) loadFromDatastore() {
dlinePrefix := fmt.Sprintf(keyDlineEntry, "")
dm.server.store.View(func(tx *buntdb.Tx) error {
tx.AscendGreaterOrEqual("", dlinePrefix, func(key, value string) bool {
if !strings.HasPrefix(key, dlinePrefix) {
return false
}
2016-11-04 12:14:52 +01:00
// get address name
2019-01-22 11:01:01 +01:00
key = strings.TrimPrefix(key, dlinePrefix)
2016-11-04 12:14:52 +01:00
// load addr/net
2019-01-22 11:01:01 +01:00
hostNet, err := utils.NormalizedNetFromString(key)
2016-11-04 12:14:52 +01:00
if err != nil {
2019-01-22 11:01:01 +01:00
dm.server.logger.Error("internal", "bad dline cidr", err.Error())
return true
2016-11-04 12:14:52 +01:00
}
// load ban info
var info IPBanInfo
2019-01-22 11:01:01 +01:00
err = json.Unmarshal([]byte(value), &info)
if err != nil {
dm.server.logger.Error("internal", "bad dline data", err.Error())
return true
}
2016-11-04 12:14:52 +01:00
2017-11-19 01:27:40 +01:00
// set opername if it isn't already set
if info.OperName == "" {
2019-01-22 11:01:01 +01:00
info.OperName = dm.server.name
2017-11-19 01:27:40 +01:00
}
2016-11-04 12:14:52 +01:00
// add to the server
2019-01-22 11:01:01 +01:00
dm.addNetworkInternal(hostNet, info)
2016-11-04 12:14:52 +01:00
2019-01-22 11:01:01 +01:00
return true
2016-11-04 12:14:52 +01:00
})
return nil
})
}
2019-01-22 11:01:01 +01:00
func (s *Server) loadDLines() {
s.dlines = NewDLineManager(s)
}