Пример #1
0
def printcert(host, port, hostname):
    con = Connection(Context(TLSv1_METHOD), socket(AF_INET, SOCK_STREAM))
    con.connect((host, port))
    con.set_tlsext_host_name(hostname if hostname else host)
    con.do_handshake()
    con.shutdown()
    con.close()
    print dump_certificate(FILETYPE_PEM, walkchain(con.get_peer_cert_chain()))
Пример #2
0
 def _dump_all_certs(self, cert_file, address):
     # This will also include intermediate certs
     context = Context(SSLv23_METHOD)
     context.set_default_verify_paths()
     client = socket.socket()
     client.connect((address, 443))
     clientSSL = Connection(context, client)
     clientSSL.set_connect_state()
     clientSSL.do_handshake()
     chains = clientSSL.get_peer_cert_chain()
     for chain in chains:
         cert_file.write(dump_certificate(FILETYPE_PEM, chain).decode())
Пример #3
0
def main():
    """
    Connect to an SNI-enabled server and request a specific hostname, specified by argv[1], of it.
    """
    if len(argv) < 2:
        print 'Usage: %s <hostname> [port]' % (argv[0], )
        return 1

    port = 443
    if len(argv) == 3:
        port = int(argv[2])

    hostname = argv[1]
    client = socket()
    #client.settimeout(2)

    #print 'Connecting...',
    stdout.flush()
    client.connect((hostname, port))
    #print 'connected', client.getpeername()

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(hostname)
    client_ssl.do_handshake()

    host = client_ssl.getpeername()
    servername = client_ssl.get_servername()
    x509 = client_ssl.get_peer_certificate()
    notAfter = datetime.strptime(x509.get_notAfter(), '%Y%m%d%H%M%SZ')
    cert_chain = client_ssl.get_peer_cert_chain()

    now = datetime.now()
    timedelta = notAfter - now

    DNS = ''
    for i in xrange(x509.get_extension_count()):
        ret = str(x509.get_extension(i))
        if re.match('^DNS:', ret):
            DNS = ret.replace('DNS:', '')

    print "servername: %s, host: %s, port: %s" % (servername, host[0], host[1])
    print "\tnotAfter: %s, remain: %s days" % (notAfter, timedelta.days)
    print "\tDNS: ", DNS
    print '\tCert Chain:'

    for i, v in enumerate(cert_chain):
        print '\t%s,i,%s' % (i, v.get_subject())
        print '\t%s,s,%s' % (i, v.get_issuer())

    client_ssl.close()
Пример #4
0
def main():
    def err_exit(ret, msg):
        ret['failed'] = True
        ret['msg'] = msg
        module.fail_json(**ret)

    module = AnsibleModule(argument_spec=dict(
        host=dict(required=True, type='str'),
        certificates=dict(required=True, type='dict'),
    ), )

    host = module.params['host']
    certificates = copy.copy(module.params['certificates'])
    split = host.split(':')
    split.reverse()
    host = split.pop()
    ret['host'] = host
    ret['port'] = None
    ret['downloaded'] = False
    ret['ansible_facts'] = dict(certificates=certificates)

    try:
        port = int(split.pop()) if split else 443
        hostport = "{}:{}".format(host, port)
        ret['port'] = port

        if host in certificates and hostport not in certificates:
            certificates[hostport] = certificates[host]

        if hostport not in certificates or certificates[hostport] is None:
            s = socket(AF_INET, SOCK_STREAM)
            ctx = Context(TLSv1_METHOD)
            con = Connection(ctx, s)
            con.connect((host, port))
            con.do_handshake()
            x509 = con.get_peer_cert_chain()[-1]
            con.shutdown()
            con.close()
            ret['downloaded'] = True
            certificates[hostport] = dump_certificate(FILETYPE_PEM, x509)
            if host not in certificates or certificates[host] is None:
                certificates[host] = certificates[hostport]

        module.exit_json(**ret)
    except Exception as e:
        msg_ = traceback.format_exc()
        module.fail_json(msg="{}: {}".format(repr(e), msg_))
Пример #5
0
def main():

    if len(argv) < 3:
        print('Usage: %s <hostname> <port>'.format(argv[0]))
        return 1

    hostname = str(argv[1])
    port = int(argv[2])

    client = socket()

    print('Connecting...')
    stdout.flush()
    client.connect((hostname, port))
    print('Connected to', client.getpeername())

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(hostname.encode('utf-8'))
    client_ssl.do_handshake()
    chain = client_ssl.get_peer_cert_chain()

    print("\n>> Certificate Chain:\n")
    i = 0
    for cert in reversed(chain):
        i += 1
        asterisks = "*" * i
        print(" [+] {:<10} {}".format(asterisks, cert.get_subject()))

    print("\n>> Certificate Details:\n")
    for cert in reversed(chain):
        pkey = cert.get_pubkey()
        print("." * 80)
        print("- [Subject]:\t\t{}".format(cert.get_subject()))
        print("- [Issuer]:\t\t{}".format(cert.get_issuer()))
        print("- [Valid from]:\t\t{}".format(cert.get_notBefore()))
        print("- [Valid until]:\t{}".format(cert.get_notAfter()))
        print("- [Has Expired]:\t{}".format(cert.has_expired()))

    print("\n")
    client_ssl.close()
    return 0
Пример #6
0
        ip = gethostbyname(hostname)
    except Exception, e:
        print e
        return None
    try:
        s = socket()
        s.connect((ip, port))
        sslcontext = Context(TLSv1_METHOD)
        sslcontext.set_timeout(30)
        c = Connection(sslcontext, s)
        c.set_connect_state()
        c.set_tlsext_host_name(hostname)
        proto_v_name = c.get_protocol_version_name()
        print "try to handshake with server: %s using %s" % (ip, proto_v_name)
        c.do_handshake()
        cert_chain = c.get_peer_cert_chain()
        c.shutdown()
        s.close()
    except Exception, e:
        print e
        return None
    else:
        return cert_chain


def read_cert_object(x509_object):
    """
	- 解析单个x509对象并返回解析结果,自定义字典
	- 参数 x509_object: OpenSSL.crypto.X509 对象
	- 返回值: 自定义字典,包含常见的x509格式信息
	"""