Skip to content

Instantly share code, notes, and snippets.

@theMiddleBlue
Last active April 14, 2020 12:33
Show Gist options
  • Save theMiddleBlue/12a6cdc44a046e2ffcca76c29dc30a02 to your computer and use it in GitHub Desktop.
Save theMiddleBlue/12a6cdc44a046e2ffcca76c29dc30a02 to your computer and use it in GitHub Desktop.
Nginx human user recognition
server {
listen 80;
server_name example.com;
encrypted_session_key 'v1-clG~!~v7B_Z0yu.:iw*Rj#l-Nc8E^';
encrypted_session_iv "themiddlerfvbgt5";
encrypted_session_expires 20;
location ~ /botbuster.js {
default_type 'text/javascript';
set_decode_base32 $enctoken $arg_t;
set_decrypt_session $plaintoken $enctoken;
set_encrypt_session $token "ts=$time_iso8601, src=$remote_addr, ua=$http_user_agent";
set_encode_base32 $token;
content_by_lua_block {
ts, src, ua = string.match(ngx.var.plaintoken, "ts.(.+). src.(.+). ua.(.+)")
local pass = 0
if src == ngx.var.remote_addr then
if ua == ngx.var.http_user_agent then
pass = 1
end
end
if pass == 1 then
ngx.say(" document.cookie = 'iamhuman=" .. ngx.var.token .. "'; ")
else
ngx.say(" console.log('Error: invalid token or session expired'); ")
end
}
}
location / {
default_type 'text/html';
set $allowreq 0;
set_decode_base32 $enciamhuman $cookie_iamhuman;
set_decrypt_session $plainiamhuman $enciamhuman;
set_by_lua_block $allowreq {
if ngx.var.cookie_iamhuman then
ts, src, ua = string.match(ngx.var.plainiamhuman, "ts.(.+). src.(.+). ua.(.+)")
if src == ngx.var.remote_addr then
if ua == ngx.var.http_user_agent then
return 1
end
end
end
return 0
}
if ($allowreq = 1) {
proxy_pass http://127.0.0.1:8888;
}
if ($allowreq = 0) {
set_encrypt_session $token "ts=$time_iso8601, src=$remote_addr, ua=$http_user_agent";
set_encode_base32 $token;
content_by_lua_block {
ngx.print('<html><head><script type=\'text/javascript\'>(function() { var as = document.createElement(\'script\'); as.type = \'text/javascript\'; as.async = true; as.src = \'/botbuster.js?t=' .. ngx.var.token .. '\'; var s = document.getElementsByTagName(\'script\')[0];s.parentNode.insertBefore(as, s); })();</script></head><body>checking if you are a human...<script> console.log("uhm"); setTimeout(function() { location.reload(); }, 1000); </script></body></html>')
ngx.exit(ngx.HTTP_OK)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment