Password spraying tries one or two common passwords against many accounts, to stay under per-account limits. Looking across accounts per source address catches it.
What to build
Scan a login log and report source addresses that look like spraying, and accounts under attack.
Requirements
- Each line is
time ip user result, with time in whole seconds (in increasing order) and result ok or fail. - An address is spraying if, within any 600-second window (times t to t + 599), it has failures against 5 or more distinct users.
- An account is under attack if it has 5 or more failures in total.
- Print
spraying: IPfor each spraying address in order of the attempt that first made it qualify, thenunder attack: USERfor each account in order of its 5th failure. If neither kind exists, printnothing suspicious.
Input
One log line per line.
Output
As described.
Constraints
Up to 1000 log lines.
Example
Input:
10 9.9.9.9 a fail
20 9.9.9.9 b fail
30 9.9.9.9 c fail
40 9.9.9.9 d fail
50 9.9.9.9 e fail
Output:
spraying: 9.9.9.9
Why it works
Per-account limits never trigger when each account sees only one or two failures, but counting distinct failed accounts per address inside a sliding time window shows the pattern; total failures per account catch the opposite attack, many guesses at one account.
Examples
10 9.9.9.9 a fail 20 9.9.9.9 b fail 30 9.9.9.9 c fail 40 9.9.9.9 d fail 50 9.9.9.9 e fail
spraying: 9.9.9.9
1 1.1.1.1 rahim ok 2 1.1.1.1 anika fail
nothing suspicious
Hints
Hint 1
For each address keep its recent failures (time, user) and drop those older than 600 seconds before counting distinct users.
Hint 2
Remember which addresses and users were already reported.
Solution
Show one correct solution (try it yourself first)
const recent = new Map();
const userFails = new Map();
const sprayers = [];
const attacked = [];
let line = prompt();
while (line !== null) {
if (line.trim()) {
const [timeText, ip, user, result] = line.trim().split(/\s+/);
const time = Number(timeText);
if (result === "fail") {
const list = (recent.get(ip) ?? []).filter((f) => f.time > time - 600);
list.push({ time, user });
recent.set(ip, list);
if (!sprayers.includes(ip) && new Set(list.map((f) => f.user)).size >= 5) sprayers.push(ip);
const n = (userFails.get(user) ?? 0) + 1;
userFails.set(user, n);
if (n === 5) attacked.push(user);
}
}
line = prompt();
}
for (const ip of sprayers) console.log(`spraying: ${ip}`);
for (const user of attacked) console.log(`under attack: ${user}`);
if (!sprayers.length && !attacked.length) console.log("nothing suspicious");
▶ Open this solution in the compiler, then press Visualize to watch it run step by step