🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Kafka Security

đŸŸĸ Free Lesson

Kafka Security

AuthenticationSASL / mTLSWho are you?AuthorizationACLsWhat can you do?EncryptionSSL/TLSData ProtectionAuditLoggingComplianceKafka Security Layers

Overview

Kafka provides comprehensive security features to protect your event streaming platform across four critical dimensions: authentication, authorization, encryption, and auditing. This guide covers implementing each security layer effectively.

Security Requirements

  • Confidentiality: Data encrypted in transit and at rest
  • Integrity: Messages cannot be tampered with
  • Authentication: Verify identity of clients and brokers
  • Authorization: Control access to topics and operations
  • Auditability: Track all access and operations

Those five requirements are not equally hard, and confusing them is the most common design error. Authentication proves who is connecting, authorization decides what that identity may do, and encryption protects the bytes on the wire; none of the three tells you what happened after the fact, which is why audit logging is a separate layer rather than a by-product. Kafka applies them at the listener, so the same cluster can expose a plaintext port inside a private network and an encrypted, authenticated port to the outside, and the failure mode to fear is the one where an internal port is reachable from an untrusted network because the firewall rule was written for a different listener name.

Threat modelling also forces you to name the attacker. If the risk is packet capture on the wire, TLS alone answers it. If the risk is a compromised application host, no amount of transport security helps because the attacker holds the credentials, so short-lived tokens, per-service principals and audit trails are what actually limit the blast radius. Security work that skips this step ends up with beautiful certificates and a wildcard ACL granting a service account read access to every topic in the cluster.

SSL/TLS Encryption

Certificate Generation

# Generate CA certificate
openssl req -new -x509 -keyout ca-key -out ca-cert -days 365 \
  -subj "/CN=Kafka-CA" -passout pass:ca-password

# Generate broker keystore
keytool -keystore kafka.server.keystore.jks \
  -alias kafka-broker -validity 365 -genkey \
  -keyalg RSA -keysize 2048 \
  -dname "CN=kafka-broker,OU=IT,O=Company"

# Generate broker truststore
keytool -keystore kafka.server.truststore.jks \
  -alias ca-cert -importcert -file ca-cert \
  -storepass truststore-password

Broker SSL Configuration

# server.properties
listeners=SSL://0.0.0.0:9093
ssl.keystore.location=/var/kafka/ssl/kafka.server.keystore.jks
ssl.keystore.password=keystore-password
ssl.key.password=key-password
ssl.truststore.location=/var/kafka/ssl/kafka.server.truststore.jks
ssl.truststore.password=truststore-password
ssl.client.auth=required
ssl.enabled.protocols=TLSv1.2,TLSv1.3
ssl.cipher.suites=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

Two lines in that block decide whether TLS is real or decorative. ssl.client.auth=required turns the listener into mutual TLS, so a client without a certificate signed by the same authority cannot even open a session; drop it to requested and unauthenticated clients still connect, they simply arrive without an identity for the authorizer to match. And ssl.enabled.protocols=TLSv1.2,TLSv1.3 matters because Java's defaults otherwise permit older protocol versions that a penetration test will flag within minutes.

Certificates expire on a schedule that ignores your deploy calendar. A one-year broker certificate that nobody renews becomes a cluster-wide outage on a random Tuesday, because brokers that cannot complete the TLS handshake reject every produce and fetch request while looking perfectly healthy in the process list. The working routine is to issue certificates with a subject alternative name covering each broker's hostname, keep the certificate authority key offline, load new certificates into a second keystore path, restart brokers one at a time so the in-sync replica set never drops below min.insync.replicas, then switch back. Clients verify the hostname through ssl.endpoint.identification.algorithm=https; setting that property to an empty string disables hostname verification, which is convenient in a lab and is the single most common way a "TLS everywhere" deployment quietly accepts any certificate it is shown.

Client SSL Configuration

# client.properties
ssl.truststore.location=/var/kafka/ssl/kafka.client.truststore.jks
ssl.truststore.password=truststore-password
ssl.keystore.location=/var/kafka/ssl/kafka.client.keystore.jks
ssl.keystore.password=keystore-password
ssl.key.password=key-password
security.protocol=SSL

SASL Authentication

SASL Mechanisms Comparison

MechanismDescriptionUse Case
PLAINUsername/passwordDevelopment, simple setups
SCRAM-SHA-256/512Salted challenge responseProduction with LDAP
GSSAPIKerberosEnterprise environments
OAUTHBEAREROAuth 2.0 tokensCloud-native applications

