传输时加密

传输时的加密(In-flight encryption)分为两种情况:

  • Brokers之间数据进行同步时的加密
  • Client和Broker进行通讯时的加密

image-20220102181259080

MSK TLS相关设置

在第一章我们创建MSK时,使用了默认的Encryption配置:

  • Client可以使用Plaintext或TLS encryption两种方式连接
  • Brokers之间的通讯也是TLS加密的

image-20220102182849372

集群创建完成后,在控制台里也能找到相关的属性:

image-20220102182335611

开启TLS会影响性能,包括CPU负载(甚至达到30%)、增加几毫秒的延迟 参考: https://docs.aws.amazon.com/msk/latest/developerguide/msk-encryption.html 但Kafka本身也不是CPU密集型的

使用TLS方式连接MSK

获取broker连接方式时,有BootstrapBrokerStringTls的连接方式, 将其保存到环境变量:

# aws kafka get-bootstrap-brokers --cluster-arn <cluster-arn>

kongpingfan:~/environment $ aws kafka get-bootstrap-brokers --cluster-arn arn:aws:kafka:ap-southeast-1:145197526627:cluster/MSKDemo/89d04308-2643-4e80-b6e2-fe996354f056-4
{
    "BootstrapBrokerStringSaslIam": "b-2.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9098,b-1.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9098,b-3.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9098", 
    "BootstrapBrokerStringTls": "b-2.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094,b-1.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094,b-3.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094", 
    "BootstrapBrokerString": "b-2.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9092,b-1.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9092,b-3.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9092"
}

export KAFKA_TLS=b-2.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094,b-1.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094,b-3.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094

使用 openssl命令测试,可以看到Amazon颁发的证书

openssl s_client -connect b-6.mskdemo.mxqzz7.c4.kafka.ap-southeast-1.amazonaws.com:9094

image-20220102183959723

现在创建一个topic进行测试:

image-20220102184515531

却发现报OutOfMemoryError,这是使用TLS方式连接Kafka时一个常见的问题。这并不是真的和内存有关,而是没有配置client使用SSL方式连接

将以下内容写到client-ssl.properties,再重新进行创建,此时可以创建成功:

echo 'security.protocol=SSL' > client-ssl.properties

# create the topic correctly
kafka-topics --bootstrap-server $KAFKA_TLS --create --topic TLSTestTopic --partitions 3 --replication-factor 3 --command-config client-ssl.properties

同理,当我们向topic里写数据时,也要加上--producer.config=client-ssl.properties参数:

kafka-console-producer --bootstrap-server $KAFKA_TLS --topic TLSTestTopic --producer.config client-ssl.properties

image-20220102185406050

大部分的JVM都会信任Amazon的证书。如果使用上面的配置依然连接报错,可以使用下面这种方式来解决:

# Corretto 11
cp /usr/lib/jvm/java-11-amazon-corretto.x86_64/lib/security/cacerts /tmp/kafka.client.truststore.jks 

# Java JDK 8
cp /usr/lib/jvm/java-1.8.0-openjdk/jre/lib/security/cacerts /tmp/kafka.client.truststore.jks

# new property
echo 'ssl.truststore.location=/tmp/kafka.client.truststore.jks' >> client-ssl.properties