limit_local_access.lua 1.15 KB
-- author: chunhua.zhang
-- only allow request from local ip and nat ip
-- depends on param: [ngx.var.real_ip], which should be setted up by 'setup.lua'
local iptool=require "iptool" 
local http_request = require "http_request"

local local_cidr = {
    "10.66.0.0/16",
    "10.67.0.0/16",
    "192.168.0.0/16",
    "172.31.0.0/16",
    "127.0.0.1",
    "188.131.200.225",
    "188.131.173.189",
    "118.89.221.106",
    "123.206.21.19",
    "123.206.73.107"
}

 -- check if ip is local
 -- depends on $real_ip which setup by  setup.lua
function check_local_access()
    
    -- read ip from ngx.var.real_ip
    local ip = ngx.var.real_ip
    if (ip == nil or ip == '') then
        return
    end

    local is_local_ip = false
    for i = 1, #local_cidr do
      local is_in_cidr = iptool:pcall_check_ip_in_ipblock(ip, local_cidr[i],false)
      if is_in_cidr then
        is_local_ip = true
        break
      end
    end
    
    if not is_local_ip then
        ngx.exit(403);
        return
    end
end

---- running------
local status, errMsg = pcall(check_local_access)
if not status then
  ngx.log(ngx.ERR, "call method [check_local_access] failed.", errMsg)
end