8000 Require SMTPUTF8 capability for UTF-8 email by ahus1 · Pull Request #55353 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-26_8_3.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ on an affected client, set `post.logout.redirect.uris` to `-`; otherwise, update
its post-logout redirect URIs to satisfy those rules. Setting `-` also works
after upgrading, so an affected client can still be remediated.

=== Allow UTF-8 email setting requires SMTPUTF8 server support
// https://github.com/keycloak/keycloak/issues/55267

When *Allow UTF-8* is enabled in a realm's email settings, {project_name} now checks whether the connected SMTP server advertises the `SMTPUTF8` extension before sending an email with an internationalized sender, recipient, reply-to, or envelope sender address.
This enforces https://www.rfc-editor.org/rfc/rfc6531.html#section-3.2[RFC 6531 section 3.2], which requires SMTP clients to avoid transmitting internationalized email addresses or headers to servers that do not offer `SMTPUTF8`.
If the server does not advertise `SMTPUTF8`, the send fails before the SMTP envelope is transmitted.
Messages with ASCII-only addresses can still be sent without this extension.
The *Test connection* action checks `SMTPUTF8` whenever *Allow UTF-8* is enabled, even if the test message uses only ASCII addresses, to validate that the configured server supports this mode.

Configure an SMTP server or relay that advertises `SMTPUTF8` if you need to send email with internationalized addresses.
If all email addresses are ASCII-only, you can disable *Allow UTF-8* instead.

=== Stricter enforcement of the requested level of authentication
// https://github.com/keycloak/keycloak/issues/53157

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@
<nginx.container>registry.gitlab.com/openid/conformance-suite/nginx:${nginx.version}</nginx.container>