Each mechanism answers a different operational question. PLAIN sends username and password as base64, which is trivially reversible, so it is only acceptable inside a TLS tunnel where the encrypted channel does the protecting; it survives in development because it needs no key material at all. SCRAM stores a salted hash in the cluster metadata rather than the password itself and proves knowledge of the password through a challenge-response, so a stolen credential store does not yield working passwords, and raising iterations from the default 4096 to 8192 trades a few milliseconds of handshake CPU for a much harder offline attack. GSSAPI buys delegation of Kerberos tickets in environments that already run a kdc, and OAUTHBEARER lets the cluster validate a bearer token issued by an external identity provider instead of holding credentials of its own.

Whichever you pick, remember that the mechanism is negotiated during the SASL handshake before the client sends its first fetch, and that brokers must agree among themselves: security.inter.broker.protocol and sasl.mechanism.inter.broker.protocol describe how replicas replicate metadata from the controller, so a mismatch there breaks log replication rather than client access and looks like a partition assignment problem in the logs.

SASL/SCRAM Setup

# Create SCRAM credentials
kafka-configs.sh --bootstrap-server localhost:9092 \
  --alter \
  --add-config 'SCRAM-SHA-256=[iterations=8192,password=admin-secret],SCRAM-SHA-512=[iterations=8192,password=admin-secret]' \
  --entity-type users --entity-name admin

kafka-configs.sh --bootstrap-server localhost:9092 \
  --alter \
  --add-config 'SCRAM-SHA-256=[iterations=8192,password=app-secret]' \
  --entity-type users --entity-name app-user

SASL Configuration

# server.properties
listeners=SASL_SSL://0.0.0.0:9093
security.inter.broker.protocol=SASL_SSL
sasl.mechanism.inter.broker.protocol=SCRAM-SHA-256
sasl.enabled.mechanisms=SCRAM-SHA-256,SCRAM-SHA-512

# JAAS configuration
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
  username="admin" \
  password="admin-secret";

Python Client with SASL

python
from kafka import KafkaProducer
from kafka import KafkaConsumer

# Producer with SASL
producer = KafkaProducer(
    bootstrap_servers=['kafka-broker:9093'],
    security_protocol='SASL_SSL',
    sasl_mechanism='SCRAM-SHA-256',
    sasl_plain_username='app-user',
    sasl_plain_password='app-secret',
    ssl_cafile='/var/kafka/ssl/ca-cert'
)

# Consumer with SASL
consumer = KafkaConsumer(
    'orders',
    bootstrap_servers=['kafka-broker:9093'],
    security_protocol='SASL_SSL',
    sasl_mechanism='SCRAM-SHA-256',
    sasl_plain_username='consumer-user',
    sasl_plain_password='consumer-secret',
    ssl_cafile='/var/kafka/ssl/ca-cert',
    group_id='order-processor'
)

ACL Authorization

ACL Structure

ACLs follow the pattern: Principal + Resource + Operation + Permission

# Grant read access to topic for specific user
kafka-acls.sh --bootstrap-server localhost:9093 \
  --add \
  --allow-principal User:app-user \
  --operation Read \
  --topic orders \
  --command-config admin.properties

# Grant write access to topic
kafka-acls.sh --bootstrap-server localhost:9093 \
  --add \
  --allow-principal User:app-user \
  --operation Write \
  --topic orders \
  --command-config admin.properties

# List ACLs for a topic
kafka-acls.sh --bootstrap-server localhost:9093 \
  --list \
  --topic orders \
  --command-config admin.properties

Common ACL Patterns

# Producer ACLs
kafka-acls.sh --add --allow-principal User:producer \
  --operation Read --topic orders \
  --operation Describe --topic orders

# Consumer ACLs
kafka-acls.sh --add --allow-principal User:consumer \
  --operation Read --topic orders \
  --operation Read --group order-processor

# Admin ACLs
kafka-acls.sh --add --allow-principal User:admin \
  --operation All --topic '*' \
  --operation All --group '*'

ACL Authorizer Configuration

# server.properties
authorizer.class.name=kafka.security.authorizer.AclAuthorizer
super.users=User:admin
allow.everyone.if.no.acl.found=false

allow.everyone.if.no.acl.found=false is the setting that decides whether the cluster fails open or fails closed. With it set to true, a principal with no matching ACL is allowed to do everything, which is fine for a first migration and disastrous as a permanent state: the first team that forgets to add an ACL gets silent, complete access. Setting it to false means an unknown principal is refused, so the operational symptom of a wrong principal name is a clean TopicAuthorizationException in the client rather than a security gap nobody notices. super.users bypasses the authorizer entirely, and the discipline is to keep that list to one break-glass principal used by humans during an incident, never by an application.

Two subtleties cost teams hours each year. First, a producer needs Describe as well as Write, and a consumer needs Read on the topic plus Read on its consumer group, because the group ACL is checked when the member joins; granting only topic access produces failures that read like broker bugs. Second, in KRaft mode the built-in authorizer is kafka.security.authorizer.StandardAuthorizer, while ZooKeeper-based deployments use kafka.security.authorizer.AclAuthorizer, so a config file copied between clusters of different modes silently disables authorization when the class name does not resolve. Verify with kafka-acls.sh --list against every cluster after a migration rather than trusting the file.

