Kafka security: authentication, encryption and ACLs
An unsecured Kafka cluster lets anyone who can reach it read, write and delete any topic. This page explains the three layers of Kafka security, then runs a secured broker inside each program to show SASL and SCRAM logins, TLS with client certificates, and ACLs that allow and deny, including the errors clients get when they are refused.
Contents
The three layers of Kafka security
By default a Kafka listener uses PLAINTEXT
- Encryption: TLS on the connection, so that nobody on the network can read or change records. The broker presents a certificate, and the client checks it against a truststore.
- Authentication: the broker learns who the client is. Either the client presents its own TLS certificate (mutual TLS), or it logs in with SASL. The result is a principal such as
.User:alice - Authorization: for every request, an authorizer checks whether the principal may perform the operation on the resource, using access control lists (ACLs). In KRaft clusters this is the
, which keeps the ACLs in the metadata log.StandardAuthorizer
A listener's security.protocolSSLSASL_PLAINTEXTSASL_SSL
| Mechanism | Since | Credentials kept in | Best for |
|---|---|---|---|
| TLS client certificates | 0.9 | Your certificate authority | Services that already have a PKI |
| SASL/GSSAPI (Kerberos) | 0.9 | Kerberos KDC, Active Directory | Companies that run Kerberos |
| SASL/PLAIN | 0.10.0 | A JAAS file, or a custom callback handler | Simple setups, always over TLS |
| SASL/SCRAM-SHA-256 and -512 | 0.10.2 | Salted hashes in the cluster metadata | Username and password users managed by the Admin API |
| SASL/OAUTHBEARER | 2.0; OIDC in 3.1 | An OAuth identity provider | Short-lived tokens from a central identity service |
The programs start a one-node KRaft cluster in the JVM with KafkaClusterTestKitspring-kafka-testEmbeddedKafkaKraftBrokerStandardAuthorizerkeytoolSASL_PLAINTEXTSASL_SSL
SASL logins and ACLs
The broker below accepts three PLAIN users. adminordersbillingallow.everyone.if.no.acl.foundfalse
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclBindingFilter;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SaslAndAcls {
public static void main(String[] args) throws Exception {
KafkaClusterTestKit cluster = startCluster();
String bootstrap = cluster.bootstrapServers();
try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
admin.createAcls(List.of(
allow("User:alice", ResourceType.TOPIC, "orders", AclOperation.WRITE),
allow("User:bob", ResourceType.TOPIC, "orders", AclOperation.READ),
allow("User:bob", ResourceType.GROUP, "billing", AclOperation.READ)))
.all().get();
Thread.sleep(500); // ACLs reach the broker through the metadata log
admin.describeAcls(AclBindingFilter.ANY).values().get().stream()
.map(b -> b.entry().principal() + " " + b.entry().permissionType() + " "
+ b.entry().operation() + " on " + b.pattern().resourceType() + " "
+ b.pattern().name())
.sorted()
.forEach(acl -> System.out.println("ACL " + acl));
}
attempt("alice sends to orders", () -> send(bootstrap, "alice", "alice-secret"));
attempt("bob sends to orders", () -> send(bootstrap, "bob", "bob-secret"));
attempt("bob reads orders as group billing", () -> read(bootstrap, "billing"));
attempt("bob reads orders as group audit", () -> read(bootstrap, "audit"));
attempt("bob with a wrong password", () -> send(bootstrap, "bob", "guess"));
attempt("alice lists topics", () -> {
try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "alice",
"alice-secret"))) {
return admin.listTopics().names().get().toString();
}
});
cluster.close();
}
static AclBinding allow(String principal, ResourceType type, String name,
AclOperation operation) {
return new AclBinding(new ResourcePattern(type, name, PatternType.LITERAL),
new AccessControlEntry(principal, "*", operation, AclPermissionType.ALLOW));
}
static String send(String bootstrap, String user, String password) throws Exception {
try (KafkaProducer<String, String> producer = new KafkaProducer<>(
client(bootstrap, "PLAIN", user, password),
new StringSerializer(), new StringSerializer())) {
var meta = producer.send(new ProducerRecord<>("orders", "order from " + user)).get();
return "written at offset " + meta.offset();
}
}
static String read(String bootstrap, String group) {
Map<String, Object> props = client(bootstrap, "PLAIN", "bob", "bob-secret");
props.put("group.id", group);
props.put("auto.offset.reset", "earliest");
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props,
new StringDeserializer(), new StringDeserializer())) {
consumer.subscribe(List.of("orders"));
for (int i = 0; i < 20; i++) {
var records = consumer.poll(Duration.ofMillis(500));
if (!records.isEmpty()) {
return "read \"" + records.iterator().next().value() + "\"";
}
}
return "nothing read";
}
}
interface Action {
String run() throws Exception;
}
static void attempt(String label, Action action) {
try {
System.out.println(label + ": " + action.run());
} catch (ExecutionException | KafkaException e) {
Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
System.out.println(label + ": " + cause.getClass().getSimpleName() + ": "
+ cause.getMessage());
} catch (Exception e) {
System.out.println(label + ": " + e);
}
}
// Client settings for SASL over plaintext; production uses SASL_SSL
static Map<String, Object> client(String bootstrap, String mechanism, String user,
String password) {
String module = mechanism.equals("PLAIN")
? "org.apache.kafka.common.security.plain.PlainLoginModule"
: "org.apache.kafka.common.security.scram.ScramLoginModule";
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", bootstrap);
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.mechanism", mechanism);
props.put("sasl.jaas.config", module + " required username=\"" + user
+ "\" password=\"" + password + "\";");
props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
return props;
}
// Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
// cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
static KafkaClusterTestKit startCluster() throws Exception {
// logging is off: the clients log every refused request at ERROR, and this
// program prints the exceptions instead. Logback's Logger is named in full
// because org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
// the PLAIN users the broker accepts, and the broker's own login (admin)
String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
+ " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
+ " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
new TestKitNodes.Builder()
.setCombined(true)
.setNumControllerNodes(1)
.setNumBrokerNodes(1)
.setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.build())
.setConfigProp("authorizer.class.name",
"org.apache.kafka.metadata.authorizer.StandardAuthorizer")
.setConfigProp("super.users", "User:admin")
// one broker cannot hold the default 3 copies of the internal topics
.setConfigProp("offsets.topic.replication.factor", "1")
.setConfigProp("transaction.state.log.replication.factor", "1")
.setConfigProp("transaction.state.log.min.isr", "1")
.setConfigProp("allow.everyone.if.no.acl.found", "false")
.setConfigProp("listener.name.external.sasl.enabled.mechanisms",
"PLAIN,SCRAM-SHA-512")
.setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
.setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
"org.apache.kafka.common.security.scram.ScramLoginModule required;")
.setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
.build();
cluster.format();
cluster.startup();
cluster.waitForReadyBrokers();
return cluster;
} finally {
System.setOut(stdout);
}
}
}
ACL User:alice ALLOW WRITE on TOPIC orders
ACL User:bob ALLOW READ on GROUP billing
ACL User:bob ALLOW READ on TOPIC orders
alice sends to orders: written at offset 0
bob sends to orders: ClusterAuthorizationException: Cluster authorization failed.
bob reads orders as group billing: read "order from alice"
bob reads orders as group audit: GroupAuthorizationException: Not authorized to access group: audit
bob with a wrong password: SaslAuthenticationException: Authentication failed: Invalid username or password
alice lists topics: [orders]
- alice's record was written at offset 0: she authenticated and holds
on the topic.WRITE - bob's send failed with
, not a topic error. Producers are idempotent by default, and starting an idempotent producer needsClusterAuthorizationException on the cluster, which a principal has implicitly only if it may write to some topic. bob may write nowhere, so the first request already failed.IDEMPOTENT_WRITE - bob read alice's record with the group
. A consumer in a group needs two ACLs:billing on the topic andREAD on the group.READ - With the group
, the same consumer gotaudit . This is the most common surprise when a team adds a new consumer: the topic ACL alone is not enough.GroupAuthorizationException - A wrong password failed with
before any request was made.SaslAuthenticationException - alice's topic list contained
, becauseorders impliesWRITE . Topics a principal cannot describe are left out of its metadata, as if they did not exist.DESCRIBE
With PLAIN, the users and passwords sit in clear text in the broker's JAAS configuration, here listener.name.external.plain.sasl.jaas.configsasl.server.callback.handler.class
SCRAM users managed at runtime
SCRAM fixes both problems of PLAIN: the cluster stores only a salted hash of each password, and the password never crosses the network. Credentials live in the KRaft metadata log, so the Admin API can add, rotate and remove users without restarting anything:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ScramCredentialInfo;
import org.apache.kafka.clients.admin.ScramMechanism;
import org.apache.kafka.clients.admin.UserScramCredentialDeletion;
import org.apache.kafka.clients.admin.UserScramCredentialUpsertion;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScramUsers {
public static void main(String[] args) throws Exception {
KafkaClusterTestKit cluster = startCluster();
String bootstrap = cluster.bootstrapServers();
try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
System.out.println("carol before: " + login(bootstrap, "carol", "carol-secret"));
// the broker stores a salted hash, never the password itself
admin.alterUserScramCredentials(List.of(new UserScramCredentialUpsertion("carol",
new ScramCredentialInfo(ScramMechanism.SCRAM_SHA_512, 8192),
"carol-secret"))).all().get();
Thread.sleep(500); // the credential reaches the broker through the metadata log
admin.describeUserScramCredentials().all().get().forEach((user, d) ->
System.out.println("stored for " + user + ": " + d.credentialInfos()));
System.out.println("carol after: " + login(bootstrap, "carol", "carol-secret"));
System.out.println("carol, wrong: " + login(bootstrap, "carol", "secret"));
// a new password replaces the old one at once
admin.alterUserScramCredentials(List.of(new UserScramCredentialUpsertion("carol",
new ScramCredentialInfo(ScramMechanism.SCRAM_SHA_512, 8192),
"carol-rotated"))).all().get();
Thread.sleep(500);
System.out.println("old password: " + login(bootstrap, "carol", "carol-secret"));
System.out.println("new password: " + login(bootstrap, "carol", "carol-rotated"));
admin.alterUserScramCredentials(List.of(new UserScramCredentialDeletion("carol",
ScramMechanism.SCRAM_SHA_512))).all().get();
Thread.sleep(500);
System.out.println("after delete: " + login(bootstrap, "carol", "carol-rotated"));
} finally {
cluster.close();
}
}
// connects with SCRAM-SHA-512 and asks for the cluster id, which needs no ACL
static String login(String bootstrap, String user, String password) {
Map<String, Object> props = client(bootstrap, "SCRAM-SHA-512", user, password);
props.put("request.timeout.ms", "5000");
props.put("default.api.timeout.ms", "5000");
try (Admin admin = Admin.create(props)) {
admin.describeCluster().clusterId().get();
return "authenticated";
} catch (ExecutionException e) {
return e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
// Client settings for SASL over plaintext; production uses SASL_SSL
static Map<String, Object> client(String bootstrap, String mechanism, String user,
String password) {
String module = mechanism.equals("PLAIN")
? "org.apache.kafka.common.security.plain.PlainLoginModule"
: "org.apache.kafka.common.security.scram.ScramLoginModule";
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", bootstrap);
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.mechanism", mechanism);
props.put("sasl.jaas.config", module + " required username=\"" + user
+ "\" password=\"" + password + "\";");
props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
return props;
}
// Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
// cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
static KafkaClusterTestKit startCluster() throws Exception {
// logging is off: the clients log every refused request at ERROR, and this
// program prints the exceptions instead. Logback's Logger is named in full
// because org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
// the PLAIN users the broker accepts, and the broker's own login (admin)
String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
+ " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
+ " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
new TestKitNodes.Builder()
.setCombined(true)
.setNumControllerNodes(1)
.setNumBrokerNodes(1)
.setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.build())
.setConfigProp("authorizer.class.name",
"org.apache.kafka.metadata.authorizer.StandardAuthorizer")
.setConfigProp("super.users", "User:admin")
// one broker cannot hold the default 3 copies of the internal topics
.setConfigProp("offsets.topic.replication.factor", "1")
.setConfigProp("transaction.state.log.replication.factor", "1")
.setConfigProp("transaction.state.log.min.isr", "1")
.setConfigProp("allow.everyone.if.no.acl.found", "false")
.setConfigProp("listener.name.external.sasl.enabled.mechanisms",
"PLAIN,SCRAM-SHA-512")
.setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
.setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
"org.apache.kafka.common.security.scram.ScramLoginModule required;")
.setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
.build();
cluster.format();
cluster.startup();
cluster.waitForReadyBrokers();
return cluster;
} finally {
System.setOut(stdout);
}
}
}
carol before: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
stored for carol: [ScramCredentialInfo{mechanism=SCRAM_SHA_512, iterations=8192}]
carol after: authenticated
carol, wrong: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
old password: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
new password: authenticated
after delete: SaslAuthenticationException: Authentication failed during authentication due to invalid credentials with SASL mechanism SCRAM-SHA-512
- Before carol had a credential, her SCRAM login failed. The message does not say whether the user is unknown or the password is wrong, so it gives an attacker nothing to probe.
stored a SCRAM-SHA-512 credential with 8192 iterations.alterUserScramCredentials returns only the mechanism and the iteration count; the hash and salt never leave the cluster.describeUserScramCredentials- carol then logged in, and a wrong password failed with the same message as before.
- Setting a new password replaced the old one at once: the old password failed, the new one worked. Clients that are already connected stay connected; the check happens at login.
- After the credential was deleted, carol could no longer log in.
A new KRaft cluster cannot accept SCRAM logins until a credential exists, and the brokers may need one for their own connections. For that, kafka-storage.sh format --add-scramsasl.enabled.mechanismsSCRAM-SHA-512ScramLoginModulestartCluster
TLS and client certificates
TLS encrypts the connection and, with ssl.client.auth=requiredkeytool
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.network.ListenerName;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MutualTls {
static final String PASS = "changeit";
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("tls");
// one self-signed certificate per party; each side trusts the others' certificates
keytool(dir, "-genkeypair", "-alias", "broker", "-keyalg", "RSA", "-dname",
"CN=localhost", "-ext", "SAN=dns:localhost,ip:127.0.0.1", "-validity", "2",
"-keystore", "broker.p12", "-storepass", PASS);
for (String user : List.of("alice", "mallory")) {
keytool(dir, "-genkeypair", "-alias", user, "-keyalg", "RSA", "-dname",
"CN=" + user + ",O=Shop", "-validity", "2", "-keystore", user + ".p12",
"-storepass", PASS);
keytool(dir, "-exportcert", "-alias", user, "-keystore", user + ".p12",
"-storepass", PASS, "-file", user + ".crt");
keytool(dir, "-importcert", "-noprompt", "-alias", user, "-file", user + ".crt",
"-keystore", "broker-trust.p12", "-storepass", PASS);
}
keytool(dir, "-exportcert", "-alias", "broker", "-keystore", "broker.p12",
"-storepass", PASS, "-file", "broker.crt");
keytool(dir, "-importcert", "-noprompt", "-alias", "broker", "-file", "broker.crt",
"-keystore", "client-trust.p12", "-storepass", PASS);
KafkaClusterTestKit cluster = startCluster(dir);
int tlsPort = cluster.brokers().get(0).boundPort(new ListenerName("TLS"));
String tls = "localhost:" + tlsPort;
try (Admin admin = Admin.create(Map.<String, Object>of(
"bootstrap.servers", cluster.bootstrapServers()))) {
admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
admin.createAcls(List.of(new AclBinding(
new ResourcePattern(ResourceType.TOPIC, "orders", PatternType.LITERAL),
new AccessControlEntry("User:alice", "*", AclOperation.WRITE,
AclPermissionType.ALLOW)))).all().get();
}
send("no truststore", tls, null, null);
send("truststore, no certificate", tls, dir.resolve("client-trust.p12"), null);
send("alice's certificate", tls, dir.resolve("client-trust.p12"),
dir.resolve("alice.p12"));
send("mallory's certificate", tls, dir.resolve("client-trust.p12"),
dir.resolve("mallory.p12"));
cluster.close();
}
static void send(String label, String bootstrap, Path trust, Path key) {
Map<String, Object> props = new HashMap<>(Map.of(
"bootstrap.servers", bootstrap, "security.protocol", "SSL",
"max.block.ms", "5000"));
if (trust != null) {
props.put("ssl.truststore.location", trust.toString());
props.put("ssl.truststore.password", PASS);
}
if (key != null) {
props.put("ssl.keystore.location", key.toString());
props.put("ssl.keystore.password", PASS);
}
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props,
new StringSerializer(), new StringSerializer())) {
long offset = producer.send(new ProducerRecord<>("orders", label)).get().offset();
System.out.println(label + ": written at offset " + offset);
} catch (ExecutionException | KafkaException e) {
Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
System.out.println(label + ": " + cause.getClass().getSimpleName());
Throwable root = cause;
while (root.getCause() != null) {
root = root.getCause();
}
if (root != cause) {
System.out.println(" root cause: " + root.getClass().getSimpleName() + ": "
+ root.getMessage());
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
static void keytool(Path dir, String... args) throws Exception {
List<String> command = new ArrayList<>();
command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString());
command.addAll(List.of(args));
command.addAll(List.of("-storetype", "PKCS12"));
Process p = new ProcessBuilder(command).directory(dir.toFile())
.redirectErrorStream(true).start();
String out = new String(p.getInputStream().readAllBytes());
if (p.waitFor() != 0) {
throw new IllegalStateException(out);
}
}
// Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit and adds a TLS
// listener that requires client certificates. The plaintext listener the test kit
// always creates stands in for a private admin network here.
static KafkaClusterTestKit startCluster(Path dir) throws Exception {
// logging is off: refused connections are logged at ERROR, and the program
// prints them instead. Logback's Logger is named in full: org.slf4j.Logger,
// imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
String tls = "listener.name.tls.";
KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
new TestKitNodes.Builder().setCombined(true).setNumControllerNodes(1)
.setNumBrokerNodes(1).build())
.setConfigProp("listeners",
"EXTERNAL://localhost:0,CONTROLLER://localhost:0,TLS://localhost:0")
.setConfigProp("listener.security.protocol.map",
"EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT,TLS:SSL")
.setConfigProp(tls + "ssl.keystore.location",
dir.resolve("broker.p12").toString())
.setConfigProp(tls + "ssl.keystore.password", PASS)
.setConfigProp(tls + "ssl.truststore.location",
dir.resolve("broker-trust.p12").toString())
.setConfigProp(tls + "ssl.truststore.password", PASS)
.setConfigProp(tls + "ssl.client.auth", "required")
// turns the certificate subject "CN=alice,O=Shop" into the user "alice"
.setConfigProp("ssl.principal.mapping.rules",
"RULE:^CN=([^,]+),.*$/$1/,DEFAULT")
.setConfigProp("authorizer.class.name",
"org.apache.kafka.metadata.authorizer.StandardAuthorizer")
.setConfigProp("super.users", "User:ANONYMOUS")
.setConfigProp("offsets.topic.replication.factor", "1")
.build();
cluster.format();
cluster.startup();
cluster.waitForReadyBrokers();
return cluster;
} finally {
System.setOut(stdout);
}
}
}
no truststore: SslAuthenticationException
root cause: SunCertPathBuilderException: unable to find valid certification path to requested target
truststore, no certificate: SslAuthenticationException
root cause: SSLHandshakeException: (certificate_required) Received fatal alert: certificate_required
alice's certificate: written at offset 0
mallory's certificate: TopicAuthorizationException
- Without a truststore, the client used the JDK's default certificate authorities. None of them signed the broker's certificate, so the handshake failed with "unable to find valid certification path".
- With a truststore but no certificate of its own, the client trusted the broker, but the broker ended the handshake with
.certificate_required - With alice's certificate, the write succeeded. The rule
inRULE:^CN=([^,]+),.*$/$1/ turned the subjectssl.principal.mapping.rules intoCN=alice,O=Shop , which matched the ACL. Without the rule, the principal would be the whole subject,User:alice .User:CN=alice,O=Shop - mallory's certificate was trusted, so she connected, but she has no ACL and got
. Authentication and authorization are separate checks.TopicAuthorizationException
Clients check the broker's host name against the certificate by default (ssl.endpoint.identification.algorithm=httpslocalhost127.0.0.1ssl.keystore.locationkafka-configs.shUser:ANONYMOUS
Prefixed ACLs, DENY and wildcards
Writing one ACL per topic does not scale to hundreds of topics. Kafka ACLs can match a name prefix or every name, and a DENY entry can carve out an exception. This program gives alice write access to all team-a.
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.acl.AccessControlEntry;
import org.apache.kafka.common.acl.AccessControlEntryFilter;
import org.apache.kafka.common.acl.AclBinding;
import org.apache.kafka.common.acl.AclBindingFilter;
import org.apache.kafka.common.acl.AclOperation;
import org.apache.kafka.common.acl.AclPermissionType;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourcePatternFilter;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AclPatterns {
static final List<String> TOPICS = List.of("team-a.orders", "team-a.payroll", "team-b.orders");
public static void main(String[] args) throws Exception {
KafkaClusterTestKit cluster = startCluster();
String bootstrap = cluster.bootstrapServers();
try (Admin admin = Admin.create(client(bootstrap, "PLAIN", "admin", "admin-secret"))) {
admin.createTopics(TOPICS.stream().map(t -> new NewTopic(t, 1, (short) 1))
.toList()).all().get();
AclBinding denyPayroll = acl(AclPermissionType.DENY, "User:alice",
"team-a.payroll", PatternType.LITERAL, AclOperation.WRITE);
admin.createAcls(List.of(
acl(AclPermissionType.ALLOW, "User:alice", "team-a.", PatternType.PREFIXED,
AclOperation.WRITE),
denyPayroll)).all().get();
Thread.sleep(500); // ACLs reach the broker through the metadata log
System.out.println("ALLOW WRITE on prefix team-a., DENY WRITE on team-a.payroll:");
sendAll(bootstrap);
System.out.println("alice sees topics " + topicsSeenByAlice(bootstrap));
admin.createAcls(List.of(acl(AclPermissionType.ALLOW, "User:*", "*",
PatternType.LITERAL, AclOperation.DESCRIBE))).all().get();
Thread.sleep(500);
System.out.println("with DESCRIBE on * for User:*, alice sees topics "
+ topicsSeenByAlice(bootstrap));
AclBindingFilter alicesAcls = new AclBindingFilter(ResourcePatternFilter.ANY,
new AccessControlEntryFilter("User:alice", null, AclOperation.ANY,
AclPermissionType.ANY));
admin.describeAcls(alicesAcls).values().get().stream()
.map(b -> b.entry().permissionType() + " " + b.entry().operation() + " "
+ b.pattern().patternType() + " " + b.pattern().name())
.sorted()
.forEach(a -> System.out.println(" alice: " + a));
admin.deleteAcls(List.of(denyPayroll.toFilter())).all().get();
Thread.sleep(500);
System.out.println("after deleting the DENY:");
sendAll(bootstrap);
} finally {
cluster.close();
}
}
static AclBinding acl(AclPermissionType type, String principal, String name,
PatternType pattern, AclOperation operation) {
return new AclBinding(new ResourcePattern(ResourceType.TOPIC, name, pattern),
new AccessControlEntry(principal, "*", operation, type));
}
static void sendAll(String bootstrap) throws Exception {
try (KafkaProducer<String, String> producer = new KafkaProducer<>(
client(bootstrap, "PLAIN", "alice", "alice-secret"),
new StringSerializer(), new StringSerializer())) {
for (String topic : TOPICS) {
try {
producer.send(new ProducerRecord<>(topic, "hello")).get();
System.out.println(" alice writes " + topic + ": ok");
} catch (ExecutionException e) {
System.out.println(" alice writes " + topic + ": "
+ e.getCause().getClass().getSimpleName());
}
}
}
}
static TreeSet<String> topicsSeenByAlice(String bootstrap) throws Exception {
try (Admin alice = Admin.create(client(bootstrap, "PLAIN", "alice", "alice-secret"))) {
return new TreeSet<>(alice.listTopics().names().get());
}
}
// Client settings for SASL over plaintext; production uses SASL_SSL
static Map<String, Object> client(String bootstrap, String mechanism, String user,
String password) {
String module = mechanism.equals("PLAIN")
? "org.apache.kafka.common.security.plain.PlainLoginModule"
: "org.apache.kafka.common.security.scram.ScramLoginModule";
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", bootstrap);
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.mechanism", mechanism);
props.put("sasl.jaas.config", module + " required username=\"" + user
+ "\" password=\"" + password + "\";");
props.put("max.block.ms", "5000"); // fail fast instead of waiting a minute
return props;
}
// Starts a one-node KRaft cluster in this JVM with KafkaClusterTestKit, the test
// cluster EmbeddedKafkaKraftBroker is built on, with SASL and the StandardAuthorizer
static KafkaClusterTestKit startCluster() throws Exception {
// logging is off: the clients log every refused request at ERROR, and this
// program prints the exceptions instead. Logback's Logger is named in full
// because org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
// the PLAIN users the broker accepts, and the broker's own login (admin)
String plainUsers = "org.apache.kafka.common.security.plain.PlainLoginModule required"
+ " username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\""
+ " user_alice=\"alice-secret\" user_bob=\"bob-secret\";";
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
new TestKitNodes.Builder()
.setCombined(true)
.setNumControllerNodes(1)
.setNumBrokerNodes(1)
.setBrokerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.setControllerSecurityProtocol(SecurityProtocol.SASL_PLAINTEXT)
.build())
.setConfigProp("authorizer.class.name",
"org.apache.kafka.metadata.authorizer.StandardAuthorizer")
.setConfigProp("super.users", "User:admin")
// one broker cannot hold the default 3 copies of the internal topics
.setConfigProp("offsets.topic.replication.factor", "1")
.setConfigProp("transaction.state.log.replication.factor", "1")
.setConfigProp("transaction.state.log.min.isr", "1")
.setConfigProp("allow.everyone.if.no.acl.found", "false")
.setConfigProp("listener.name.external.sasl.enabled.mechanisms",
"PLAIN,SCRAM-SHA-512")
.setConfigProp("listener.name.external.plain.sasl.jaas.config", plainUsers)
.setConfigProp("listener.name.external.scram-sha-512.sasl.jaas.config",
"org.apache.kafka.common.security.scram.ScramLoginModule required;")
.setConfigProp("listener.name.controller.plain.sasl.jaas.config", plainUsers)
.build();
cluster.format();
cluster.startup();
cluster.waitForReadyBrokers();
return cluster;
} finally {
System.setOut(stdout);
}
}
}
ALLOW WRITE on prefix team-a., DENY WRITE on team-a.payroll:
alice writes team-a.orders: ok
alice writes team-a.payroll: TopicAuthorizationException
alice writes team-b.orders: TopicAuthorizationException
alice sees topics [team-a.orders, team-a.payroll]
with DESCRIBE on * for User:*, alice sees topics [team-a.orders, team-a.payroll, team-b.orders]
alice: ALLOW WRITE PREFIXED team-a.
alice: DENY WRITE LITERAL team-a.payroll
after deleting the DENY:
alice writes team-a.orders: ok
alice writes team-a.payroll: ok
alice writes team-b.orders: TopicAuthorizationException
- The
ACL onPREFIXED let alice write toteam-a. . Topics that team-a creates later are covered automatically.team-a.orders - The DENY on
won over the prefixed ALLOW. Kafka checks DENY entries first, and any matching DENY refuses the request.team-a.payroll matched nothing, so the request was refused.team-b.orders- alice could still see
in her topic list: the DENY coversteam-a.payroll only, and the prefixedWRITE grant impliesWRITE .DESCRIBE - After an ALLOW of
onDESCRIBE for* , alice saw all three topics. The wildcards match every topic and every principal.User:* - After the DENY was deleted, the write to
succeeded.team-a.payroll
Every request type maps to an operation on a resource type: TOPICGROUPCLUSTERTRANSACTIONAL_IDDELEGATION_TOKEN
| Client | ACLs |
|---|---|
| Producer | WRITEDESCRIBE |
| Transactional producer | Also WRITEDESCRIBETRANSACTIONAL_ID |
| Consumer in a group | READREAD |
| Kafka Streams application | The above, plus CREATEDELETEapplication.id |
| Operator tools | DESCRIBEALTERCLUSTER |
From the command line, the same ACLs are managed with kafka-acls.sh --bootstrap-server ... --command-config admin.properties --add --allow-principal User:alice --operation Write --topic team-a. --resource-pattern-type prefixed
A secured client configuration
In production, the pieces combine into a SASL_SSL
# client.properties: SCRAM login inside TLS
bootstrap.servers=kafka-1:9093,kafka-2:9093,kafka-3:9093
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
username="orders-service" password="${file:/etc/kafka/secrets.properties:password}";
ssl.truststore.location=/etc/kafka/ca-truststore.p12
ssl.truststore.password=${file:/etc/kafka/secrets.properties:truststore}
config.providers=file
config.providers.file.class=org.apache.kafka.common.config.provider.FileConfigProvider
- Passwords out of the file: the
replaces eachFileConfigProvider reference with a value from another file, which can have stricter permissions or come from a secrets manager.${file:...} - The broker side: the listener needs
, a keystore,listeners=SASL_SSL://:9093 , andsasl.enabled.mechanisms on brokers and controllers.authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer - Inter-broker and controller traffic:
andinter.broker.listener.name should point at secured listeners too, with the brokers' own principals incontroller.listener.names .super.users - Spring Boot: the same keys go under
,spring.kafka.security.protocol andspring.kafka.properties.sasl.mechanism , andspring.kafka.properties.sasl.jaas.config .spring.kafka.ssl.*
Choosing a security setup
| Situation | Setup |
|---|---|
| Services with users and passwords | SASL_SSL |
| A company PKI already issues service certificates | SSLssl.client.auth=required |
| Central identity provider with short-lived tokens | SASL_SSL |
| Kerberos and Active Directory everywhere | SASL_SSL |
| Many topics per team | PREFIXEDteam.domain. |
| One sensitive topic inside a team's prefix | A DENY |
| Development on a laptop | PLAINTEXT |
Securing a cluster also changes how it is operated: every tool on --command-config