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)
예제 #2
0
 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()
예제 #3
0
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)))
예제 #4
0
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"
예제 #5
0
 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()
예제 #6
0
파일: __init__.py 프로젝트: renewfrl/python
def check_ssl_expiry_date(url):
    context = ssl.create_default_context()  #create a SSL context
    with socket.create_connection(
        (url, "443")) as sock:  #open connection to the server
        with context.wrap_socket(sock, server_hostname=url
                                 ) as ssock:  #provide access to the SSL layer
            data = ssock.getpeercert()  # get certificate
            return (ssock.version(), data['subjectAltName'][0][1],
                    data['notAfter'])
예제 #7
0
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))
            ]
예제 #8
0
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")
예제 #10
0
def get_num_days_before_expired(hostname: str, port: str = '443'):
    """
    Get number of days before an TLS/SSL of a domain expired
    """
    context = ssl.SSLContext()
    with socket.create_connection((hostname, port)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            certificate = ssock.getpeercert(True)
            cert = ssl.DER_cert_to_PEM_cert(certificate)
            x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                                   cert)
            cert_expires = datetime.strptime(
                x509.get_notAfter().decode('utf-8'), '%Y%m%d%H%M%S%z')
            num_days = (cert_expires - datetime.now(timezone.utc)).days
            # print(f'{hostname} expires in {num_days} day(s)')
            return num_days
예제 #11
0
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
예제 #13
0
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'

    hostname = base_url
    context = ssl.create_default_context()
예제 #14
0
from urllib.request import ssl, socket
from datetime import datetime
import pandas as pd
import json

# @title 獲取網站 SSL 憑證
# url = 'expired.badssl.com'   #80  @param {type: "string"}
url = 'myself-bbs.com'  # 443
context = ssl.create_default_context()
try:
    with socket.create_connection((url, '443')) as sock:
        with context.wrap_socket(sock, server_hostname=url) as ssock:
            ver = ssock.version()
            data = ssock.getpeercert()

    print('TLS 的版本為:', ver, '\n')
    print('SSL 憑證的細節為:')
    print(data)
except ssl.SSLCertVerificationError as err:
    print(str(err))
    print(str(err).split('certificate verify failed: ')[1])
except Exception as err:
    print(str(err))
예제 #15
0
def get_date(hostname, port):
    with socket.create_connection((hostname, port)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            cert = ssock.getpeercert()
            date_expire = datetime.strptime(cert["notAfter"], "%b  %d %H:%M:%S %Y %Z")
            return date_expire
# Opening file
IndataDomain = open(
    'C:\\Users\\LST\\Documents\\Python\\loop\\indatadomain.txt', 'r')
count = 0

# Using for loop
for line in IndataDomain:
    count += 1

    domain = ("{}".format(line.strip()))
    port = '443'
    context = ssl.create_default_context()

    reversed_dns = socket.gethostbyaddr(domain)

    with socket.create_connection((domain, port)) as sock:
        with context.wrap_socket(sock, server_hostname=domain) as ssock:
            #print(ssock.version())
            CertInfoALL = json.dumps(ssock.getpeercert())
            #notBefore
            notBeforepattern = "notBefore(.*?),"  #Hittar text mellan "notBefore" & ","
            notBeforesubstring = re.search(
                notBeforepattern, CertInfoALL).group(
                    0
                )  #Grupp(0) skriver även ut notbefore, det gör inte group(1)
            #notAfter
            notAfterpattern = "notAfter(.*?),"  #Hittar text mellan "notBefore" & ","
            notAftersubstring = re.search(notAfterpattern, CertInfoALL).group(
                0)  #Grupp(0) skriver även ut notbefore, det gör inte group(1)

            #print("Date:" , today, "; Domain:" , domain,";", notBeforesubstring,";" , notAftersubstring) #Skriv ut på skärm för test
예제 #17
0
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)
        ]