有没有办法以编程方式检查SAN SSL证书的主题备用名称?
例如,使用以下命令我可以获得许多信息但不是所有SAN:
openssl s_client -connect www.website.com:443
非常感谢!
答案 0 :(得分:78)
要获取证书的使用者备用名称(SAN),请使用以下命令:
openssl s_client -connect website.com:443 | openssl x509 -noout -text | grep DNS:
首先,此命令连接到我们想要的站点(website.com,SSL的端口443):
openssl s_client -connect website.com:443
然后管道(|
)进入此命令:
openssl x509 -noout -text
这将获取证书文件并输出所有有用的详细信息。 -noout
标志使其无法输出(base64编码的)证书文件本身,这是我们不需要的。 -text
标志告诉它以文本形式输出证书详细信息。
通常我们不关心大量的输出(签名,发行者,扩展等),因此我们将 管道输入一个简单的grep:
grep DNS:
由于SAN条目以DNS:
开头,因此只返回包含该条目的行,删除所有其他信息并留下所需信息。
您可能会注意到命令没有干净地退出; openssl s_client
实际上充当客户端并使连接保持打开状态,等待输入。如果您希望它立即退出(例如,在shell脚本中解析输出),只需将echo
输入其中:
echo | openssl s_client -connect website.com:443 | openssl x509 -noout -text | grep DNS:
为此,您不需要openssl s_client
命令。只需在-in MyCertificate.crt
命令上添加openssl x509
,然后再通过grep管道,例如:
openssl x509 -noout -text -in MyCertificate.crt | grep DNS:
答案 1 :(得分:2)
有没有办法以编程方式检查SAN SSL证书的备用名称?
X509证书中可能有多个SAN。以下内容来自SSL/TLS Client的OpenSSL wiki。它遍历名称并打印出来。
您从TLS连接X509*
中获取SSL_get_peer_certificate
,从内存中获取d2i_X509
,或从文件系统获得PEM_read_bio_X509
。
void print_san_name(const char* label, X509* const cert)
{
int success = 0;
GENERAL_NAMES* names = NULL;
unsigned char* utf8 = NULL;
do
{
if(!cert) break; /* failed */
names = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0 );
if(!names) break;
int i = 0, count = sk_GENERAL_NAME_num(names);
if(!count) break; /* failed */
for( i = 0; i < count; ++i )
{
GENERAL_NAME* entry = sk_GENERAL_NAME_value(names, i);
if(!entry) continue;
if(GEN_DNS == entry->type)
{
int len1 = 0, len2 = -1;
len1 = ASN1_STRING_to_UTF8(&utf8, entry->d.dNSName);
if(utf8) {
len2 = (int)strlen((const char*)utf8);
}
if(len1 != len2) {
fprintf(stderr, " Strlen and ASN1_STRING size do not match (embedded null?): %d vs %d\n", len2, len1);
}
/* If there's a problem with string lengths, then */
/* we skip the candidate and move on to the next. */
/* Another policy would be to fails since it probably */
/* indicates the client is under attack. */
if(utf8 && len1 && len2 && (len1 == len2)) {
fprintf(stdout, " %s: %s\n", label, utf8);
success = 1;
}
if(utf8) {
OPENSSL_free(utf8), utf8 = NULL;
}
}
else
{
fprintf(stderr, " Unknown GENERAL_NAME type: %d\n", entry->type);
}
}
} while (0);
if(names)
GENERAL_NAMES_free(names);
if(utf8)
OPENSSL_free(utf8);
if(!success)
fprintf(stdout, " %s: <not available>\n", label);
}
答案 2 :(得分:2)
也可以使用捆绑的openssl功能:
}
答案 3 :(得分:0)
如果您只想查看 SAN,则grep DNS:
是显而易见的解决方案。
如果您想要一个更干净的列表以进一步处理,可以使用此Perl正则表达式仅提取名称:@names=/\sDNS:([^\s,]+)/g
例如:
true | openssl s_client -connect example.com:443 2>/dev/null \
| openssl x509 -noout -text \
| perl -l -07 -ne '@names=/\bDNS:([^\s,]+)/g; print join("\n", sort @names);'
哪个会输出:
example.com
example.edu
example.net
example.org
www.example.com
www.example.edu
www.example.net
www.example.org
因此您可以将其通过管道传输到while read name; do echo "do stuff with $name"; done
等。
或者对于一行中用逗号分隔的列表,将join("\n",
替换为join(",",
(perl的-07
开关使它一次读取整个输入,而不是逐行读取)