Защита от перебора паролей: SMTP, IMAP, веб — лимит по IP и по ящику
continuous-integration/drone/pr Build is passing
continuous-integration/drone/pr Build is passing
Один LoginGuard на все проверки пароля (SMTP AUTH, IMAP LOGIN/AUTHENTICATE, вход в веб, смена пароля): 10 неверных с IP за 15 мин → блок 15 мин, дальше вдвое дольше до суток; 20 неверных на ящик с разных IP → ящик закрыт, кроме IP, с которых в него уже входили. Во время блока пароль не проверяется (SMTP 421, IMAP BYE + NO [UNAVAILABLE], веб 429 + Retry-After); неверный пароль — ответ через 1 с; 3 неверных в соединении — обрыв. X-Forwarded-For веб-входа — только от прокси в частной сети, иначе заголовок отбрасывается (подменой IP лимит не обойти). Попутно: IMAP терял тегированный ответ после "* BYE" (LOGOUT, обрыв после неудачных входов) — takeUntil теперь после тегированной строки. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.mailserver.imap;
|
||||
|
||||
import com.mailserver.security.LoginGuard;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
@@ -67,11 +68,17 @@ public class ImapServer {
|
||||
|
||||
private final Settings settings;
|
||||
private final ImapStore store;
|
||||
private final LoginGuard guard;
|
||||
private DisposableServer server;
|
||||
|
||||
public ImapServer(Settings settings, ImapStore store) {
|
||||
this(settings, store, LoginGuard.disabled());
|
||||
}
|
||||
|
||||
public ImapServer(Settings settings, ImapStore store, LoginGuard guard) {
|
||||
this.settings = settings;
|
||||
this.store = store;
|
||||
this.guard = guard;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
@@ -98,7 +105,7 @@ public class ImapServer {
|
||||
});
|
||||
ImapSession session = new ImapSession(
|
||||
new ImapSession.Settings(settings.hostname(), settings.tls() != null, settings.authWithoutTls()),
|
||||
store, remoteIp[0], settings.implicitTls());
|
||||
store, guard, remoteIp[0], settings.implicitTls());
|
||||
@SuppressWarnings("unchecked")
|
||||
Sinks.Empty<Void>[] idleDone = new Sinks.Empty[1];
|
||||
|
||||
@@ -135,7 +142,9 @@ public class ImapServer {
|
||||
log.debug("IMAP {}: connection closed: {}", session.remoteIp, e.toString());
|
||||
return Mono.just(ImapSession.line("* BYE " + e.getMessage()));
|
||||
})
|
||||
.takeUntil(response -> session.closing);
|
||||
// after the tagged line of the command that closes (LOGOUT, too many failed logins), not after
|
||||
// its first untagged "* BYE" — the tagged answer must still reach the client
|
||||
.takeUntil(response -> session.closing && !untagged(response));
|
||||
|
||||
return Flux.concat(Mono.just(session.greeting()), responses)
|
||||
.concatMap(response -> response == ImapSession.STARTTLS_READY
|
||||
@@ -164,6 +173,10 @@ public class ImapServer {
|
||||
return new String(bytes, StandardCharsets.US_ASCII).trim().toUpperCase(Locale.ROOT).equals("DONE");
|
||||
}
|
||||
|
||||
private static boolean untagged(byte[] response) {
|
||||
return response.length > 1 && response[0] == '*' && response[1] == ' ';
|
||||
}
|
||||
|
||||
private static Flux<byte[]> blocking(java.util.concurrent.Callable<List<byte[]>> work) {
|
||||
return Mono.fromCallable(work).subscribeOn(Schedulers.boundedElastic()).flatMapIterable(list -> list);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.mailserver.imap;
|
||||
|
||||
import com.mailserver.security.LoginGuard;
|
||||
import com.mailserver.service.LocalDelivery;
|
||||
import jakarta.mail.Session;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
@@ -9,6 +10,7 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -39,6 +41,8 @@ final class ImapSession {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImapSession.class);
|
||||
|
||||
private static final int MAX_BAD_COMMANDS = 30;
|
||||
/** Wrong passwords in one connection before it is closed. */
|
||||
private static final int MAX_AUTH_FAILURES = 3;
|
||||
private static final int SOURCE_CACHE = 16;
|
||||
private static final DateTimeFormatter INTERNAL_DATE =
|
||||
DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH);
|
||||
@@ -53,6 +57,7 @@ final class ImapSession {
|
||||
|
||||
private final Settings settings;
|
||||
private final ImapStore store;
|
||||
private final LoginGuard guard;
|
||||
final String remoteIp;
|
||||
|
||||
boolean tls;
|
||||
@@ -78,8 +83,13 @@ final class ImapSession {
|
||||
volatile String idleTag;
|
||||
|
||||
ImapSession(Settings settings, ImapStore store, String remoteIp, boolean tls) {
|
||||
this(settings, store, LoginGuard.disabled(), remoteIp, tls);
|
||||
}
|
||||
|
||||
ImapSession(Settings settings, ImapStore store, LoginGuard guard, String remoteIp, boolean tls) {
|
||||
this.settings = settings;
|
||||
this.store = store;
|
||||
this.guard = guard;
|
||||
this.remoteIp = remoteIp;
|
||||
this.tls = tls;
|
||||
}
|
||||
@@ -254,7 +264,7 @@ final class ImapSession {
|
||||
out.add(line(tag + " NO [PRIVACYREQUIRED] Use STARTTLS first"));
|
||||
return;
|
||||
}
|
||||
loggedIn(tag, store.authenticate(user, password), user, out);
|
||||
checkPassword(tag, user, password, out);
|
||||
}
|
||||
|
||||
private void authenticate(String tag, ImapReader in, List<byte[]> out) {
|
||||
@@ -292,13 +302,44 @@ final class ImapSession {
|
||||
bad(tag, "Bad PLAIN response", out);
|
||||
return;
|
||||
}
|
||||
loggedIn(tag, store.authenticate(fields[1], fields[2]), fields[1], out);
|
||||
checkPassword(tag, fields[1], fields[2], out);
|
||||
}
|
||||
|
||||
/** Through the login guard: a blocked IP/mailbox gets no answer about the password and the connection closes. */
|
||||
private void checkPassword(String tag, String user, String password, List<byte[]> out) {
|
||||
Duration wait = guard.retryAfter(remoteIp, user);
|
||||
if (!wait.isZero()) {
|
||||
log.warn("IMAP {}: login as {} refused, blocked for {}", remoteIp, user, LoginGuard.human(wait));
|
||||
out.add(line("* BYE Too many failed logins, try again in " + LoginGuard.human(wait)));
|
||||
out.add(line(tag + " NO [UNAVAILABLE] Too many failed logins"));
|
||||
closing = true;
|
||||
return;
|
||||
}
|
||||
ImapStore.Account result = store.authenticate(user, password);
|
||||
if (result == null) {
|
||||
guard.failure(remoteIp, user);
|
||||
pause(guard.failureDelay());
|
||||
} else {
|
||||
guard.success(remoteIp, user);
|
||||
}
|
||||
loggedIn(tag, result, user, out);
|
||||
}
|
||||
|
||||
private static void pause(Duration delay) {
|
||||
if (delay.isZero()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(delay.toMillis());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private void loggedIn(String tag, ImapStore.Account result, String user, List<byte[]> out) {
|
||||
if (result == null) {
|
||||
log.warn("IMAP {}: authentication failed for {}", remoteIp, user);
|
||||
if (++badCommands > 5) {
|
||||
if (++badCommands >= MAX_AUTH_FAILURES) {
|
||||
out.add(line("* BYE Too many failed logins"));
|
||||
closing = true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user