2016-06-17 55 views
2

我想根據SSL證書檢查主機名和端口。我創建了這個功能:Python SSL證書根據公用名稱檢查主機名

@staticmethod 
def common_name_check(hostname, port): 
    try: 
     ctx = ssl.create_default_context() 
     s = ctx.wrap_socket(socket.socket(), server_hostname=hostname) 
     s.connect((hostname, int(port))) 
     cert = s.getpeercert() 
     ssl.match_hostname(cert, hostname) 
    except Exception as e: 
     exc_type, exc_obj, exc_tb = sys.exc_info() 
     fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] 
     print(exc_type, fname, exc_tb.tb_lineno) 
     return False 
    else: 
     return True 

我的問題是:當證書過期時,驗證失敗。但例外的是模棱兩可:

<class 'ssl.SSLError'> 

我不知道,如果錯誤是由於證書過期或壞的通用名稱

我怎麼能只檢查是否主機名/端口是有效的證書?

回答

0

正是。 SSL錯誤太泛泛。我也爲此苦苦掙扎。所以你可能想要檢查這個鏈接。

Verifying SSL certificates in python

下面是一個代碼唯一的答案。

from OpenSSL import SSL 
from socket import socket 

context = SSL.Context(SSL.TLSv1_METHOD) # Use TLS Method 
context.set_options(SSL.OP_NO_SSLv2) # Don't accept SSLv2 
context.set_verify(SSL.VERIFY_NONE, callback) 
context.load_verify_locations(ca_file, ca_path) 

host = "google.com" 
port = 443 #ssl 
sock = socket() 
ssl_sock = SSL.Connection(context, sock) 
ssl_sock.connect((host, port)) 
ssl_sock.do_handshake() 

def callback(self, conn, certificate, err, depth, valid): 
    # err here is the error code ([List of error codes and what they mean][2]. 
    if err == 62: 
     print("HOSTNAME MISMATCH!!!") 
相關問題