You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

kline.go 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/goshuirc/irc-go/ircfmt"
  12. "github.com/goshuirc/irc-go/ircmatch"
  13. "github.com/goshuirc/irc-go/ircmsg"
  14. "github.com/oragono/oragono/irc/custime"
  15. "github.com/oragono/oragono/irc/sno"
  16. "github.com/tidwall/buntdb"
  17. )
  18. const (
  19. keyKlineEntry = "bans.kline %s"
  20. )
  21. // KLineInfo contains the address itself and expiration time for a given network.
  22. type KLineInfo struct {
  23. // Mask that is blocked.
  24. Mask string
  25. // Matcher, to facilitate fast matching.
  26. Matcher ircmatch.Matcher
  27. // Info contains information on the ban.
  28. Info IPBanInfo
  29. }
  30. // KLineManager manages and klines.
  31. type KLineManager struct {
  32. sync.RWMutex
  33. // kline'd entries
  34. entries map[string]*KLineInfo
  35. }
  36. // NewKLineManager returns a new KLineManager.
  37. func NewKLineManager() *KLineManager {
  38. var km KLineManager
  39. km.entries = make(map[string]*KLineInfo)
  40. return &km
  41. }
  42. // AllBans returns all bans (for use with APIs, etc).
  43. func (km *KLineManager) AllBans() map[string]IPBanInfo {
  44. allb := make(map[string]IPBanInfo)
  45. km.RLock()
  46. defer km.RUnlock()
  47. for name, info := range km.entries {
  48. allb[name] = info.Info
  49. }
  50. return allb
  51. }
  52. // AddMask adds to the blocked list.
  53. func (km *KLineManager) AddMask(mask string, length *IPRestrictTime, reason string, operReason string) {
  54. kln := KLineInfo{
  55. Mask: mask,
  56. Matcher: ircmatch.MakeMatch(mask),
  57. Info: IPBanInfo{
  58. Time: length,
  59. Reason: reason,
  60. OperReason: operReason,
  61. },
  62. }
  63. km.Lock()
  64. km.entries[mask] = &kln
  65. km.Unlock()
  66. }
  67. // RemoveMask removes a mask from the blocked list.
  68. func (km *KLineManager) RemoveMask(mask string) {
  69. km.Lock()
  70. delete(km.entries, mask)
  71. km.Unlock()
  72. }
  73. // CheckMasks returns whether or not the hostmask(s) are banned, and how long they are banned for.
  74. func (km *KLineManager) CheckMasks(masks ...string) (isBanned bool, info *IPBanInfo) {
  75. doCleanup := false
  76. defer func() {
  77. // asynchronously remove expired bans
  78. if doCleanup {
  79. go func() {
  80. km.Lock()
  81. defer km.Unlock()
  82. for key, entry := range km.entries {
  83. if entry.Info.Time.IsExpired() {
  84. delete(km.entries, key)
  85. }
  86. }
  87. }()
  88. }
  89. }()
  90. km.RLock()
  91. defer km.RUnlock()
  92. for _, entryInfo := range km.entries {
  93. if entryInfo.Info.Time != nil && entryInfo.Info.Time.IsExpired() {
  94. doCleanup = true
  95. continue
  96. }
  97. matches := false
  98. for _, mask := range masks {
  99. if entryInfo.Matcher.Match(mask) {
  100. matches = true
  101. break
  102. }
  103. }
  104. if matches {
  105. return true, &entryInfo.Info
  106. }
  107. }
  108. // no matches!
  109. return false, nil
  110. }
  111. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  112. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  113. // check oper permissions
  114. if !client.class.Capabilities["oper:local_ban"] {
  115. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  116. return false
  117. }
  118. currentArg := 0
  119. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  120. var andKill bool
  121. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  122. andKill = true
  123. currentArg++
  124. }
  125. // when setting a ban that covers the oper's current connection, we require them to say
  126. // "KLINE MYSELF" so that we're sure they really mean it.
  127. var klineMyself bool
  128. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  129. klineMyself = true
  130. currentArg++
  131. }
  132. // duration
  133. duration, err := custime.ParseDuration(msg.Params[currentArg])
  134. durationIsUsed := err == nil
  135. if durationIsUsed {
  136. currentArg++
  137. }
  138. // get mask
  139. if len(msg.Params) < currentArg+1 {
  140. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  141. return false
  142. }
  143. mask := strings.ToLower(msg.Params[currentArg])
  144. currentArg++
  145. // check mask
  146. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  147. mask = mask + "!*@*"
  148. } else if !strings.Contains(mask, "@") {
  149. mask = mask + "@*"
  150. }
  151. matcher := ircmatch.MakeMatch(mask)
  152. for _, clientMask := range client.AllNickmasks() {
  153. if !klineMyself && matcher.Match(clientMask) {
  154. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To KLINE yourself, you must use the command: /KLINE MYSELF <arguments>")
  155. return false
  156. }
  157. }
  158. // check remote
  159. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  160. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Remote servers not yet supported")
  161. return false
  162. }
  163. // get comment(s)
  164. reason := "No reason given"
  165. operReason := "No reason given"
  166. if len(msg.Params) > currentArg {
  167. tempReason := strings.TrimSpace(msg.Params[currentArg])
  168. if len(tempReason) > 0 && tempReason != "|" {
  169. tempReasons := strings.SplitN(tempReason, "|", 2)
  170. if tempReasons[0] != "" {
  171. reason = tempReasons[0]
  172. }
  173. if len(tempReasons) > 1 && tempReasons[1] != "" {
  174. operReason = tempReasons[1]
  175. } else {
  176. operReason = reason
  177. }
  178. }
  179. }
  180. // assemble ban info
  181. var banTime *IPRestrictTime
  182. if durationIsUsed {
  183. banTime = &IPRestrictTime{
  184. Duration: duration,
  185. Expires: time.Now().Add(duration),
  186. }
  187. }
  188. info := IPBanInfo{
  189. Reason: reason,
  190. OperReason: operReason,
  191. Time: banTime,
  192. }
  193. // save in datastore
  194. err = server.store.Update(func(tx *buntdb.Tx) error {
  195. klineKey := fmt.Sprintf(keyKlineEntry, mask)
  196. // assemble json from ban info
  197. b, err := json.Marshal(info)
  198. if err != nil {
  199. return err
  200. }
  201. tx.Set(klineKey, string(b), nil)
  202. return nil
  203. })
  204. if err != nil {
  205. client.Notice(fmt.Sprintf("Could not successfully save new K-LINE: %s", err.Error()))
  206. return false
  207. }
  208. server.klines.AddMask(mask, banTime, reason, operReason)
  209. var snoDescription string
  210. if durationIsUsed {
  211. client.Notice(fmt.Sprintf("Added temporary (%s) K-Line for %s", duration.String(), mask))
  212. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added temporary (%s) K-Line for %s"), client.nick, duration.String(), mask)
  213. } else {
  214. client.Notice(fmt.Sprintf("Added K-Line for %s", mask))
  215. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added K-Line for %s"), client.nick, mask)
  216. }
  217. server.snomasks.Send(sno.LocalXline, snoDescription)
  218. var killClient bool
  219. if andKill {
  220. var clientsToKill []*Client
  221. var killedClientNicks []string
  222. server.clients.ByNickMutex.RLock()
  223. for _, mcl := range server.clients.ByNick {
  224. for _, clientMask := range mcl.AllNickmasks() {
  225. if matcher.Match(clientMask) {
  226. clientsToKill = append(clientsToKill, mcl)
  227. killedClientNicks = append(killedClientNicks, mcl.nick)
  228. }
  229. }
  230. }
  231. server.clients.ByNickMutex.RUnlock()
  232. for _, mcl := range clientsToKill {
  233. mcl.exitedSnomaskSent = true
  234. mcl.Quit(fmt.Sprintf("You have been banned from this server (%s)", reason))
  235. if mcl == client {
  236. killClient = true
  237. } else {
  238. // if mcl == client, we kill them below
  239. mcl.destroy()
  240. }
  241. }
  242. // send snomask
  243. sort.Strings(killedClientNicks)
  244. server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s killed %d clients with a KLINE $c[grey][$r%s$c[grey]]"), client.nick, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
  245. }
  246. return killClient
  247. }
  248. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  249. // check oper permissions
  250. if !client.class.Capabilities["oper:local_unban"] {
  251. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  252. return false
  253. }
  254. // get host
  255. mask := msg.Params[0]
  256. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  257. mask = mask + "!*@*"
  258. } else if !strings.Contains(mask, "@") {
  259. mask = mask + "@*"
  260. }
  261. // save in datastore
  262. err := server.store.Update(func(tx *buntdb.Tx) error {
  263. klineKey := fmt.Sprintf(keyKlineEntry, mask)
  264. // check if it exists or not
  265. val, err := tx.Get(klineKey)
  266. if val == "" {
  267. return errNoExistingBan
  268. } else if err != nil {
  269. return err
  270. }
  271. tx.Delete(klineKey)
  272. return nil
  273. })
  274. if err != nil {
  275. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf("Could not remove ban [%s]", err.Error()))
  276. return false
  277. }
  278. server.klines.RemoveMask(mask)
  279. client.Notice(fmt.Sprintf("Removed K-Line for %s", mask))
  280. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
  281. return false
  282. }
  283. func (s *Server) loadKLines() {
  284. s.klines = NewKLineManager()
  285. // load from datastore
  286. s.store.View(func(tx *buntdb.Tx) error {
  287. //TODO(dan): We could make this safer
  288. tx.AscendKeys("bans.kline *", func(key, value string) bool {
  289. // get address name
  290. key = key[len("bans.kline "):]
  291. mask := key
  292. // load ban info
  293. var info IPBanInfo
  294. json.Unmarshal([]byte(value), &info)
  295. // add to the server
  296. s.klines.AddMask(mask, info.Time, info.Reason, info.OperReason)
  297. return true // true to continue I guess?
  298. })
  299. return nil
  300. })
  301. }