SSL证书自签名使用及监控 (2)

证书起到服务端口上了,我们怎么查看证书信息,或者实时检查证书过期信息呢,已默认443端口为例

root@CN-00013965:/# echo 'Q' | timeout 5 openssl s_client -connect 127.0.0.1:443 2>/dev/null | openssl x509 -noout -subject -dates subject=C = CN, ST = myprovince, L = mycity, O = myorganization, OU = mygroup, CN = , emailAddress = my@mail.com notBefore=Oct 18 08:09:32 2019 GMT notAfter=Oct 15 08:09:32 2029 GMT

如果postgresql数据库起的HTTPS,那么直接openssl不能直接拿到端口证书,我们可以借助python脚本,脚本是Github上找的

#!/usr/bin/env python import argparse import socket import ssl import struct import subprocess import sys try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse def main(): args = get_args() target = get_target_address_from_args(args) sock = socket.create_connection(target) try: certificate_as_pem = get_certificate_from_socket(sock) print(certificate_as_pem.decode('utf-8')) except Exception as exc: sys.stderr.write('Something failed while fetching certificate: {0}\n'.format(exc)) sys.exit(1) finally: sock.close() def get_args(): parser = argparse.ArgumentParser() parser.add_argument('database', help='Either an IP address, hostname or URL with host and port') return parser.parse_args() def get_target_address_from_args(args): specified_target = args.database if '//' not in specified_target: specified_target = '//' + specified_target parsed = urlparse(specified_target) return (parsed.hostname, parsed.port or 5432) def get_certificate_from_socket(sock): request_ssl(sock) ssl_context = get_ssl_context() sock = ssl_context.wrap_socket(sock) sock.do_handshake() certificate_as_der = sock.getpeercert(binary_form=True) certificate_as_pem = encode_der_as_pem(certificate_as_der) return certificate_as_pem def request_ssl(sock): version_ssl = postgres_protocol_version_to_binary(1234, 5679) length = struct.pack('!I', 8) packet = length + version_ssl sock.sendall(packet) data = read_n_bytes_from_socket(sock, 1) if data != b'S': raise Exception('Backend does not support TLS') def get_ssl_context(): for proto in ('PROTOCOL_TLSv1_2', 'PROTOCOL_TLSv1', 'PROTOCOL_SSLv23'): protocol = getattr(ssl, proto, None) if protocol: break return ssl.SSLContext(protocol) def encode_der_as_pem(cert): cmd = ['openssl', 'x509', '-inform', 'DER'] pipe = subprocess.PIPE process = subprocess.Popen(cmd, stdin=pipe, stdout=pipe, stderr=pipe) stdout, stderr = process.communicate(cert) if stderr: raise Exception('OpenSSL error when converting cert to PEM: {0}'.format(stderr)) return stdout.strip() def read_n_bytes_from_socket(sock, n): buf = bytearray(n) view = memoryview(buf) while n: nbytes = sock.recv_into(view, n) view = view[nbytes:] # slicing views is cheap n -= nbytes return buf def postgres_protocol_version_to_binary(major, minor): return struct.pack('!I', major << 16 | minor) if __name__ == '__main__': main()

使用方法:如果python文件名叫get_postgres_cert.py

python get_postgres_cert.py 127.0.0.1:5432

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjfzp.html