如何在 tls 握手期间验证客户端证书

How to verify the client certificate during the tls handshake

我通过以下命令创建了一个 tls 服务器,它会要求正在连接的客户端提供客户端证书。我还使用 openssl 命令行模拟了一个客户端,它将提供一个客户端证书。但似乎服务器没有检查客户端证书是否正是我们想要的。你知道怎么让服务器做校验吗?

对于服务器:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
openssl s_server -key key.pem -cert cert.pem -accept 44330 -Verify 0

对于客户:

openssl req -x509 -newkey rsa:2048 -keyout clientkey.pem -out clientcert.pem -days 365 -nodes
openssl s_client -connect 127.0.0.1:44330 -cert clientcert.pem -key clientkey.pem

... check if the client certificate is what exactly we want or not

您没有从客户端证书中指定您想要的内容,这就是它无法检查的原因。如果您希望客户端证书由特定 CA 签名,请使用 -CAfile 选项 as documented:

-CAfile infile
A file containing trusted certificates to use during client authentication and to use when attempting to build the server certificate chain. The list is also used in the list of acceptable client CAs passed to the client when a certificate is requested.

因此,如果您想确保客户端证书是您签发的自签名证书(或其他由它签名的证书),请使用:

 openssl s_server -key key.pem -cert cert.pem -accept 44330 -Verify 0 \
   -CAfile clientcert.pem