def obtain_cert_info(self): context = ssl.create_default_context() with socket.create_connection((self.base_url, self.port)) as socket_connection: with context.wrap_socket(socket_connection, server_hostname=self.base_url) as server_socket: # uncomment to print everything # print(json.dumps(server_socket.getpeercert() , indent=2, sort_keys=True)) cert_info = server_socket.getpeercert() subject = dict(x[0] for x in cert_info['subject']) issued_to = subject['commonName'] issuer = dict(x[0] for x in cert_info['issuer']) issued_by = issuer['commonName'] valid_from = cert_info['notBefore'] valid_to = cert_info['notAfter'] serial_number = cert_info['serialNumber'] der_cert = server_socket.getpeercert(False) der_cert_bin = server_socket.getpeercert(True) pem_cert = ssl.DER_cert_to_PEM_cert(server_socket.getpeercert(True)) # uncomment the below line if you want to see the actual public cert # print("certificate pub:",pem_cert) thumb_md5 = hashlib.md5(der_cert_bin).hexdigest() thumb_sha1 = hashlib.sha1(der_cert_bin).hexdigest() thumb_sha256 = hashlib.sha256(der_cert_bin).hexdigest() print("issued_to: " + issued_to) print("issued_by: " + issued_by) print("valid_from: " + valid_from) print("valid_to: " + valid_from) print("MD5: " + thumb_md5) print("SHA1: " + thumb_sha1) print("SHA256: " + thumb_sha256) print("cipher: " + str(server_socket.cipher())) print("SSL/TLS version: " + server_socket.version()) print("serial_number: " + serial_number) # print(server_socket.shared_ciphers()) server_socket.close()
def getSSLInfo(checkthis, host, port): try: # if it's https, this will work, or should work context = ssl.create_default_context() with socket.create_connection((host, port)) as sock: with context.wrap_socket(sock, server_hostname=host) as ssock: # get the ssl/tls info: d = ssock.getpeercert() # dumps a 3 part list: encryption, version, bits cipherinfo = ssock.cipher() # time from input dt1 = datetime.strptime(d['notAfter'], '%b %d %H:%M:%S %Y GMT') # time difference timediff = dt2 - dt1 print(str(timediff.days) + ",", end='') print(d['serialNumber'] + ",", end='') # 56E419412363A9E0E94715A1EC60E545 print(ssock.version() + ",", end='') # TLSv1.2 (or SSLv2, SSLv3, TLSv1, TLSv1.1) print(str(d['version']) + ",", end='') # 3 print(str(cipherinfo[2]) + ",", end='') # 256 print(cipherinfo[0] + ",", end='') # ECDHE-RSA-AES256-GCM-SHA384 print(d['notAfter'] + ",", end='') # May 24 23:59:59 2020 GMT print(host + ":" + str(port) + ",", end='') # rubysash:443 print(getResponseCode(checkthis)) except: # whoops, it's probably not https. Do something better here print("1,0,0,0,0,", end='') print(host + ":" + str(port) + "," + str(getResponseCode(checkthis)))
def check_SSL_certificate(url, verbose): """ Check SSL certificate expiration date of a server hostname """ hostname = urllib.parse.urlparse(url).hostname port = urllib.parse.urlparse(url).port if verbose == 1: print("- Checking SSL certificate in progres...") now = datetime.now() context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: if verbose == 1: print(json.dumps(ssock.getpeercert())) expire_data = json.dumps(ssock.getpeercert()["notAfter"][:-4]) # Stripping (") from string expire_data = expire_data[1:] expire_data = expire_data[:-1] date_time_obj = datetime.strptime(expire_data, "%b %d %H:%M:%S %Y") if date_time_obj > now: return "valid" else: return "expired"
def checkSSlcertificate(url): base_url = url.replace('https://', '') base_url = base_url.replace('/', '') print("base_url", base_url) port = '443' hostname = base_url context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: try: with context.wrap_socket(sock, server_hostname=hostname) as ssock: #print("Sock", ssock.version()) data = ssock.getpeercert() # print(ssock.getpeercert()) except CertificateError: print("SSL certificate error ", url) # send notification to bot exit() date_time_str = data["notAfter"] date_time_obj = datetime.datetime.strptime(date_time_str, '%b %d %H:%M:%S %Y GMT') print('Date:', date_time_obj) currentTime = datetime.datetime.now() print(currentTime) certificateExpirationDate = date_time_obj - currentTime print(str(certificateExpirationDate)) daysToExpire = str(certificateExpirationDate).split()[0] print(daysToExpire) if int(daysToExpire) <= 60: print("less then 60 days to expire SSL certificate for URL ", url)
def obtain_cert_info(self): context = ssl.create_default_context() with socket.create_connection((self.base_url, self.port)) as socket_connection: with context.wrap_socket(socket_connection, server_hostname=self.base_url) as server_socket: #uncomment to print everything #print(json.dumps(server_socket.getpeercert() , indent=2, sort_keys=True)) cert_info = server_socket.getpeercert() subject = dict(x[0] for x in cert_info['subject']) issued_to = subject['commonName'] issuer = dict(x[0] for x in cert_info['issuer']) issued_by = issuer['commonName'] valid_from =cert_info['notBefore'] valid_to = cert_info['notAfter'] serial_number =cert_info['serialNumber'] der_cert = server_socket.getpeercert(False) der_cert_bin = server_socket.getpeercert(True) pem_cert = ssl.DER_cert_to_PEM_cert(server_socket.getpeercert(True)) # uncomment the below line if you want to see the actual public cert #print("certificate pub:",pem_cert) thumb_md5 = hashlib.md5(der_cert_bin).hexdigest() thumb_sha1 = hashlib.sha1(der_cert_bin).hexdigest() thumb_sha256 = hashlib.sha256(der_cert_bin).hexdigest() print("issued_to: " + issued_to) print("issued_by: " + issued_by) print("valid_from: " + valid_from) print("valid_to: " + valid_from) print("MD5: " + thumb_md5) print("SHA1: " + thumb_sha1) print("SHA256: " + thumb_sha256) print ("cipher: "+str(server_socket.cipher())) print("SSL/TLS version: "+server_socket.version()) print("serial_number: "+serial_number) # print(server_socket.shared_ciphers()) server_socket.close()
def getSSLInfo(kid): host = str(sites[kid][0]) # expert-marketer.com port = str(sites[kid][1]) # 80 proto = str(sites[kid][3]) # http:// or https:// path = str(sites[kid][4]) # / or /somepath.php text = str(sites[kid][5]) # text to validate on the site # It's either going to be http or https # if it's http, we just put place holders for now checkthis = proto + host + ":" + port + path if (proto == 'http://'): nd[kid] = [ 1, 0, 0, 0, 0, 0, host + ":" + str(port), str(getResponseCode(checkthis)) ] else: try: # if it's https, this will work, or should work context = ssl.create_default_context() with socket.create_connection((host, port)) as sock: with context.wrap_socket(sock, server_hostname=host) as ssock: # get the ssl/tls info: d = ssock.getpeercert() # dumps a 3 part list: encryption, version, bits cipherinfo = ssock.cipher() # time from input dt1 = datetime.strptime(d['notAfter'], '%b %d %H:%M:%S %Y GMT') # time difference timediff = dt2 - dt1 #print(str(timediff.days) + ",", end='') #print(d['serialNumber'] + ",", end='') # 56E419412363A9E0E94715A1EC60E545 #print(str(d['version']) + ",", end='') # 3 #print(ssock.version() + ",", end='') # TLSv1.2 (or SSLv2, SSLv3, TLSv1, TLSv1.1) #print(str(cipherinfo[2]) + ",", end='') # 256 (x8 for 2048 RSA key) #print(cipherinfo[0] + ",", end='') # ECDHE-RSA-AES256-GCM-SHA384 #print(d['notAfter'] + ",", end='') # May 24 23:59:59 2020 GMT #print(host + ":" + str(port) + ",", end='') # rubysash:443 #print(getResponseCode(checkthis)) nd[kid] = [ ssock.version(), d['version'], str(timediff.days), d['notAfter'], cipherinfo[2], cipherinfo[0], host + ":" + str(port), str(getResponseCode(checkthis)) ] except: # whoops, it's probably not https. Do something better here nd[kid] = [ 1, 0, 0, 0, 0, 0, host + ":" + str(port), str(getResponseCode(checkthis)) ]
def get_ssl_expire_time_difference(base_url): #some site without http/https in the path port = '443' #base_url = 'google.com' # for test hostname = base_url #ssl._create_default_https_context = ssl._create_unverified_context() context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: #print(ssock.version()) data = json.dumps(ssock.getpeercert()) # convert to dict type data2 = json.loads(data) #print(type(data2)) #print( data2) # Get Expire Date expire = data2['notAfter'] #print( 'expire date :' + expire) # UTC +0 # GMT String To GMT Time #dateString = "Oct 28 23:59:59 2020 GMT" dateString = expire dateFormatter = "%b %d %H:%M:%S %Y GMT" expire_time = datetime.strptime(dateString, dateFormatter) # Convert UTC + 8 expire_time = expire_time + timedelta(hours=8) expire_date = expire_time.strftime('%Y-%m-%d %H:%M:%S ') # print( 'expire date : ' + expire_date ) # Get Time Now t = datetime.now() # Calculate Time Difference d1 = expire_time #d1 = datetime(2020, 8, 3) # for test d2 = t dayCount = (d1 - d2).days #print( dayCount ) return dayCount, expire_date
def _get_certification_expiration_date_for_given_service(self, endpoint): endpoint = endpoint.lstrip() if self._valid_url(url=endpoint): if self._is_https_endpoint(endpoint): endpoint = self.obj_util.remove_http_https_prefix(url=endpoint) hostname = endpoint.split(":")[0] port = endpoint.split(":")[1] context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket( sock, server_hostname=hostname) as ssock: data = json.dumps(ssock.getpeercert()) expiration_date = json.loads(data)["notAfter"] return dt.strptime(expiration_date, "%b %d %H:%M:%S %Y %Z")
def _validate_ssl(): from urllib.request import Request, urlopen, ssl, socket from urllib.error import URLError, HTTPError import json #some site without http/https in the path base_url = 'CHANGE_ME_TO_YOUR_SITE' port = '443' hostname = base_url context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: print(ssock.version()) data = json.dumps(ssock.getpeercert()) # print(ssock.getpeercert()) print (data)
def lambda_handler(event, context): # TCP connection should be fast, so let's set a timeout of 10 seconds tcp_connection_timeout = 10 # Handle query strings to avoid "Internal server error" from API Gateway if event['queryStringParameters']: if 'url' in event['queryStringParameters']: base_url = event["queryStringParameters"]['url'] else: response = { "statusCode": 200, "isBase64Encoded": False, "body": "Usage: ?url=domain.com&port=443" } return response # use port 443 if client didn't send port query string if 'port' in event['queryStringParameters']: port = int(event["queryStringParameters"]['port']) else: port = 443 context = ssl.create_default_context() try: with socket.create_connection((base_url, port), timeout=tcp_connection_timeout) as sock: with context.wrap_socket(sock, server_hostname=base_url) as ssock: data = ssock.getpeercert() except Exception as e: response = { "statusCode": 200, "isBase64Encoded": False, "body": f'Error: {e}' } return response # format ssl end date date output to mm/dd/YYYY ssl_end_date_format = datetime.strptime( data['notAfter'], '%b %d %X %Y %Z').strftime('%m/%d/%Y') response = { "statusCode": 200, "isBase64Encoded": False, "body": ssl_end_date_format } return response
def send_notification(days_to_expire): smtp_port = 587 smtp_server = "smtp.acmecorp.com" sender_email = "*****@*****.**" receiver_email = "*****@*****.**" password = input("Type your password and press enter: ") if days_to_expire == 1: days = "1 day" else: days = str(days_to_expire) + " days" message = """\ Subject: Certificate Expiration The TLS Certificate for your site expires in {days}""" email_context = ssl.create_default_context() with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls(context=email_context) server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.format(days=days))
def get_ssl_date(base_url, port=443): """[summary] Args: base_url (string): give domain name that you want port (int): give your website port if do not know it, use defaults Returns: dictionary: it,s return dictionary with startdate and enddate of certificate """ hostname = base_url row = {} try: context = ssl.create_default_context(cafile=certifi.where()) with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: start_date = ssock.getpeercert()['notBefore'] expire_date = ssock.getpeercert()['notAfter'] row = {"start_date": start_date, "expire_date": expire_date} except Exception as error: print("error to find ssl expire date: {}".format(error)) return row
get_file = open('your_path', 'r') file = get_file.read() dictionary = yaml.load(file, Loader=yaml.FullLoader) urls_prod = dictionary['domain']['prod'] urls_prep = dictionary['domain']['prep'] server_name = dictionary['server'] port_number = dictionary['port'] statsd_client = StatsClient(server_name, port_number) for url in urls_prod: base_url = url port = '443' hostname = base_url context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: data = ssock.getpeercert() x = data['notAfter'] obj = datetime.strptime(x, '%b %d %H:%M:%S %Y GMT').date() delta = (obj - date.today()).days statsd_client.gauge(f'whatever_you_want.exp', delta) for url in urls_prep: base_url = url port = '443'
def getSSLInfo(kid): host = str(sites[kid]) # expert-marketer.com # fixme: this was so we could check corp tools for strings # and check if apps were up, etc. Haven't implemented yet #port = str(sites[kid][1]) # 80 #proto = str(sites[kid][3]) # http:// or https:// #path = str(sites[kid][4]) # / or /somepath.php #text = str(sites[kid][5]) # text to validate on the site # fixme: Everything is https, on port 443 - not real world proto = 'https://' port = '443' path = '/' text = 'N/A' # It's either going to be http or https # if it's http, we just put place holders for now # fixme: this logic was for testing other than https, but we aren't doing that now checkthis = proto + host + ":" + port + path code = getResponseCode(checkthis) if (proto == 'http://'): nnd[kid] = [ '--', "--", "--", "--", "--", "--", host + ":" + str(port), str(code) ] elif (code == 200): try: # if it's https, this will work, or should work context = ssl.create_default_context() with socket.create_connection((host, port)) as sock: # fixme: chokes on invalid URL with context.wrap_socket(sock, server_hostname=host) as ssock: # get the ssl/tls info: d = ssock.getpeercert() # dumps a 3 part list: encryption, version, bits cipherinfo = ssock.cipher() # time from input dt1 = datetime.strptime(d['notAfter'], '%b %d %H:%M:%S %Y GMT') # time difference timediff = dt2 - dt1 #print(str(timediff.days) + ",", end='') # -42 #print(d['serialNumber'] + ",", end='') # 56E419412363A9E0E94715A1EC60E545 #print(str(d['version']) + ",", end='') # 3 #print(ssock.version() + ",", end='') # TLSv1.2 (or SSLv2, SSLv3, TLSv1, TLSv1.1) #print(str(cipherinfo[2]) + ",", end='') # 256 (x8 for 2048 RSA key) #print(cipherinfo[0] + ",", end='') # ECDHE-RSA-AES256-GCM-SHA384 #print(d['notAfter'] + ",", end='') # May 24 23:59:59 2020 GMT #print(host + ":" + str(port) + ",", end='') # rubysash:443 nd[kid] = [ ssock.version(), d['version'], str(timediff.days), d['notAfter'], cipherinfo[2], cipherinfo[0], host + ":" + str(port), str(code) ] except: # whoops, it's probably not https, but we did get a 200 code. Do something better here # this branch only happened when I was debugging code error, not with working code nd[kid] = [ '--', "--", "--", "--", "--", "--", host + ":" + str(port), str(code) ] else: # this branch is the normal failsafe if we can't get a good handshake nd[kid] = [ '--', "--", "--", "--", "--", "--", host + ":" + str(port), str(code) ]