Encryption at Rest

Broker Configuration

# Enable encryption at rest (requires specific storage backend)
log.dirs=/encrypted/kafka-logs
compression.type=lz4

Kafka itself never encrypts log segments; the two settings above only place data on a volume that an operator has already encrypted with dm-crypt, LUKS or a cloud provider's volume encryption, and compression happens first so the ciphertext is not full of zeros. Because the page cache holds hot segments in memory unencrypted by design, this layer defends against a stolen disk or a decommissioned host, not against an attacker with a shell on a live broker.

Client-Side Encryption

python
from cryptography.fernet import Fernet
from kafka import KafkaProducer
import json

class EncryptedProducer:
    def __init__(self, bootstrap_servers, encryption_key):
        self.producer = KafkaProducer(
            bootstrap_servers=bootstrap_servers,
            value_serializer=lambda v: json.dumps(v).encode('utf-8')
        )
        self.cipher = Fernet(encryption_key)
    
    def send(self, topic, message, key=None):
        encrypted_value = self.cipher.encrypt(json.dumps(message).encode())
        self.producer.send(topic, key=key, value=encrypted_value)
    
    def flush(self):
        self.producer.flush()

# Usage
key = Fernet.generate_key()
producer = EncryptedProducer(['kafka:9092'], key)
producer.send('sensitive-orders', {'amount': 100, 'user': 'john'})

Audit Logging

Authorization decisions are logged only if you ask for them. Setting the kafka.authorizer.logger to INFO writes every allow and deny with the principal, the resource and the operation, which is the record auditors actually accept; at WARN you get denials alone and cannot prove who read what. Volume is predictable once you measure it: a cluster serving 5,000 requests per second from 40 services can emit tens of millions of lines a day, so the log needs its own shipper, its own retention window and a destination outside the cluster, because a broker that cannot write to disk because the audit file filled the volume has turned a compliance feature into an outage. Ship to an append-only store, alert on repeated denials from one principal, and keep the audit trail long enough to satisfy the policy you published, not merely as long as the disk allows.

Security Best Practices

1. Network Security

# Bind to specific interface
listeners=SSL://10.0.1.10:9093

# Restrict listener names
listener.security.protocol.map=INTERNAL:SSL,EXTERNAL:SASL_SSL
inter.broker.listener.name=INTERNAL

2. Credential Management

python
# Use environment variables for credentials
import os
from kafka import KafkaProducer

producer = KafkaProducer(
    bootstrap_servers=os.environ['KAFKA_BOOTSTRAP_SERVERS'],
    sasl_plain_username=os.environ['KAFKA_SASL_USERNAME'],
    sasl_plain_password=os.environ['KAFKA_SASL_PASSWORD'],
    ssl_cafile=os.environ['KAFKA_SSL_CAFILE']
)

3. Regular Credential Rotation

#!/bin/bash
# rotate_scram_credentials.sh

NEW_PASSWORD=$(openssl rand -base64 32)

kafka-configs.sh --bootstrap-server localhost:9093 \
  --alter \
  --add-config "SCRAM-SHA-256=[password=$NEW_PASSWORD]" \
  --entity-type users --entity-name app-user

# Update application configuration
echo "SCRAM_PASSWORD=$NEW_PASSWORD" > /etc/kafka/.env.new
mv /etc/kafka/.env.new /etc/kafka/.env

4. Security Checklist

  • SSL/TLS enabled for all listeners
  • SASL authentication configured
  • ACLs implemented for all topics
  • Super users limited to emergency access only
  • Credentials stored in secure vault
  • Audit logging enabled
  • Regular security assessments scheduled

Common Mistakes

Setting ssl.endpoint.identification.algorithm to an empty string so brokers stop complaining about certificates

Fix: Keep hostname verification on and issue certificates with correct subject alternative names, otherwise TLS will happily encrypt a connection to the wrong host

Granting a consumer Read on the topic but forgetting Read on the consumer group

Fix: Add both ACLs, because the group permission is checked when the member joins and the failure surfaces as a rebalance loop rather than an authorization error

Copying a ZooKeeper-era authorizer class into a KRaft cluster

Fix: Use kafka.security.authorizer.StandardAuthorizer on KRaft and confirm with kafka-acls.sh --list that authorization is actually answering requests

Summary

Kafka security requires a defense-in-depth approach implementing SSL/TLS encryption, SASL authentication, ACL authorization, and comprehensive auditing. Follow security best practices and regularly audit your configuration to maintain a secure event streaming platform.

See Also

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Kafka Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement