Merge branch 'next' into kikeflare

This commit is contained in:
Thomas Lynch
2023-02-11 23:49:49 +11:00
28 changed files with 444 additions and 344 deletions

View File

@ -40,38 +40,38 @@ frontend http-in
#option forwardfor
# drop requests with invalid host header
acl is_existing_vhost hdr(host),lower,map_str(/etc/haproxy/hosts.map) -m found
acl is_existing_vhost hdr(host),lower,map_str(/etc/haproxy/map/hosts.map) -m found
http-request silent-drop unless is_existing_vhost
# debug only, /cdn-cgi/trace
#http-request return status 200 content-type "text/plain; charset=utf-8" lf-file /etc/haproxy/trace.txt if { path /cdn-cgi/trace }
# debug information at /.basedflare/cgi/trace
http-request return status 200 content-type "text/plain; charset=utf-8" lf-file /etc/haproxy/template/trace.txt if { path /.basedflare/cgi/trace }
# acl for blocked IPs/subnets
acl blocked_ip_or_subnet src,map_ip(/etc/haproxy/blocked.map) -m found
acl blocked_ip_or_subnet src,map_ip(/etc/haproxy/map/blocked.map) -m found
http-request deny deny_status 403 if blocked_ip_or_subnet
# ratelimit (and for tor, kill circuit) on POST bot-check. legitimate users shouldn't hit this.
http-request track-sc0 src table bot_check_post_throttle if { path /bot-check } { method POST }
http-request track-sc0 src table bot_check_post_throttle if { path /.basedflare/bot-check } { method POST }
http-request lua.kill-tor-circuit if { sc_http_req_rate(0) gt 1 }
http-request tarpit if { sc_http_req_rate(0) gt 1 }
# acl for lua check whitelisted IPs/subnets and some excluded paths
acl is_excluded src,map_ip(/etc/haproxy/whitelist.map) -m found
acl is_excluded src,map_ip(/etc/haproxy/map/whitelist.map) -m found
acl is_excluded path /favicon.ico #add more
# acl ORs for when ddos_mode_enabled
acl ddos_mode_enabled_override hdr_cnt(xr3la1rfFc) eq 0
acl ddos_mode_enabled hdr(host),lower,map(/etc/haproxy/ddos.map) -m bool
acl ddos_mode_enabled base,map(/etc/haproxy/ddos.map) -m bool
acl ddos_mode_enabled hdr(host),lower,map(/etc/haproxy/map/ddos.map) -m bool
acl ddos_mode_enabled base,map(/etc/haproxy/map/ddos.map) -m bool
# serve challenge page scripts directly from haproxy
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 }
http-request return file /etc/haproxy/js/argon2.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /.basedflare/js/argon2.js }
http-request return file /etc/haproxy/js/challenge.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /.basedflare/js/challenge.js }
http-request return file /etc/haproxy/js/worker.js status 200 content-type "application/javascript; charset=utf-8" hdr "cache-control" "public, max-age=300" if { path /.basedflare/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
http-request return file /var/www/html/maintenance.html status 200 content-type "text/html; charset=utf-8" hdr "cache-control" "private, max-age=30" if maintenance_mode
acl maintenance_mode hdr(host),lower,map_str(/etc/haproxy/map/maintenance.map) -m found
http-request return lf-file /etc/haproxy/template/maintenance.html status 200 content-type "text/html; charset=utf-8" hdr "cache-control" "private, max-age=30" if maintenance_mode
# create acl for bools updated by lua
acl captcha_passed var(txn.captcha_passed) -m bool
@ -80,14 +80,14 @@ frontend http-in
acl validate_pow var(txn.validate_pow) -m bool
# check pow/captcha and show page if necessary
acl on_captcha_url path /bot-check
http-request use-service lua.hcaptcha-view if on_captcha_url !is_excluded
acl on_bot_check path /.basedflare/bot-check
http-request use-service lua.bot-check if on_bot_check !is_excluded
# challenge decisions, checking, and redirecting to /bot-check
http-request lua.decide-checks-necessary if !is_excluded !on_captcha_url ddos_mode_enabled
http-request lua.hcaptcha-check if !is_excluded !on_captcha_url validate_captcha
http-request lua.pow-check if !is_excluded !on_captcha_url validate_pow OR !is_excluded !on_captcha_url ddos_mode_enabled_override
http-request redirect location /bot-check?%[capture.req.uri] code 302 if validate_captcha !captcha_passed !on_captcha_url ddos_mode_enabled !is_excluded OR validate_pow !pow_passed !on_captcha_url ddos_mode_enabled !is_excluded OR !pow_passed ddos_mode_enabled_override !on_captcha_url !is_excluded
http-request lua.decide-checks-necessary if !is_excluded !on_bot_check ddos_mode_enabled
http-request lua.captcha-check if !is_excluded !on_bot_check validate_captcha
http-request lua.pow-check if !is_excluded !on_bot_check validate_pow OR !is_excluded !on_bot_check ddos_mode_enabled_override
http-request redirect location /.basedflare/bot-check?%[capture.req.uri] code 302 if validate_captcha !captcha_passed !on_bot_check ddos_mode_enabled !is_excluded OR validate_pow !pow_passed !on_bot_check ddos_mode_enabled !is_excluded OR !pow_passed ddos_mode_enabled_override !on_bot_check !is_excluded
# X-Cache-Status header (may be sent in some non-cache responses because NOSRV can happen for other reasons, but should always be present in responses served by cache-use)
http-response set-header X-Cache-Status HIT if !{ srv_id -m found }
@ -111,7 +111,7 @@ backend servers
# placeholder servers, activated by LUA or the control panel
server-template websrv 1-100 0.0.0.0:80 check disabled
# use server based on hostname
use-server %[req.hdr(host),lower,map(/etc/haproxy/backends.map)] if TRUE
use-server %[req.hdr(host),lower,map(/etc/haproxy/map/backends.map)] if TRUE
backend bot_check_post_throttle
stick-table type ipv6 size 100k expire 60s store http_req_rate(60s)

File diff suppressed because one or more lines are too long

View File

@ -1,157 +0,0 @@
function updateElem(selector, text) {
document.querySelector(selector)
.innerText = text;
}
function insertError(str) {
const ring = document.querySelector('.lds-ring');
const captcha = document.querySelector('#captcha');
(ring || captcha).insertAdjacentHTML('afterend', `<p class="red">Error: ${str}</p>`);
ring && ring.remove();
captcha && captcha.remove();
updateElem('.powstatus', '');
}
function finishRedirect() {
window.location=location.search.slice(1)+location.hash || "/";
}
const wasmSupported = (() => {
try {
if (typeof WebAssembly === "object"
&& typeof WebAssembly.instantiate === "function") {
const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
if (module instanceof WebAssembly.Module)
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
}
} catch (e) {
}
return false;
})();
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 => {
const s = res.status;
if (s >= 400 && s < 500) {
return insertError('bad challenge response request.');
} else if (s >= 500) {
return insertError('server responded with error.');
}
finishRedirect();
}).catch(err => {
insertError('failed to send challenge response.');
});
}
const powFinished = new Promise((resolve, reject) => {
window.addEventListener('DOMContentLoaded', async () => {
if (!wasmSupported) {
return insertError('browser does not support WebAssembly.');
}
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 eHashes = Math.pow(16, Math.floor(diff/8)) * ((diff%8)*2);
const diffString = '0'.repeat(Math.floor(diff/8));
const combined = pow;
const [userkey, challenge, signature] = combined.split("#");
const start = Date.now();
if (window.Worker) {
const cpuThreads = window.navigator.hardwareConcurrency;
const isTor = location.hostname.endsWith('.onion');
/* Try to use all threads on tor, because tor limits threads for anti fingerprinting but this
makes it awfully slow because workerThreads will always be = 1 */
const workerThreads = isTor ? cpuThreads : Math.max(Math.ceil(cpuThreads/2),cpuThreads-1);
let finished = false;
const messageHandler = (e) => {
if (e.data.length === 1) {
const totalHashes = e.data[0]; //assumes all worker threads are same speed
const elapsedSec = Math.floor((Date.now()-start)/1000);
const hps = Math.floor(totalHashes/elapsedSec);
const requiredSec = Math.floor(eHashes/hps) * 1.5; //estimate 1.5x time
const remainingSec = Math.max(0, Math.floor(requiredSec-elapsedSec)); //dont show negative time
return updateElem('.powstatus', `Proof-of-work: ${hps}H/s, ~${remainingSec}s remaining`);
}
if (finished) { return; }
finished = true;
const hasCaptcha = document.getElementById('captcha');
updateElem('.powstatus', `Found proof-of-work solution.${!hasCaptcha?' Submitting...':''}`);
workers.forEach(w => w.terminate());
const [workerId, answer] = e.data;
console.log('Worker', workerId, 'returned answer', answer, 'in', Date.now()-start+'ms');
const dummyTime = 5000 - (Date.now()-start);
window.setTimeout(() => {
resolve(`${combined}#${answer}`);
}, dummyTime);
}
const workers = [];
for (let i = 0; i < workerThreads; i++) {
const argonWorker = new Worker('/js/worker.js');
argonWorker.onmessage = messageHandler;
workers.push(argonWorker);
}
for (let i = 0; i < workerThreads; i++) {
await new Promise(res => setTimeout(res, 100));
workers[i].postMessage([userkey, challenge, diff, diffString, argonOpts, i, workerThreads]);
}
} else {
console.warn('No webworker support, running in main/UI thread!');
let i = 0;
let start = Date.now();
while(true) {
const hash = await argon2.hash({
pass: challenge + i.toString(),
salt: userkey,
...argonOpts,
});
if (hash.hashHex.startsWith(diffString)
&& ((parseInt(hash.hashHex[diffString.length],16) &
0xff >> (((diffString.length+1)*8)-diff)) === 0)) {
console.log('Main thread found solution:', hash.hashHex, 'in', (Date.now()-start)+'ms');
break;
}
++i;
}
const dummyTime = 5000 - (Date.now()-start);
window.setTimeout(() => {
resolve(`${combined}#${i}`);
}, dummyTime);
}
});
}).then((powResponse) => {
const hasCaptchaForm = document.getElementById('captcha');
if (!hasCaptchaForm) {
postResponse(powResponse);
}
return powResponse;
});
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((powResponse) => {
postResponse(powResponse, captchaResponse);
});
}

