postfix-api/src/main/java/de/gurkengewuerz/postfix_rest_send/objects/BruteforceFilter.java

72 lines
2.5 KiB
Java

package de.gurkengewuerz.postfix_rest_send.objects;
import de.gurkengewuerz.postfix_rest_send.Main;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by gurkengewuerz.de on 13.07.2017.
*/
public class BruteforceFilter {
private final HashMap<String, Integer> attempts = new HashMap<>();
private int maxAttemps = 3;
public BruteforceFilter(int maxAttemps) {
this.maxAttemps = maxAttemps;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
refresh();
} catch (SQLException e) {
Logger.getLogger(BruteforceFilter.class.getName()).log(Level.SEVERE, null, e);
}
}
}, 0, 2 * 60 * 1000);
}
public BruteforceFilter() {
this(3);
}
private void refresh() throws SQLException {
ResultSet rs = Main.getDatabase().executeQuery("SELECT ip, COUNT(*) count FROM token_bruteforce WHERE occurred > ? GROUP BY ip ORDER BY COUNT(*) DESC;", (System.currentTimeMillis() / 1000) - (24 * 60 * 60));
synchronized (attempts) {
attempts.clear();
while (rs.next()) {
attempts.put(rs.getString("ip"), rs.getInt("count"));
}
}
if (Main.getConfig().debug())
Logger.getLogger(getClass().getName()).log(Level.INFO, "refreshed bans (" + attempts.size() + ")");
}
public void failed(String ip) {
if (Main.getConfig().getBoolean("disable_bruteforcefilter")) return;
Main.getDatabase().executeUpdate("INSERT INTO token_bruteforce (ip, occurred) VALUES (?, ?);", ip, System.currentTimeMillis() / 1000);
synchronized (attempts) {
if (attempts.containsKey(ip)) {
attempts.replace(ip, attempts.get(ip) + 1);
} else {
attempts.put(ip, 1);
}
if (Main.getConfig().debug())
Logger.getLogger(getClass().getName()).log(Level.INFO, "banned " + ip + " attemp " + attempts.get(ip));
}
}
public boolean banned(String ip) {
if (Main.getConfig().getBoolean("disable_bruteforcefilter")) return false;
synchronized (attempts) {
return attempts.containsKey(ip) && attempts.get(ip) >= maxAttemps;
}
}
}