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.

dline.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "errors"
  6. "fmt"
  7. "net"
  8. "sort"
  9. "time"
  10. "strings"
  11. "encoding/json"
  12. "github.com/goshuirc/irc-go/ircfmt"
  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. keyDlineEntry = "bans.dline %s"
  20. )
  21. var (
  22. errNoExistingBan = errors.New("Ban does not exist")
  23. )
  24. // IPRestrictTime contains the expiration info about the given IP.
  25. type IPRestrictTime struct {
  26. // Duration is how long this block lasts for.
  27. Duration time.Duration `json:"duration"`
  28. // Expires is when this block expires.
  29. Expires time.Time `json:"expires"`
  30. }
  31. // IsExpired returns true if the time has expired.
  32. func (iptime *IPRestrictTime) IsExpired() bool {
  33. return iptime.Expires.Before(time.Now())
  34. }
  35. // IPBanInfo holds info about an IP/net ban.
  36. type IPBanInfo struct {
  37. // Reason is the ban reason.
  38. Reason string `json:"reason"`
  39. // OperReason is an oper ban reason.
  40. OperReason string `json:"oper_reason"`
  41. // Time holds details about the duration, if it exists.
  42. Time *IPRestrictTime `json:"time"`
  43. }
  44. // BanMessage returns the ban message.
  45. func (info IPBanInfo) BanMessage(message string) string {
  46. message = fmt.Sprintf(message, info.Reason)
  47. if info.Time != nil {
  48. message += fmt.Sprintf(" [%s]", info.Time.Duration.String())
  49. }
  50. return message
  51. }
  52. // dLineAddr contains the address itself and expiration time for a given network.
  53. type dLineAddr struct {
  54. // Address is the address that is blocked.
  55. Address net.IP
  56. // Info contains information on the ban.
  57. Info IPBanInfo
  58. }
  59. // dLineNet contains the net itself and expiration time for a given network.
  60. type dLineNet struct {
  61. // Network is the network that is blocked.
  62. Network net.IPNet
  63. // Info contains information on the ban.
  64. Info IPBanInfo
  65. }
  66. // DLineManager manages and dlines.
  67. type DLineManager struct {
  68. // addresses that are dlined
  69. addresses map[string]*dLineAddr
  70. // networks that are dlined
  71. networks map[string]*dLineNet
  72. }
  73. // NewDLineManager returns a new DLineManager.
  74. func NewDLineManager() *DLineManager {
  75. var dm DLineManager
  76. dm.addresses = make(map[string]*dLineAddr)
  77. dm.networks = make(map[string]*dLineNet)
  78. return &dm
  79. }
  80. // AllBans returns all bans (for use with APIs, etc).
  81. func (dm *DLineManager) AllBans() map[string]IPBanInfo {
  82. allb := make(map[string]IPBanInfo)
  83. for name, info := range dm.addresses {
  84. allb[name] = info.Info
  85. }
  86. for name, info := range dm.networks {
  87. allb[name] = info.Info
  88. }
  89. return allb
  90. }
  91. // AddNetwork adds a network to the blocked list.
  92. func (dm *DLineManager) AddNetwork(network net.IPNet, length *IPRestrictTime, reason string, operReason string) {
  93. netString := network.String()
  94. dln := dLineNet{
  95. Network: network,
  96. Info: IPBanInfo{
  97. Time: length,
  98. Reason: reason,
  99. OperReason: operReason,
  100. },
  101. }
  102. dm.networks[netString] = &dln
  103. }
  104. // RemoveNetwork removes a network from the blocked list.
  105. func (dm *DLineManager) RemoveNetwork(network net.IPNet) {
  106. netString := network.String()
  107. delete(dm.networks, netString)
  108. }
  109. // AddIP adds an IP address to the blocked list.
  110. func (dm *DLineManager) AddIP(addr net.IP, length *IPRestrictTime, reason string, operReason string) {
  111. addrString := addr.String()
  112. dla := dLineAddr{
  113. Address: addr,
  114. Info: IPBanInfo{
  115. Time: length,
  116. Reason: reason,
  117. OperReason: operReason,
  118. },
  119. }
  120. dm.addresses[addrString] = &dla
  121. }
  122. // RemoveIP removes an IP from the blocked list.
  123. func (dm *DLineManager) RemoveIP(addr net.IP) {
  124. addrString := addr.String()
  125. delete(dm.addresses, addrString)
  126. }
  127. // CheckIP returns whether or not an IP address was banned, and how long it is banned for.
  128. func (dm *DLineManager) CheckIP(addr net.IP) (isBanned bool, info *IPBanInfo) {
  129. // check IP addr
  130. addrString := addr.String()
  131. addrInfo := dm.addresses[addrString]
  132. if addrInfo != nil {
  133. if addrInfo.Info.Time != nil {
  134. if addrInfo.Info.Time.IsExpired() {
  135. // ban on IP has expired, remove it from our blocked list
  136. dm.RemoveIP(addr)
  137. } else {
  138. return true, &addrInfo.Info
  139. }
  140. } else {
  141. return true, &addrInfo.Info
  142. }
  143. }
  144. // check networks
  145. var netsToRemove []net.IPNet
  146. for _, netInfo := range dm.networks {
  147. if !netInfo.Network.Contains(addr) {
  148. continue
  149. }
  150. if netInfo.Info.Time != nil {
  151. if netInfo.Info.Time.IsExpired() {
  152. // ban on network has expired, remove it from our blocked list
  153. netsToRemove = append(netsToRemove, netInfo.Network)
  154. } else {
  155. return true, &addrInfo.Info
  156. }
  157. } else {
  158. return true, &addrInfo.Info
  159. }
  160. }
  161. // remove expired networks
  162. for _, expiredNet := range netsToRemove {
  163. dm.RemoveNetwork(expiredNet)
  164. }
  165. // no matches!
  166. return false, nil
  167. }
  168. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  169. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  170. // check oper permissions
  171. if !client.class.Capabilities["oper:local_ban"] {
  172. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  173. return false
  174. }
  175. currentArg := 0
  176. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  177. var andKill bool
  178. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  179. andKill = true
  180. currentArg++
  181. }
  182. // when setting a ban that covers the oper's current connection, we require them to say
  183. // "DLINE MYSELF" so that we're sure they really mean it.
  184. var dlineMyself bool
  185. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  186. dlineMyself = true
  187. currentArg++
  188. }
  189. // duration
  190. duration, err := custime.ParseDuration(msg.Params[currentArg])
  191. durationIsUsed := err == nil
  192. if durationIsUsed {
  193. currentArg++
  194. }
  195. // get host
  196. if len(msg.Params) < currentArg+1 {
  197. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  198. return false
  199. }
  200. hostString := msg.Params[currentArg]
  201. currentArg++
  202. // check host
  203. var hostAddr net.IP
  204. var hostNet *net.IPNet
  205. _, hostNet, err = net.ParseCIDR(hostString)
  206. if err != nil {
  207. hostAddr = net.ParseIP(hostString)
  208. }
  209. if hostAddr == nil && hostNet == nil {
  210. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Could not parse IP address or CIDR network")
  211. return false
  212. }
  213. if hostNet == nil {
  214. hostString = hostAddr.String()
  215. if !dlineMyself && hostAddr.Equal(client.IP()) {
  216. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To DLINE yourself, you must use the command: /DLINE MYSELF <arguments>")
  217. return false
  218. }
  219. } else {
  220. hostString = hostNet.String()
  221. if !dlineMyself && hostNet.Contains(client.IP()) {
  222. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To DLINE yourself, you must use the command: /DLINE MYSELF <arguments>")
  223. return false
  224. }
  225. }
  226. // check remote
  227. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  228. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Remote servers not yet supported")
  229. return false
  230. }
  231. // get comment(s)
  232. reason := "No reason given"
  233. operReason := "No reason given"
  234. if len(msg.Params) > currentArg {
  235. tempReason := strings.TrimSpace(msg.Params[currentArg])
  236. if len(tempReason) > 0 && tempReason != "|" {
  237. tempReasons := strings.SplitN(tempReason, "|", 2)
  238. if tempReasons[0] != "" {
  239. reason = tempReasons[0]
  240. }
  241. if len(tempReasons) > 1 && tempReasons[1] != "" {
  242. operReason = tempReasons[1]
  243. } else {
  244. operReason = reason
  245. }
  246. }
  247. }
  248. // assemble ban info
  249. var banTime *IPRestrictTime
  250. if durationIsUsed {
  251. banTime = &IPRestrictTime{
  252. Duration: duration,
  253. Expires: time.Now().Add(duration),
  254. }
  255. }
  256. info := IPBanInfo{
  257. Reason: reason,
  258. OperReason: operReason,
  259. Time: banTime,
  260. }
  261. // save in datastore
  262. err = server.store.Update(func(tx *buntdb.Tx) error {
  263. dlineKey := fmt.Sprintf(keyDlineEntry, hostString)
  264. // assemble json from ban info
  265. b, err := json.Marshal(info)
  266. if err != nil {
  267. return err
  268. }
  269. tx.Set(dlineKey, string(b), nil)
  270. return nil
  271. })
  272. if err != nil {
  273. client.Notice(fmt.Sprintf("Could not successfully save new D-LINE: %s", err.Error()))
  274. return false
  275. }
  276. if hostNet == nil {
  277. server.dlines.AddIP(hostAddr, banTime, reason, operReason)
  278. } else {
  279. server.dlines.AddNetwork(*hostNet, banTime, reason, operReason)
  280. }
  281. var snoDescription string
  282. if durationIsUsed {
  283. client.Notice(fmt.Sprintf("Added temporary (%s) D-Line for %s", duration.String(), hostString))
  284. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added temporary (%s) D-Line for %s"), client.nick, duration.String(), hostString)
  285. } else {
  286. client.Notice(fmt.Sprintf("Added D-Line for %s", hostString))
  287. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added D-Line for %s"), client.nick, hostString)
  288. }
  289. server.snomasks.Send(sno.LocalXline, snoDescription)
  290. var killClient bool
  291. if andKill {
  292. var clientsToKill []*Client
  293. var killedClientNicks []string
  294. var toKill bool
  295. server.clients.ByNickMutex.RLock()
  296. for _, mcl := range server.clients.ByNick {
  297. if hostNet == nil {
  298. toKill = hostAddr.Equal(mcl.IP())
  299. } else {
  300. toKill = hostNet.Contains(mcl.IP())
  301. }
  302. if toKill {
  303. clientsToKill = append(clientsToKill, mcl)
  304. killedClientNicks = append(killedClientNicks, mcl.nick)
  305. }
  306. }
  307. server.clients.ByNickMutex.RUnlock()
  308. for _, mcl := range clientsToKill {
  309. mcl.exitedSnomaskSent = true
  310. mcl.Quit(fmt.Sprintf("You have been banned from this server (%s)", reason))
  311. if mcl == client {
  312. killClient = true
  313. } else {
  314. // if mcl == client, we kill them below
  315. mcl.destroy()
  316. }
  317. }
  318. // send snomask
  319. sort.Strings(killedClientNicks)
  320. server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s killed %d clients with a DLINE $c[grey][$r%s$c[grey]]"), client.nick, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
  321. }
  322. return killClient
  323. }
  324. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  325. // check oper permissions
  326. if !client.class.Capabilities["oper:local_unban"] {
  327. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  328. return false
  329. }
  330. // get host
  331. hostString := msg.Params[0]
  332. // check host
  333. var hostAddr net.IP
  334. var hostNet *net.IPNet
  335. _, hostNet, err := net.ParseCIDR(hostString)
  336. if err != nil {
  337. hostAddr = net.ParseIP(hostString)
  338. }
  339. if hostAddr == nil && hostNet == nil {
  340. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Could not parse IP address or CIDR network")
  341. return false
  342. }
  343. if hostNet == nil {
  344. hostString = hostAddr.String()
  345. } else {
  346. hostString = hostNet.String()
  347. }
  348. // save in datastore
  349. err = server.store.Update(func(tx *buntdb.Tx) error {
  350. dlineKey := fmt.Sprintf(keyDlineEntry, hostString)
  351. // check if it exists or not
  352. val, err := tx.Get(dlineKey)
  353. if val == "" {
  354. return errNoExistingBan
  355. } else if err != nil {
  356. return err
  357. }
  358. tx.Delete(dlineKey)
  359. return nil
  360. })
  361. if err != nil {
  362. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf("Could not remove ban [%s]", err.Error()))
  363. return false
  364. }
  365. if hostNet == nil {
  366. server.dlines.RemoveIP(hostAddr)
  367. } else {
  368. server.dlines.RemoveNetwork(*hostNet)
  369. }
  370. client.Notice(fmt.Sprintf("Removed D-Line for %s", hostString))
  371. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  372. return false
  373. }
  374. func (s *Server) loadDLines() {
  375. s.dlines = NewDLineManager()
  376. // load from datastore
  377. s.store.View(func(tx *buntdb.Tx) error {
  378. //TODO(dan): We could make this safer
  379. tx.AscendKeys("bans.dline *", func(key, value string) bool {
  380. // get address name
  381. key = key[len("bans.dline "):]
  382. // load addr/net
  383. var hostAddr net.IP
  384. var hostNet *net.IPNet
  385. _, hostNet, err := net.ParseCIDR(key)
  386. if err != nil {
  387. hostAddr = net.ParseIP(key)
  388. }
  389. // load ban info
  390. var info IPBanInfo
  391. json.Unmarshal([]byte(value), &info)
  392. // add to the server
  393. if hostNet == nil {
  394. s.dlines.AddIP(hostAddr, info.Time, info.Reason, info.OperReason)
  395. } else {
  396. s.dlines.AddNetwork(*hostNet, info.Time, info.Reason, info.OperReason)
  397. }
  398. return true // true to continue I guess?
  399. })
  400. return nil
  401. })
  402. }