mirror of
https://gitgud.io/fatchan/haproxy-protection.git
synced 2025-05-09 02:05:37 +00:00
Merge branch 'argon2' into kikeflare
This commit is contained in:
@ -37,6 +37,9 @@ Add some env vars to docker-compose file:
|
||||
- CHALLENGE_INCLUDES_IP - any value, whether to lock solved challenges to IP or tor circuit
|
||||
- BACKEND_NAME - Optional, name of backend to build from hosts.map
|
||||
- SERVER_PREFIX - Optional, prefix of server names used in server-template
|
||||
- POW_TIME - argon2 iterations
|
||||
- POW_KB - argon2 memory usage in KB
|
||||
- POW_DIFFICULTY - pow "difficulty" (you should change all 3 POW_ parameters to tune the difficulty)
|
||||
|
||||
Add a domain name + backend IP to `haproxy/hosts.map` like:
|
||||
```plain
|
||||
|
@ -5,6 +5,7 @@ services:
|
||||
# context: ./
|
||||
# dockerfile: tor/Dockerfile
|
||||
haproxy:
|
||||
network_mode: host
|
||||
ports:
|
||||
- 80:80
|
||||
build:
|
||||
@ -37,6 +38,9 @@ services:
|
||||
- BACKEND_NAME=servers
|
||||
- SERVER_PREFIX=websrv
|
||||
#- CHALLENGE_INCLUDES_IP=1
|
||||
- POW_TIME=1
|
||||
- POW_KB=6000
|
||||
- POW_DIFFICULTY=3
|
||||
nginx:
|
||||
ports:
|
||||
- 81:80
|
||||
|
@ -88,10 +88,9 @@ STOPSIGNAL SIGUSR1
|
||||
|
||||
ADD haproxy/docker-entrypoint.sh /usr/local/bin/
|
||||
RUN ln -s usr/local/bin/docker-entrypoint.sh / # backwards compat
|
||||
|
||||
# This is terrible mess but we need it for simple testing purposes of our POC
|
||||
RUN apt-get update && apt-get install socat dnsutils -y
|
||||
|
||||
RUN apt update && apt install -y git lua5.3 liblua5.3-dev argon2 libargon2-dev luarocks
|
||||
RUN git config --global url."https://".insteadOf git://
|
||||
RUN luarocks install argon2
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
|
||||
# no USER for backwards compatibility (to try to avoid breaking existing users)
|
||||
|
@ -6,6 +6,8 @@ global
|
||||
stats socket /var/run/haproxy.sock mode 666 level admin
|
||||
stats socket 127.0.0.1:1999 level admin
|
||||
httpclient.ssl.verify none
|
||||
# Allow larger buffer size for return-file of argon scripts
|
||||
tune.bufsize 51200
|
||||
|
||||
defaults
|
||||
mode http
|
||||
@ -49,10 +51,9 @@ frontend http-in
|
||||
acl ddos_mode_enabled base,map(/etc/haproxy/ddos.map) -m bool
|
||||
|
||||
# serve challenge page scripts directly from haproxy
|
||||
acl is_challenge_js path /js/challenge.js
|
||||
acl is_worker_js path /js/worker.js
|
||||
http-request return file /var/www/js/challenge.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if is_challenge_js
|
||||
http-request return file /var/www/js/worker.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if is_worker_js
|
||||
http-request return file /var/www/js/argon2.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /js/argon2.js }
|
||||
http-request return file /var/www/js/challenge.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /js/challenge.js }
|
||||
http-request return file /var/www/js/worker.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /js/worker.js }
|
||||
|
||||
# acl for domains in maintenance mode to return maintenance page (after challenge page htp-request return rules, for the footerlogo)
|
||||
acl maintenance_mode hdr(host),lower,map_str(/etc/haproxy/maintenance.map) -m found
|
||||
|
@ -0,0 +1 @@
|
||||
localhost 127.0.0.1:81
|
||||
|
1
haproxy/js/argon2.js
Normal file
1
haproxy/js/argon2.js
Normal file
File diff suppressed because one or more lines are too long
@ -2,21 +2,43 @@ function finishRedirect() {
|
||||
window.location=location.search.slice(1)+location.hash || "/";
|
||||
}
|
||||
|
||||
function finishPow(combined, answer) {
|
||||
document.cookie='z_ddos_pow='+combined+'#'+answer+';expires=Thu, 31-Dec-37 23:55:55 GMT; path=/; SameSite=Strict; '+(location.protocol==='https:'?'Secure=true; ':'');
|
||||
const hasCaptchaForm = document.querySelector('form');
|
||||
if (!hasCaptchaForm) {
|
||||
finishRedirect();
|
||||
function postResponse(powResponse, captchaResponse) {
|
||||
const body = {
|
||||
'pow_response': powResponse,
|
||||
};
|
||||
if (captchaResponse) {
|
||||
body['h-captcha-response'] = captchaResponse;
|
||||
body['g-recaptcha-response'] = captchaResponse;
|
||||
}
|
||||
fetch('/bot-check', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams(body),
|
||||
redirect: 'manual',
|
||||
}).then(res => {
|
||||
finishRedirect();
|
||||
})
|
||||
}
|
||||
|
||||
const powFinished = new Promise((resolve, reject) => {
|
||||
window.addEventListener('DOMContentLoaded', (event) => {
|
||||
const combined = document.querySelector('[data-pow]').dataset.pow;
|
||||
const [_userkey, challenge, _signature] = combined.split("#");
|
||||
window.addEventListener('DOMContentLoaded', async () => {
|
||||
const { time, kb, pow, diff } = document.querySelector('[data-pow]').dataset;
|
||||
const argonOpts = {
|
||||
time: time,
|
||||
mem: kb,
|
||||
hashLen: 32,
|
||||
parallelism: 1,
|
||||
type: argon2.ArgonType.Argon2id,
|
||||
};
|
||||
console.log('Got pow', pow, 'with difficulty', diff);
|
||||
const diffString = '0'.repeat(diff);
|
||||
const combined = pow;
|
||||
const [userkey, challenge, signature] = combined.split("#");
|
||||
const start = Date.now();
|
||||
if (window.Worker && crypto.subtle) {
|
||||
const threads = Math.min(2,Math.ceil(window.navigator.hardwareConcurrency/2));
|
||||
if (window.Worker) {
|
||||
const threads = Math.min(8,Math.ceil(window.navigator.hardwareConcurrency/2));
|
||||
let finished = false;
|
||||
const messageHandler = (e) => {
|
||||
if (finished) { return; }
|
||||
@ -26,58 +48,55 @@ const powFinished = new Promise((resolve, reject) => {
|
||||
console.log('Worker', workerId, 'returned answer', answer, 'in', Date.now()-start+'ms');
|
||||
const dummyTime = 5000 - (Date.now()-start);
|
||||
window.setTimeout(() => {
|
||||
finishPow(combined, answer);
|
||||
resolve();
|
||||
resolve(`${combined}#${answer}`);
|
||||
}, dummyTime);
|
||||
}
|
||||
const workers = [];
|
||||
for (let i = 0; i < threads; i++) {
|
||||
const shaWorker = new Worker('/js/worker.js');
|
||||
shaWorker.onmessage = messageHandler;
|
||||
workers.push(shaWorker);
|
||||
const argonWorker = new Worker('/js/worker.js');
|
||||
argonWorker.onmessage = messageHandler;
|
||||
workers.push(argonWorker);
|
||||
}
|
||||
workers.forEach((w, i) => w.postMessage([challenge, i, threads]));
|
||||
workers.forEach(async (w, i) => {
|
||||
await new Promise(res => setTimeout(res, 100));
|
||||
w.postMessage([userkey, challenge, diffString, argonOpts, i, threads]);
|
||||
});
|
||||
} else {
|
||||
console.warn('No webworker or crypto.subtle support, using legacy method in main/UI thread!');
|
||||
function sha256(ascii){function rightRotate(value,amount){return(value>>>amount)|(value<<(32-amount))};var mathPow=Math.pow;var maxWord=mathPow(2,32);var lengthProperty='length';var i,j;var result='';var words=[];var asciiBitLength=ascii[lengthProperty]*8;var hash=sha256.h=sha256.h||[];var k=sha256.k=sha256.k||[];var primeCounter=k[lengthProperty];var isComposite={};for(var candidate=2;primeCounter<64;candidate+=1){if(!isComposite[candidate]){for(i=0;i<313;i+=candidate){isComposite[i]=candidate}hash[primeCounter]=(mathPow(candidate,.5)*maxWord)|0;k[primeCounter++]=(mathPow(candidate,1/3)*maxWord)|0}}ascii+='\x80';while(ascii[lengthProperty]%64-56){ascii+='\x00';}for(i=0;i<ascii[lengthProperty];i+=1){j=ascii.charCodeAt(i);if(j>>8){return;}words[i>>2]|=j<<((3-i)%4)*8}words[words[lengthProperty]]=((asciiBitLength/maxWord)|0);words[words[lengthProperty]]=(asciiBitLength);for(j=0;j<words[lengthProperty];){var w=words.slice(j,j+=16);var oldHash=hash;hash=hash.slice(0,8);for(i=0;i<64;i+=1){var i2=i+j;var w15=w[i-15],w2=w[i-2];var a=hash[0],e=hash[4];var temp1=hash[7]+(rightRotate(e,6)^rightRotate(e,11)^rightRotate(e,25))+((e&hash[5])^((~e)&hash[6]))+k[i]+(w[i]=(i<16)?w[i]:(w[i-16]+(rightRotate(w15,7)^rightRotate(w15,18)^(w15>>>3))+w[i-7]+(rightRotate(w2,17)^rightRotate(w2,19)^(w2>>>10)))|0);var temp2=(rightRotate(a,2)^rightRotate(a,13)^rightRotate(a,22))+((a&hash[1])^(a&hash[2])^(hash[1]&hash[2]));hash=[(temp1+temp2)|0].concat(hash);hash[4]=(hash[4]+temp1)|0}for(i=0;i<8;i+=1){hash[i]=(hash[i]+oldHash[i])|0}}for(i=0;i<8;i+=1){for(j=3;j+1;j-=1){var b=(hash[i]>>(j*8))&255;result+=((b<16)?0:'')+b.toString(16)}}return result}
|
||||
const challengeIndex = parseInt(challenge[0], 16)*2;
|
||||
let i = 0
|
||||
, result;
|
||||
console.warn('No webworker support, running in main/UI thread!');
|
||||
let i = 0;
|
||||
let start = Date.now();
|
||||
while(true) {
|
||||
result = sha256(challenge+i);
|
||||
if (result.substring(challengeIndex, challengeIndex+4) === '0041'){
|
||||
console.log('Main thread found solution:', i, result);
|
||||
const hash = await argon2.hash({
|
||||
pass: challenge + i.toString(),
|
||||
salt: userkey,
|
||||
...argonOpts,
|
||||
});
|
||||
if (hash.hashHex.startsWith(diffString)) {
|
||||
console.log('Main thread found solution:', hash.hashHex, 'in', (Date.now()-start)+'ms');
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
const dummyTime = 5000 - (Date.now()-start);
|
||||
window.setTimeout(() => {
|
||||
finishPow(combined, i);
|
||||
resolve();
|
||||
resolve(`${combined}#${i}`);
|
||||
}, dummyTime);
|
||||
}
|
||||
});
|
||||
}).then((powResponse) => {
|
||||
const hasCaptchaForm = document.getElementById('captcha');
|
||||
if (!hasCaptchaForm) {
|
||||
postResponse(powResponse);
|
||||
}
|
||||
return powResponse;
|
||||
});
|
||||
|
||||
function onCaptchaSubmit(callback) {
|
||||
function onCaptchaSubmit(captchaResponse) {
|
||||
const captchaElem = document.querySelector('[data-sitekey]');
|
||||
captchaElem.insertAdjacentHTML('afterend', `<div class="lds-ring"><div></div><div></div><div></div><div></div></div>`);
|
||||
captchaElem.remove();
|
||||
powFinished.then(() => {
|
||||
fetch('/bot-check', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
'h-captcha-response': callback,
|
||||
'g-recaptcha-response': callback,
|
||||
}),
|
||||
redirect: 'manual',
|
||||
}).then(res => {
|
||||
finishRedirect();
|
||||
})
|
||||
powFinished.then((powResponse) => {
|
||||
postResponse(powResponse, captchaResponse);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -1,19 +1,19 @@
|
||||
async function hash(data, method) {
|
||||
const buffer = new TextEncoder('utf-8').encode(data);
|
||||
const hashBuffer = await crypto.subtle.digest(method, buffer)
|
||||
return Array.from(new Uint8Array(hashBuffer));
|
||||
}
|
||||
importScripts('/js/argon2.js');
|
||||
|
||||
onmessage = async function(e) {
|
||||
const [challenge, id, threads] = e.data;
|
||||
console.log('Worker thread', id,'got challenge', challenge);
|
||||
const [userkey, challenge, diffString, argonOpts, id, threads] = e.data;
|
||||
console.log('Worker thread', id, 'started');
|
||||
let i = id;
|
||||
let challengeIndex = parseInt(challenge[0], 16);
|
||||
while(true) {
|
||||
let result = await hash(challenge+i, 'sha-256');
|
||||
if(result[challengeIndex] === 0x00
|
||||
&& result[challengeIndex+1] === 0x41){
|
||||
console.log('Worker thread found solution:', i);
|
||||
const hash = await argon2.hash({
|
||||
pass: challenge + i.toString(),
|
||||
salt: userkey,
|
||||
...argonOpts,
|
||||
});
|
||||
// This throttle seems to really help some browsers not stop the workers abruptly
|
||||
i % 10 === 0 && await new Promise(res => setTimeout(res, 10));
|
||||
if (hash.hashHex.startsWith(diffString)) {
|
||||
console.log('Worker', id, 'found solution');
|
||||
postMessage([id, i]);
|
||||
break;
|
||||
}
|
||||
|
@ -6,6 +6,18 @@ local cookie = require("cookie")
|
||||
local json = require("json")
|
||||
local sha = require("sha")
|
||||
local randbytes = require("randbytes")
|
||||
local argon2 = require("argon2")
|
||||
local pow_difficulty = tonumber(os.getenv("POW_DIFFICULTY") or 3)
|
||||
local pow_kb = tonumber(os.getenv("POW_KB") or 6000)
|
||||
local pow_time = tonumber(os.getenv("POW_TIME") or 1)
|
||||
argon2.t_cost(pow_time)
|
||||
argon2.m_cost(pow_kb)
|
||||
argon2.parallelism(1)
|
||||
argon2.hash_len(32)
|
||||
argon2.variant(argon2.variants.argon2_id)
|
||||
|
||||
-- Testing only
|
||||
-- require("socket")
|
||||
-- require("print_r")
|
||||
|
||||
local captcha_secret = os.getenv("HCAPTCHA_SECRET") or os.getenv("RECAPTCHA_SECRET")
|
||||
@ -80,7 +92,7 @@ local body_template = [[
|
||||
img,h3,p{margin:0 0 5px 0}
|
||||
footer{font-size:x-small;margin-top:auto;margin-bottom:20px;text-align:center}
|
||||
img{display:inline}
|
||||
.pt{padding-top:15vh;display:flex;align-items: center}
|
||||
.pt{padding-top:15vh;display:flex;align-items:center;word-break:break-all}
|
||||
.pt img{margin-right:10px}
|
||||
details[open]{border-left-color: #1400ff}
|
||||
.lds-ring{display:inline-block;position:relative;width:80px;height:80px}.lds-ring div{box-sizing:border-box;display:block;position:absolute;width:32px;height:32px;margin:10px;border:5px solid var(--text-color);border-radius:50%%;animation:lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;border-color:var(--text-color) transparent transparent transparent}.lds-ring div:nth-child(1){animation-delay:-0.45s}.lds-ring div:nth-child(2){animation-delay:-0.3s}.lds-ring div:nth-child(3){animation-delay:-0.15s}@keyframes lds-ring{0%%{transform:rotate(0deg)}100%%{transform:rotate(360deg)}}
|
||||
@ -88,9 +100,10 @@ local body_template = [[
|
||||
<noscript>
|
||||
<style>.jsonly{display:none}</style>
|
||||
</noscript>
|
||||
<script src="/js/argon2.js"></script>
|
||||
<script src="/js/challenge.js"></script>
|
||||
</head>
|
||||
<body data-pow="%s">
|
||||
<body data-pow="%s" data-diff="%s" data-time="%s" data-kb="%s">
|
||||
%s
|
||||
%s
|
||||
%s
|
||||
@ -113,12 +126,15 @@ local noscript_extra_template = [[
|
||||
<summary>No JavaScript?</summary>
|
||||
<ol>
|
||||
<li>
|
||||
<p>Run this in a linux terminal:</p>
|
||||
<p>Run this in a linux terminal (requires <code>argon2</code> package installed):</p>
|
||||
<code style="word-break: break-all;">
|
||||
echo "Q0g9IiQyIjtCPSIwMDQxIjtJPTA7RElGRj0kKCgxNiMke0NIOjA6MX0gKiAyKSk7d2hpbGUgdHJ1ZTsgZG8gSD0kKGVjaG8gLW4gJENIJEkgfCBzaGEyNTZzdW0pO0U9JHtIOiRESUZGOjR9O1tbICRFID09ICRCIF1dICYmIGVjaG8gJDEjJDIjJDMjJEkgJiYgZXhpdCAwOygoSSsrKSk7ZG9uZTs=" | base64 -d | bash -s %s %s %s
|
||||
echo "Q0g9IiQyIjtCPSQocHJpbnRmICcwJS4wcycgJChzZXEgMSAkNCkpO2VjaG8gIldvcmtpbmcuLi4iO0k9MDt3aGlsZSB0cnVlOyBkbyBIPSQoZWNobyAtbiAkQ0gkSSB8IGFyZ29uMiAkMSAtaWQgLXQgJDUgLWsgJDYgLXAgMSAtbCAzMiAtcik7RT0ke0g6MDokNH07W1sgJEUgPT0gJEIgXV0gJiYgZWNobyAiT3V0cHV0OiIgJiYgZWNobyAkMSMkMiMkMyMkSSAmJiBleGl0IDA7KChJKyspKTtkb25lOwo=" | base64 -d | bash -s %s %s %s %s %s %s
|
||||
</code>
|
||||
<li>Set a cookie named <code>z_ddos_pow</code> with the value as the script output, and path <code>/</code>.
|
||||
<li>Remove <code>/bot-check?</code> from the url, and reload the page.
|
||||
<li>Paste the output from the script into the box and submit:
|
||||
<form method="POST">
|
||||
<textarea type="text" name="pow_response"></textarea>
|
||||
<input type="submit" value="submit" />
|
||||
</form>
|
||||
</ol>
|
||||
</details>
|
||||
]]
|
||||
@ -146,25 +162,26 @@ local captcha_section_template = [[
|
||||
<h3>
|
||||
Please solve the captcha to continue.
|
||||
</h3>
|
||||
<form class="jsonly" method="POST">
|
||||
<div id="captcha" class="jsonly">
|
||||
<div class="%s" data-sitekey="%s" data-callback="onCaptchaSubmit"></div>
|
||||
<script src="%s" async defer></script>
|
||||
</form>
|
||||
</div>
|
||||
]]
|
||||
|
||||
function _M.view(applet)
|
||||
|
||||
-- set response body and declare status code
|
||||
local response_body = ""
|
||||
local response_status_code
|
||||
|
||||
-- if request is GET, serve the challenge page
|
||||
if applet.method == "GET" then
|
||||
|
||||
-- get the user_key#challenge#sig
|
||||
local user_key = sha.bin_to_hex(randbytes(16))
|
||||
local challenge_hash = utils.generate_secret(applet, pow_cookie_secret, user_key, true)
|
||||
local signature = sha.hmac(sha.sha256, hmac_cookie_secret, user_key .. challenge_hash)
|
||||
local combined_challenge = user_key .. "#" .. challenge_hash .. "#" .. signature
|
||||
-- print_r(user_key)
|
||||
-- print_r(challenge_hash)
|
||||
-- print_r(signature)
|
||||
-- print_r(combined_challenge)
|
||||
|
||||
-- define body sections
|
||||
local site_name_body = ""
|
||||
@ -186,28 +203,47 @@ function _M.view(applet)
|
||||
-- pow at least is always enabled when reaching bot-check page
|
||||
site_name_body = string.format(site_name_section_template, host)
|
||||
if captcha_enabled then
|
||||
captcha_body = string.format(captcha_section_template, captcha_classname, captcha_sitekey, captcha_script_src)
|
||||
captcha_body = string.format(captcha_section_template, captcha_classname,
|
||||
captcha_sitekey, captcha_script_src)
|
||||
else
|
||||
pow_body = pow_section_template
|
||||
noscript_extra_body = string.format(noscript_extra_template, user_key, challenge_hash, signature)
|
||||
noscript_extra_body = string.format(noscript_extra_template, user_key, challenge_hash, signature,
|
||||
pow_difficulty, pow_time, pow_kb)
|
||||
end
|
||||
|
||||
-- sub in the body sections
|
||||
response_body = string.format(body_template, combined_challenge, site_name_body, pow_body, captcha_body, noscript_extra_body, ray_id)
|
||||
response_body = string.format(body_template, combined_challenge,
|
||||
pow_difficulty, pow_time, pow_kb,
|
||||
site_name_body, pow_body, captcha_body, noscript_extra_body, ray_id)
|
||||
response_status_code = 403
|
||||
|
||||
-- if request is POST, check the answer to the pow/cookie
|
||||
elseif applet.method == "POST" then
|
||||
|
||||
-- parsed POST body
|
||||
local parsed_body = url.parseQuery(applet.receive(applet))
|
||||
|
||||
-- whether to set cookies sent as secure or not
|
||||
local secure_cookie_flag = " Secure=true;"
|
||||
if applet.sf:ssl_fc() == "0" then
|
||||
secure_cookie_flag = ""
|
||||
end
|
||||
|
||||
-- handle setting the captcha cookie
|
||||
local user_captcha_response = parsed_body["h-captcha-response"] or parsed_body["g-recaptcha-response"]
|
||||
if user_captcha_response then
|
||||
-- format the url for verifying the captcha response
|
||||
local captcha_url = string.format(
|
||||
"https://%s%s",
|
||||
core.backends[captcha_backend_name].servers[captcha_backend_name]:get_addr(),
|
||||
captcha_siteverify_path
|
||||
)
|
||||
-- construct the captcha body to send to the captcha url
|
||||
local captcha_body = url.buildQuery({
|
||||
secret=captcha_secret,
|
||||
response=user_captcha_response
|
||||
})
|
||||
-- instantiate an http client and make the request
|
||||
local httpclient = core.httpclient()
|
||||
local res = httpclient:post{
|
||||
url=captcha_url,
|
||||
@ -217,42 +253,95 @@ function _M.view(applet)
|
||||
[ "content-type" ] = { "application/x-www-form-urlencoded" }
|
||||
}
|
||||
}
|
||||
-- try parsing the response as json
|
||||
local status, api_response = pcall(json.decode, res.body)
|
||||
if not status then
|
||||
api_response = {}
|
||||
end
|
||||
-- the response was good i.e the captcha provider says they passed, give them a cookie
|
||||
if api_response.success == true then
|
||||
-- for captcha, they dont need to solve a POW but we check the user_hash and sig later
|
||||
|
||||
local user_key = sha.bin_to_hex(randbytes(16))
|
||||
local user_hash = utils.generate_secret(applet, captcha_cookie_secret, user_key, true)
|
||||
local signature = sha.hmac(sha.sha256, hmac_cookie_secret, user_key .. user_hash)
|
||||
local combined_cookie = user_key .. "#" .. user_hash .. "#" .. signature
|
||||
local secure_cookie_flag = " Secure=true;"
|
||||
if applet.sf:ssl_fc() == "0" then
|
||||
secure_cookie_flag = ""
|
||||
end
|
||||
applet:add_header(
|
||||
"set-cookie",
|
||||
string.format(
|
||||
"z_ddos_captcha=%s; Expires=Thu, 31-Dec-37 23:55:55 GMT; Path=/; SameSite=Strict;",
|
||||
"z_ddos_captcha=%s; Expires=Thu, 31-Dec-37 23:55:55 GMT; Path=/; SameSite=Strict;%s",
|
||||
combined_cookie,
|
||||
secure_cookie_flag
|
||||
)
|
||||
)
|
||||
|
||||
end
|
||||
end
|
||||
-- if failed captcha, will just get sent back here so 302 is fine
|
||||
|
||||
-- handle setting the POW cookie
|
||||
local user_pow_response = parsed_body["pow_response"]
|
||||
if user_pow_response then
|
||||
|
||||
-- split the response up (makes the nojs submission easier because it can be a single field)
|
||||
local split_response = utils.split(user_pow_response, "#")
|
||||
if #split_response == 4 then
|
||||
local given_user_key = split_response[1]
|
||||
local given_challenge_hash = split_response[2]
|
||||
local given_signature = split_response[3]
|
||||
local given_answer = split_response[4]
|
||||
|
||||
-- regenerate the challenge and compare it
|
||||
local generated_challenge_hash = utils.generate_secret(applet, pow_cookie_secret, given_user_key, true)
|
||||
if given_challenge_hash == generated_challenge_hash then
|
||||
|
||||
-- regenerate the signature and compare it
|
||||
local generated_signature = sha.hmac(sha.sha256, hmac_cookie_secret, given_user_key .. given_challenge_hash)
|
||||
if given_signature == generated_signature then
|
||||
|
||||
-- do the work with their given answer
|
||||
local full_hash = argon2.hash_encoded(given_challenge_hash .. given_answer, given_user_key)
|
||||
|
||||
-- check the output is correct
|
||||
local hash_output = utils.split(full_hash, '$')[5]:sub(0, 43) -- https://github.com/thibaultcha/lua-argon2/issues/37
|
||||
local hex_hash_output = sha.bin_to_hex(sha.base64_to_bin(hash_output));
|
||||
local hex_hash_sub = hex_hash_output:sub(0, pow_difficulty)
|
||||
|
||||
if hex_hash_sub == string.rep('0', pow_difficulty) then
|
||||
|
||||
-- the answer was good, give them a cookie
|
||||
local signature = sha.hmac(sha.sha256, hmac_cookie_secret, given_user_key .. given_challenge_hash .. given_answer)
|
||||
local combined_cookie = given_user_key .. "#" .. given_challenge_hash .. "#" .. given_answer .. "#" .. signature
|
||||
applet:add_header(
|
||||
"set-cookie",
|
||||
string.format(
|
||||
"z_ddos_pow=%s; Expires=Thu, 31-Dec-37 23:55:55 GMT; Path=/; SameSite=Strict;%s",
|
||||
combined_cookie,
|
||||
secure_cookie_flag
|
||||
)
|
||||
)
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- redirect them to their desired page in applet.qs (query string)
|
||||
-- if they didn't get the appropriate cookies they will be sent back to the challenge page
|
||||
response_status_code = 302
|
||||
applet:add_header("location", applet.qs)
|
||||
|
||||
-- else if its another http method, just 403 them
|
||||
else
|
||||
-- other methods
|
||||
response_status_code = 403
|
||||
end
|
||||
|
||||
-- finish sending the response
|
||||
applet:set_status(response_status_code)
|
||||
applet:add_header("content-type", "text/html; charset=utf-8")
|
||||
applet:add_header("content-length", string.len(response_body))
|
||||
applet:start_response()
|
||||
applet:send(response_body)
|
||||
|
||||
end
|
||||
|
||||
-- check if captcha is enabled, path+domain priority, then just domain, and 0 otherwise
|
||||
@ -274,6 +363,7 @@ end
|
||||
function _M.check_captcha_status(txn)
|
||||
local parsed_request_cookies = cookie.get_cookie_table(txn.sf:hdr("Cookie"))
|
||||
local received_captcha_cookie = parsed_request_cookies["z_ddos_captcha"] or ""
|
||||
-- split the cookie up
|
||||
local split_cookie = utils.split(received_captcha_cookie, "#")
|
||||
if #split_cookie ~= 3 then
|
||||
return
|
||||
@ -304,22 +394,16 @@ function _M.check_pow_status(txn)
|
||||
end
|
||||
local given_user_key = split_cookie[1]
|
||||
local given_challenge_hash = split_cookie[2]
|
||||
local given_signature = split_cookie[3]
|
||||
local given_nonce = split_cookie[4]
|
||||
local given_answer = split_cookie[3]
|
||||
local given_signature = split_cookie[4]
|
||||
-- regenerate the challenge and compare it
|
||||
local generated_challenge_hash = utils.generate_secret(txn, pow_cookie_secret, given_user_key, false)
|
||||
if given_challenge_hash ~= generated_challenge_hash then
|
||||
return
|
||||
end
|
||||
-- regenerate the signature and compare it
|
||||
local generated_signature = sha.hmac(sha.sha256, hmac_cookie_secret, given_user_key .. given_challenge_hash)
|
||||
if given_signature ~= generated_signature then
|
||||
return
|
||||
end
|
||||
-- check the work
|
||||
local completed_work = sha.sha256(generated_challenge_hash .. given_nonce)
|
||||
local challenge_offset = tonumber(generated_challenge_hash:sub(1,1),16) * 2
|
||||
if completed_work:sub(challenge_offset+1, challenge_offset+4) == '0041' then -- i dont know lua properly :^)
|
||||
local generated_signature = sha.hmac(sha.sha256, hmac_cookie_secret, given_user_key .. given_challenge_hash .. given_answer)
|
||||
if given_signature == generated_signature then
|
||||
return txn:set_var("txn.pow_passed", true)
|
||||
end
|
||||
end
|
||||
|
Reference in New Issue
Block a user