main.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. local t1k = require "resty.t1k"
  2. local t1k_constants = require "resty.t1k.constants"
  3. local ngx = ngx
  4. local fmt = string.format
  5. local blocked_message = [[{"code": %s, "success":false, ]] ..
  6. [["message": "blocked by Chaitin SafeLine Web Application Firewall", "event_id": "%s"}]]
  7. local _M = {}
  8. local mode = os.getenv("SAFELINE_MODE")
  9. local host = os.getenv("SAFELINE_HOST")
  10. local port = os.getenv("SAFELINE_PORT")
  11. local connect_timeout = os.getenv("SAFELINE_CONNECT_TIMEOUT")
  12. local send_timeout = os.getenv("SAFELINE_SEND_TIMEOUT")
  13. local read_timeout = os.getenv("SAFELINE_READ_TIMEOUT")
  14. local req_body_size = os.getenv("SAFELINE_REQ_BODY_SIZE")
  15. local keepalive_size = os.getenv("SAFELINE_KEEPALIVE_SIZE")
  16. local keepalive_timeout = os.getenv("SAFELINE_KEEPALIVE_TIMEOUT")
  17. local remote_addr = os.getenv("SAFELINE_REMOTE_ADDR")
  18. local function get_conf()
  19. local t = {
  20. mode = mode or "block",
  21. host = host,
  22. port = port,
  23. connect_timeout = connect_timeout or 1000,
  24. send_timeout = send_timeout or 1000,
  25. read_timeout = read_timeout or 1000,
  26. req_body_size = req_body_size or 1024,
  27. keepalive_size = keepalive_size or 256,
  28. keepalive_timeout = keepalive_timeout or 60000,
  29. remote_addr = remote_addr
  30. }
  31. return t
  32. end
  33. function _M.rewrite()
  34. local t = get_conf()
  35. if not t.host then
  36. ngx.log(ngx.ERR, "safeline host is required")
  37. return
  38. end
  39. local ok, err, result = t1k.do_access(t, false)
  40. if not ok then
  41. ngx.log(ngx.ERR, "failed to detector req: ", err)
  42. return
  43. end
  44. if result then
  45. if result.action == t1k_constants.ACTION_BLOCKED then
  46. local msg = fmt(blocked_message, result.status, result.event_id)
  47. ngx.log(ngx.ERR, "blocked by safeline waf: ",msg)
  48. ngx.status = tonumber(result.status,10)
  49. ngx.say(msg)
  50. return ngx.exit(ngx.HTTP_OK)
  51. end
  52. end
  53. end
  54. return _M