View File

@ -1,29 +0,0 @@
importScripts('/js/argon2.js');
onmessage = async function(e) {
const [userkey, challenge, diff, diffString, argonOpts, id, threads] = e.data;
console.log('Worker thread', id, 'started');
let i = id;
if (id === 0) {
setInterval(() => {
postMessage([i]);
}, 500);
}
while(true) {
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)
&& ((parseInt(hash.hashHex[diffString.length],16) &
0xff >> (((diffString.length+1)*8)-diff)) === 0)) {
console.log('Worker', id, 'found solution');
postMessage([id, i]);
break;
}
i+=threads;
}
}

View File

@ -7,7 +7,7 @@
:root{--text-color:#c5c8c6;--bg-color:#1d1f21}
@media (prefers-color-scheme:light){:root{--text-color:#333;--bg-color:#EEE}}
a,a:visited{color:var(--text-color)}
body,html{height:100%}
body,html{height:100%%}
body{display:flex;flex-direction:column;background-color:var(--bg-color);color:var(--text-color);font-family:Helvetica,Arial,sans-serif;text-align:center;margin:0}
code{background-color:#dfdfdf30;border-radius:3px;padding:0 3px;}
img,h3,p{margin:0 0 5px 0}
@ -19,7 +19,8 @@ footer{font-size:x-small;margin-top:auto;margin-bottom:20px}.pt{padding-top:30vh
<footer>
<img src="/img/footerlogo.png">
<p>Security and Performance by <a href="https://BasedFlare.com">BasedFlare</a></p>
<p>Node: <code>20563af028ae90e0be85ab6c03f0e71b</code></p>
<p>Security and Performance by <a href="https://basedflare.com">BasedFlare</a></p>
<p>Node: <code>%[env(RAY_ID)]</code></p>
</footer>
</body>
</html>

View File

@ -7,4 +7,4 @@ tls=%[ssl_fc]
tlsv=%sslv
sni=%[ssl_fc_sni]
vey_id=%[env(RAY_ID)]
bucket=%[env(BUCKET_DURATION)]
expiry=%[env(CHALLENGE_EXPIRY)]