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 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. // KLINE LIST
  113. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  114. // check oper permissions
  115. if !client.class.Capabilities["oper:local_ban"] {
  116. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  117. return false
  118. }
  119. currentArg := 0
  120. // if they say LIST, we just list the current klines
  121. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  122. bans := server.klines.AllBans()
  123. if len(bans) == 0 {
  124. client.Notice("No KLINEs have been set!")
  125. }
  126. for key, info := range bans {
  127. client.Notice(fmt.Sprintf("Ban - %s - %s", key, info.BanMessage("%s")))
  128. }
  129. return false
  130. }
  131. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  132. var andKill bool
  133. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  134. andKill = true
  135. currentArg++
  136. }
  137. // when setting a ban that covers the oper's current connection, we require them to say
  138. // "KLINE MYSELF" so that we're sure they really mean it.
  139. var klineMyself bool
  140. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  141. klineMyself = true
  142. currentArg++
  143. }
  144. // duration
  145. duration, err := custime.ParseDuration(msg.Params[currentArg])
  146. durationIsUsed := err == nil
  147. if durationIsUsed {
  148. currentArg++
  149. }
  150. // get mask
  151. if len(msg.Params) < currentArg+1 {
  152. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  153. return false
  154. }
  155. mask := strings.ToLower(msg.Params[currentArg])
  156. currentArg++
  157. // check mask
  158. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  159. mask = mask + "!*@*"
  160. } else if !strings.Contains(mask, "@") {
  161. mask = mask + "@*"
  162. }
  163. matcher := ircmatch.MakeMatch(mask)
  164. for _, clientMask := range client.AllNickmasks() {
  165. if !klineMyself && matcher.Match(clientMask) {
  166. 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>")
  167. return false
  168. }
  169. }
  170. // check remote
  171. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  172. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Remote servers not yet supported")
  173. return false
  174. }
  175. // get comment(s)
  176. reason := "No reason given"
  177. operReason := "No reason given"
  178. if len(msg.Params) > currentArg {
  179. tempReason := strings.TrimSpace(msg.Params[currentArg])
  180. if len(tempReason) > 0 && tempReason != "|" {
  181. tempReasons := strings.SplitN(tempReason, "|", 2)
  182. if tempReasons[0] != "" {
  183. reason = tempReasons[0]
  184. }
  185. if len(tempReasons) > 1 && tempReasons[1] != "" {
  186. operReason = tempReasons[1]
  187. } else {
  188. operReason = reason
  189. }
  190. }
  191. }
  192. // assemble ban info
  193. var banTime *IPRestrictTime
  194. if durationIsUsed {
  195. banTime = &IPRestrictTime{
  196. Duration: duration,
  197. Expires: time.Now().Add(duration),
  198. }
  199. }
  200. info := IPBanInfo{
  201. Reason: reason,
  202. OperReason: operReason,
  203. Time: banTime,
  204. }
  205. // save in datastore
  206. err = server.store.Update(func(tx *buntdb.Tx) error {
  207. klineKey := fmt.Sprintf(keyKlineEntry, mask)
  208. // assemble json from ban info
  209. b, err := json.Marshal(info)
  210. if err != nil {
  211. return err
  212. }
  213. tx.Set(klineKey, string(b), nil)
  214. return nil
  215. })
  216. if err != nil {
  217. client.Notice(fmt.Sprintf("Could not successfully save new K-LINE: %s", err.Error()))
  218. return false
  219. }
  220. server.klines.AddMask(mask, banTime, reason, operReason)
  221. var snoDescription string
  222. if durationIsUsed {
  223. client.Notice(fmt.Sprintf("Added temporary (%s) K-Line for %s", duration.String(), mask))
  224. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added temporary (%s) K-Line for %s"), client.nick, duration.String(), mask)
  225. } else {
  226. client.Notice(fmt.Sprintf("Added K-Line for %s", mask))
  227. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added K-Line for %s"), client.nick, mask)
  228. }
  229. server.snomasks.Send(sno.LocalXline, snoDescription)
  230. var killClient bool
  231. if andKill {
  232. var clientsToKill []*Client
  233. var killedClientNicks []string
  234. server.clients.ByNickMutex.RLock()
  235. for _, mcl := range server.clients.ByNick {
  236. for _, clientMask := range mcl.AllNickmasks() {
  237. if matcher.Match(clientMask) {
  238. clientsToKill = append(clientsToKill, mcl)
  239. killedClientNicks = append(killedClientNicks, mcl.nick)
  240. }
  241. }
  242. }
  243. server.clients.ByNickMutex.RUnlock()
  244. for _, mcl := range clientsToKill {
  245. mcl.exitedSnomaskSent = true
  246. mcl.Quit(fmt.Sprintf("You have been banned from this server (%s)", reason))
  247. if mcl == client {
  248. killClient = true
  249. } else {
  250. // if mcl == client, we kill them below
  251. mcl.destroy()
  252. }
  253. }
  254. // send snomask
  255. sort.Strings(killedClientNicks)
  256. 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, ", ")))
  257. }
  258. return killClient
  259. }
  260. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  261. // check oper permissions
  262. if !client.class.Capabilities["oper:local_unban"] {
  263. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  264. return false
  265. }
  266. // get host
  267. mask := msg.Params[0]
  268. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  269. mask = mask + "!*@*"
  270. } else if !strings.Contains(mask, "@") {
  271. mask = mask + "@*"
  272. }
  273. // save in datastore
  274. err := server.store.Update(func(tx *buntdb.Tx) error {
  275. klineKey := fmt.Sprintf(keyKlineEntry, mask)
  276. // check if it exists or not
  277. val, err := tx.Get(klineKey)
  278. if val == "" {
  279. return errNoExistingBan
  280. } else if err != nil {
  281. return err
  282. }
  283. tx.Delete(klineKey)
  284. return nil
  285. })
  286. if err != nil {
  287. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf("Could not remove ban [%s]", err.Error()))
  288. return false
  289. }
  290. server.klines.RemoveMask(mask)
  291. client.Notice(fmt.Sprintf("Removed K-Line for %s", mask))
  292. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
  293. return false
  294. }
  295. func (s *Server) loadKLines() {
  296. s.klines = NewKLineManager()
  297. // load from datastore
  298. s.store.View(func(tx *buntdb.Tx) error {
  299. //TODO(dan): We could make this safer
  300. tx.AscendKeys("bans.kline *", func(key, value string) bool {
  301. // get address name
  302. key = key[len("bans.kline "):]
  303. mask := key
  304. // load ban info
  305. var info IPBanInfo
  306. json.Unmarshal([]byte(value), &info)
  307. // add to the server
  308. s.klines.AddMask(mask, info.Time, info.Reason, info.OperReason)
  309. return true // true to continue I guess?
  310. })
  311. return nil
  312. })
  313. }