<!-- Test -->
<greenmail.version>2.1.3</greenmail.version>
<greenmail.version>2.1.15</greenmail.version>
<jmeter.version>2.10</jmeter.version>
<junit.version>4.13.2</junit.version>
<picketlink.version>2.7.0.Final</picketlink.version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ public interface EmailSenderProvider extends Provider {

String CONFIG_ALLOW_UTF8 = "allowutf8";

/** Require SMTPUTF8 for an SMTP test even if its addresses are ASCII-only. */
String CONFIG_REQUIRE_SMTPUTF8_FOR_TEST = "_requireSmtpUtf8ForTest";

default void send(Map<String, String> config, UserModel user, String subject, String textBody, String htmlBody) throws EmailException {
send(config, user.getEmail(), subject, textBody, htmlBody);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.keycloak.utils.EmailValidationUtil;
import org.keycloak.utils.SMTPUtil;

import org.eclipse.angus.mail.smtp.SMTPTransport;
import org.jboss.logging.Logger;

import static org.keycloak.utils.StringUtil.isNotBlank;
Expand Down Expand Up @@ -81,6 +82,8 @@ public void send(Map<String, String> config, String address, String subject, Str
final boolean allowutf8 = isAllowUTF8(config);
final String convertedAddress = checkUserAddress(address, allowutf8);
final String from = checkFromAddress(config.get("from"), allowutf8);
final boolean requiresSmtpUtf8 = allowutf8 && (Boolean.parseBoolean(config.get(CONFIG_REQUIRE_SMTPUTF8_FOR_TEST)) || containsNonAscii(convertedAddress)
|| containsNonAscii(from) || containsNonAscii(config.get("replyTo")) || containsNonAscii(config.get("envelopeFrom")));

Session session = Session.getInstance(buildEmailProperties(config, from));

Expand All @@ -91,6 +94,10 @@ public void send(Map<String, String> config, String address, String subject, Str
EmailAuthenticator selectedAuthenticator = selectAuthenticatorBasedOnConfig(config);
selectedAuthenticator.connect(this.session, config, transport);

if (requiresSmtpUtf8 && !(transport instanceof SMTPTransport smtpTransport && smtpTransport.supportsExtension("SMTPUTF8"))) {
throw new EmailException("SMTP server does not advertise SMTPUTF8, which is required for this email");
}

transport.sendMessage(message, new InternetAddress[]{new InternetAddress(convertedAddress)});

} catch (Exception e) {
Expand Down Expand Up @@ -245,6 +252,10 @@ private static boolean isAllowUTF8(Map<String, String> config) {
return "true".equals(config.get(CONFIG_ALLOW_UTF8));
}

private static boolean containsNonAscii(String value) {
return value != null && value.chars().anyMatch(c -> c > 127);
}

private static boolean isDebugEnabled(Map<String, String> config) {
return "true".equals(config.get("debug"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ public void sendSmtpTestEmail(Map<String, String> config, UserModel user) throws
Map<String, Object> attributes = new HashMap<>(this.attributes);

EmailTemplate email = processTemplate("emailTestSubject", Collections.emptyList(), "email-test.ftl", attributes);
send(config, email.getSubject(), email.getTextBody(), email.getHtmlBody());
Map<String, String> testConfig = new HashMap<>(config);
testConfig.put(EmailSenderProvider.CONFIG_REQUIRE_SMTPUTF8_FOR_TEST, "true");
send(testConfig, email.getSubject(), email.getTextBody(), email.getHtmlBody());
}

@Override
Expand Down
4 changes: 0 additions & 4 deletions test-framework/email-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@
<packaging>jar</packaging>
<description>Email server extension for Keycloak Test Framework</description>

<properties>
<greenmail.version>2.1.3</greenmail.version>
</properties>

<dependencies>
<dependency>
<groupId>org.keycloak.testframework</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,27 @@

package org.keycloak.tests.admin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;

import jakarta.mail.Address;
import jakarta.mail.internet.MimeMessage;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;

import org.keycloak.admin.client.Keycloak;
Expand Down Expand Up @@ -61,6 +74,9 @@

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
Expand Down Expand Up @@ -260,7 +276,7 @@ public void testAllowUTF8() throws Exception {
assertStatus(response, 204);
assertMailReceived("auto@xn--keycloak-k3a.org");

// utf8 on from allowed if allowutf8 enabled
// GreenMail advertises SMTPUTF8, so a UTF-8 sender is allowed
response = adminClient.realms().realm(managedRealm.getName()).testSMTPConnection(smtpMap("127.0.0.1", "3025", "autoñ@keycloak.org",
null, null, null, null, null, null, null, "true"));
assertStatus(response, 204);
Expand All @@ -285,7 +301,7 @@ public void testAllowUTF8() throws Exception {
null, null, null, null, null));
assertStatus(response, 500);

// allowed on address if allowutf8 enabled
// a UTF-8 recipient is allowed when the server advertises SMTPUTF8
response = adminClient.realms().realm(managedRealm.getName()).testSMTPConnection(smtpMap("127.0.0.1", "3025", "auto@keycloak.org",
null, null, null, null, null, null, null, "true"));
assertStatus(response, 204);
Expand All @@ -298,6 +314,174 @@ public void testAllowUTF8() throws Exception {
}
}

@Test
@Order(12)
public void testAllowUTF8RejectedWithoutSMTPUTF8() throws Exception {
try (SmtpServerWithou 10BC8 tUtf8 smtpServer = new SmtpServerWithoutUtf8()) {
Response response = adminClient.realms().realm(managedRealm.getName()).testSMTPConnection(smtpMap(
"127.0.0.1", Integer.toString(smtpServer.getPort()), "autoñ@keycloak.org",
null, null, null, null, null, null, null, "true"));
assertStatus(response, 500);
SmtpResult result = smtpServer.result().get(10, TimeUnit.SECONDS);
assertTrue(result.ehloReceived());
assertFalse(result.mailFromReceived());
}
}

@Test
@Order(13)
public void testAllowUTF8ConnectionTestRequiresSMTPUTF8WithAsciiAddresses() throws Exception {
try (SmtpServerWithoutUtf8 smtpServer = new SmtpServerWithoutUtf8()) {
Response response = adminClient.realms().realm(managedRealm.getName()).testSMTPConnection(smtpMap(
"127.0.0.1", Integer.toString(smtpServer.getPort()), "auto@keycloak.org",
null, null, null, null, null, null, null, "true"));
assertStatus(response, 500);
SmtpResult result = smtpServer.result().get(10, TimeUnit.SECONDS);
assertTrue(result.ehloReceived());
assertFalse(result.mailFromReceived());
}
}

@Test
@Order(14)
public void testAllowUTF8NormalSendAllowsAsciiAddressesWithoutSMTPUTF8() throws Exception {
try (SmtpServerWithoutUtf8 smtpServer = new SmtpServerWithoutUtf8()) {
RealmResource realm = adminClient.realms().realm(managedRealm.getName());
RealmRepresentation realmRep = realm.toRepresentation();
Map<String, String> previousSettings = realmRep.getSmtpServer();
realmRep.setSmtpServer(smtpMap("127.0.0.1", Integer.toString(smtpServer.getPort()), "auto@keycloak.org",
null, null, null, null, null, null, null, "true"));
realm.update(realmRep);

try {
AccessToken token = oAuthClient.parseToken(adminClient.tokenManager().getAccessToken().getToken(), AccessToken.class);
adminClient.realm(managedRealm.getName()).users().get(token.getSubject()).sendVerifyEmail();
SmtpResult result = smtpServer.result().get(10, TimeUnit.SECONDS);
assertTrue(result.ehloReceived());
assertTrue(result.mailFromReceived());
assertTrue(result.messageReceived());
} finally {
realmRep.setSmtpServer(previousSettings);
realm.update(realmRep);
}
}
}

@Test
@Order(15)
public void testAllowUTF8NormalSendRejectsNonAsciiAddressesWithoutSMTPUTF8() throws Exception {
RealmResource realm = adminClient.realms().realm(managedRealm.getName());
RealmRepresentation realmRep = realm.toRepresentation();
Map<String, String> previousSettings = realmRep.getSmtpServer();
AccessToken token = oAuthClient.parseToken(adminClient.tokenManager().getAccessToken().getToken(), AccessToken.class);
UserResource user = adminClient.realm(managedRealm.getName()).users().get(token.getSubject());
UserRepresentation userRep = user.toRepresentation();
String previousEmail = userRep.getEmail();

try {
for (String field : List.of("from", "recipient", "replyTo", "envelopeFrom")) {
try (SmtpServerWithoutUtf8 smtpServer = new SmtpServerWithoutUtf8()) {
Map<String, String> config = smtpMap("127.0.0.1", Integer.toString(smtpServer.getPort()), "auto@keycloak.org",
null, null, null, null, null, null, null, "true");
userRep.setEmail("recipient".equals(field) ? "adminñ@localhost" : previousEmail);
user.update(userRep);
if (!"recipient".equals(field)) {
config.put(field, "autoñ@keycloak.org");
}
realmRep.setSmtpServer(config);
realm.update(realmRep);

WebApplicationException error = assertThrows(WebApplicationException.class, user::sendVerifyEmail, field);
assertEquals(500, error.getResponse().getStatus(), field);
SmtpResult result = smtpServer.result().get(10, TimeUnit.SECONDS);
assertTrue(result.ehloReceived(), field);
assertFalse(result.mailFromReceived(), field);
}
}
} finally {
userRep.setEmail(previousEmail);
user.update(userRep);
realmRep.setSmtpServer(previousSettings);
realm.update(realmRep);
}
}

private record SmtpResult(boolean ehloReceived, boolean mailFromReceived, boolean messageReceived) {
}

private static class SmtpServerWithoutUtf8 implements AutoCloseable {

private final ServerSocket serverSocket;
private final CompletableFuture<SmtpResult> result;

private SmtpServerWithoutUtf8() throws IOException {
serverSocket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"));
serverSocket.setSoTimeout(10000);
result = CompletableFuture.supplyAsync(this::serve);
}

private int getPort() {
return serverSocket.getLocalPort();
}

private CompletableFuture<SmtpResult> result() {
return result;
}

private SmtpResult serve() {
try (Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8))) {
socket.setSoTimeout(10000);
respond(writer, "220 localhost ready");
boolean ehloReceived = false;
boolean mailFromReceived = false;
boolean messageReceived = false;
boolean readingData = false;
String command;
while ((command = reader.readLine()) != null) {
if (readingData) {
if (command.equals(".")) {
readingData = false;
messageReceived = true;
respond(writer, "250 accepted");
}
} else if (command.startsWith("EHLO ")) {
ehloReceived = true;
respond(writer, "250 localhost");
} else if (command.startsWith("MAIL FROM:")) {
mailFromReceived = true;
respond(writer, "250 accepted");
} else if (command.startsWith("RCPT TO:")) {
respond(writer, "250 accepted");
} else if (command.equals("DATA")) {
readingData = true;
respond(writer, "354 end with <CRLF>.<CRLF>");
} else if (command.equals("QUIT")) {
respond(writer, "221 goodbye");
break;
} else {
throw new IOException("Unexpected SMTP command: " + command);
}
}
return new SmtpResult(ehloReceived, mailFromReceived, messageReceived);
} catch (IOException e) {
throw new CompletionException(e);
}
}

private static void respond(BufferedWriter writer, String response) throws IOException {
writer.write(response);
writer.write("\r\n");
writer.flush();
}

@Override
public void close() throws IOException {
serverSocket.close();
}
}

private Map<String, String> settings(String host, String port, String from, String auth, String ssl, String starttls,
String username, String password) throws Exception {
return smtpMap(host, port, from, auth, ssl, starttls, username, password, "", "", null);
Expand Down
Loading
0