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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. // AddNetwork adds a network to the blocked list.
  69. func (dm *DLineManager) AddNetwork(network net.IPNet, length *IPRestrictTime, reason string, operReason string) {
  70. netString := network.String()
  71. dln := dLineNet{
  72. Network: network,
  73. Info: IPBanInfo{
  74. Time: length,
  75. Reason: reason,
  76. OperReason: operReason,
  77. },
  78. }
  79. dm.networks[netString] = &dln
  80. }
  81. // RemoveNetwork removes a network from the blocked list.
  82. func (dm *DLineManager) RemoveNetwork(network net.IPNet) {
  83. netString := network.String()
  84. delete(dm.networks, netString)
  85. }
  86. // AddIP adds an IP address to the blocked list.
  87. func (dm *DLineManager) AddIP(addr net.IP, length *IPRestrictTime, reason string, operReason string) {
  88. addrString := addr.String()
  89. dla := dLineAddr{
  90. Address: addr,
  91. Info: IPBanInfo{
  92. Time: length,
  93. Reason: reason,
  94. OperReason: operReason,
  95. },
  96. }
  97. dm.addresses[addrString] = &dla
  98. }
  99. // RemoveIP removes an IP from the blocked list.
  100. func (dm *DLineManager) RemoveIP(addr net.IP) {
  101. addrString := addr.String()
  102. delete(dm.addresses, addrString)
  103. }
  104. // CheckIP returns whether or not an IP address was banned, and how long it is banned for.
  105. func (dm *DLineManager) CheckIP(addr net.IP) (isBanned bool, info *IPBanInfo) {
  106. // check IP addr
  107. addrString := addr.String()
  108. addrInfo := dm.addresses[addrString]
  109. if addrInfo != nil {
  110. if addrInfo.Info.Time != nil {
  111. if addrInfo.Info.Time.IsExpired() {
  112. // ban on IP has expired, remove it from our blocked list
  113. dm.RemoveIP(addr)
  114. } else {
  115. return true, &addrInfo.Info
  116. }
  117. } else {
  118. return true, &addrInfo.Info
  119. }
  120. }
  121. // check networks
  122. var netsToRemove []net.IPNet
  123. for _, netInfo := range dm.networks {
  124. if !netInfo.Network.Contains(addr) {
  125. continue
  126. }
  127. if netInfo.Info.Time != nil {
  128. if netInfo.Info.Time.IsExpired() {
  129. // ban on network has expired, remove it from our blocked list
  130. netsToRemove = append(netsToRemove, netInfo.Network)
  131. } else {
  132. return true, &addrInfo.Info
  133. }
  134. } else {
  135. return true, &addrInfo.Info
  136. }
  137. }
  138. // remove expired networks
  139. for _, expiredNet := range netsToRemove {
  140. dm.RemoveNetwork(expiredNet)
  141. }
  142. // no matches!
  143. return false, nil
  144. }
  145. // DLINE [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  146. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  147. // check oper permissions
  148. if !client.class.Capabilities["oper:local_ban"] {
  149. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  150. return false
  151. }
  152. currentArg := 0
  153. // when setting a ban that covers the oper's current connection, we require them to say
  154. // "DLINE MYSELF" so that we're sure they really mean it.
  155. var dlineMyself bool
  156. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  157. dlineMyself = true
  158. currentArg++
  159. }
  160. // duration
  161. duration, err := time.ParseDuration(msg.Params[currentArg])
  162. durationIsUsed := err == nil
  163. if durationIsUsed {
  164. currentArg++
  165. }
  166. // get host
  167. if len(msg.Params) < currentArg+1 {
  168. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  169. return false
  170. }
  171. hostString := msg.Params[currentArg]
  172. currentArg++
  173. // check host
  174. var hostAddr net.IP
  175. var hostNet *net.IPNet
  176. _, hostNet, err = net.ParseCIDR(hostString)
  177. if err != nil {
  178. hostAddr = net.ParseIP(hostString)
  179. }
  180. if hostAddr == nil && hostNet == nil {
  181. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Could not parse IP address or CIDR network")
  182. return false
  183. }
  184. if hostNet == nil {
  185. hostString = hostAddr.String()
  186. if !dlineMyself && hostAddr.Equal(net.ParseIP(IPString(client.socket.conn.RemoteAddr()))) {
  187. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To DLINE yourself, you must pass use the command: /DLINE MYSELF <arguments>")
  188. return false
  189. }
  190. } else {
  191. hostString = hostNet.String()
  192. if !dlineMyself && hostNet.Contains(net.ParseIP(IPString(client.socket.conn.RemoteAddr()))) {
  193. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To DLINE yourself, you must pass use the command: /DLINE MYSELF <arguments>")
  194. return false
  195. }
  196. }
  197. // check remote
  198. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  199. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Remote servers not yet supported")
  200. return false
  201. }
  202. // get comment(s)
  203. reason := "No reason given"
  204. operReason := "No reason given"
  205. if len(msg.Params) > currentArg {
  206. tempReason := strings.TrimSpace(msg.Params[currentArg])
  207. if len(tempReason) > 0 && tempReason != "|" {
  208. tempReasons := strings.SplitN(tempReason, "|", 2)
  209. if tempReasons[0] != "" {
  210. reason = tempReasons[0]
  211. }
  212. if len(tempReasons) > 1 && tempReasons[1] != "" {
  213. operReason = tempReasons[1]
  214. } else {
  215. operReason = reason
  216. }
  217. }
  218. }
  219. // assemble ban info
  220. var banTime *IPRestrictTime
  221. if durationIsUsed {
  222. banTime = &IPRestrictTime{
  223. Duration: duration,
  224. Expires: time.Now().Add(duration),
  225. }
  226. }
  227. info := IPBanInfo{
  228. Reason: reason,
  229. OperReason: operReason,
  230. Time: banTime,
  231. }
  232. // save in datastore
  233. err = server.store.Update(func(tx *buntdb.Tx) error {
  234. dlineKey := fmt.Sprintf(keyDlineEntry, hostString)
  235. // assemble json from ban info
  236. b, err := json.Marshal(info)
  237. if err != nil {
  238. return err
  239. }
  240. tx.Set(dlineKey, string(b), nil)
  241. return nil
  242. })
  243. if hostNet == nil {
  244. server.dlines.AddIP(hostAddr, banTime, reason, operReason)
  245. } else {
  246. server.dlines.AddNetwork(*hostNet, banTime, reason, operReason)
  247. }
  248. if durationIsUsed {
  249. client.Notice(fmt.Sprintf("Added temporary (%s) D-Line for %s", duration.String(), hostString))
  250. } else {
  251. client.Notice(fmt.Sprintf("Added D-Line for %s", hostString))
  252. }
  253. return false
  254. }
  255. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  256. // check oper permissions
  257. if !client.class.Capabilities["oper:local_unban"] {
  258. client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
  259. return false
  260. }
  261. // get host
  262. hostString := msg.Params[0]
  263. // check host
  264. var hostAddr net.IP
  265. var hostNet *net.IPNet
  266. _, hostNet, err := net.ParseCIDR(hostString)
  267. if err != nil {
  268. hostAddr = net.ParseIP(hostString)
  269. }
  270. if hostAddr == nil && hostNet == nil {
  271. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Could not parse IP address or CIDR network")
  272. return false
  273. }
  274. if hostNet == nil {
  275. hostString = hostAddr.String()
  276. } else {
  277. hostString = hostNet.String()
  278. }
  279. // save in datastore
  280. err = server.store.Update(func(tx *buntdb.Tx) error {
  281. dlineKey := fmt.Sprintf(keyDlineEntry, hostString)
  282. // check if it exists or not
  283. val, err := tx.Get(dlineKey)
  284. if val == "" {
  285. return errNoExistingBan
  286. } else if err != nil {
  287. return err
  288. }
  289. tx.Delete(hostString)
  290. return nil
  291. })
  292. if err != nil {
  293. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf("Could not remove ban [%s]", err.Error()))
  294. }
  295. if hostNet == nil {
  296. server.dlines.RemoveIP(hostAddr)
  297. } else {
  298. server.dlines.RemoveNetwork(*hostNet)
  299. }
  300. client.Notice(fmt.Sprintf("Removed D-Line for %s", hostString))
  301. return false
  302. }
  303. func (s *Server) loadDLines() {
  304. s.dlines = NewDLineManager()
  305. // load from datastore
  306. s.store.View(func(tx *buntdb.Tx) error {
  307. //TODO(dan): We could make this safer
  308. tx.AscendKeys("bans.dline *", func(key, value string) bool {
  309. // get address name
  310. key = key[len("bans.dline "):]
  311. // load addr/net
  312. var hostAddr net.IP
  313. var hostNet *net.IPNet
  314. _, hostNet, err := net.ParseCIDR(key)
  315. if err != nil {
  316. hostAddr = net.ParseIP(key)
  317. }
  318. // load ban info
  319. var info IPBanInfo
  320. json.Unmarshal([]byte(value), &info)
  321. // add to the server
  322. if hostNet == nil {
  323. s.dlines.AddIP(hostAddr, info.Time, info.Reason, info.OperReason)
  324. } else {
  325. s.dlines.AddNetwork(*hostNet, info.Time, info.Reason, info.OperReason)
  326. }
  327. return true // true to continue I guess?
  328. })
  329. return nil
  330. })
  331. }