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

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