Ejemplo n.º 1
0
def testPFSCipher(host,port,cipher):
	try:
		
		# Construct the socket
		client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
		client.settimeout(10)
		client.connect((host, port))	
		
		# Define the method as serverpreferred and use the Cipher from the test
		contextToUse = Context(pfsCipherList[cipher])
		contextToUse.set_cipher_list(cipher) 

		# Estabilish a SSL connection using the server's preferred connection
		client_ssl = Connection(contextToUse, client)
		client_ssl.set_connect_state()
		client_ssl.set_tlsext_host_name(host)
		
		# Try to perform an SSL handshake
		client_ssl.do_handshake()

		# Close the connection
		client_ssl.close()
		client.close()
		return True 
	except openSSLError as e: # Server may be down or avoiding SSL connection
		return False
	except ValueError as e: # Not configured or not allowed
		return False
	pass
Ejemplo n.º 2
0
def start(keystore, keystorealias, keypass, keystorepassphrase, hostandport,
          timeout):
    verify(keystore, keystorealias, keypass, keystorepassphrase, hostandport)
    sslContext = getOpensslContext(keystore, keystorealias, keypass,
                                   keystorepassphrase)
    socket = socket_any_family()
    socket.settimeout(timeout)
    hostandport = hostandport.split(":", 2)
    socket.connect((hostandport[0], int(hostandport[1])))
    sslConnection = Connection(sslContext, socket)
    sslConnection.set_connect_state()
    sslConnection.set_tlsext_host_name(hostandport[0].encode('utf-8'))
    while True:
        try:
            sslConnection.do_handshake()
        except OpenSSL.SSL.WantReadError:
            rd, _, _ = select.select([socket], [], [], socket.gettimeout())
            if not rd:
                raise timeout('select timed out')
            continue
        except OpenSSL.SSL.Error as e:
            raise ssl.SSLError('bad handshake: %r' % e)
        break
    sslContext.set_timeout(timeout)
    sslConnection.send(b"GET / HTTP/1.0\r\n\r\n")
    socket.recv(1024)
def _openssl_connect(hostname):
    client = socket()
    client.connect((hostname, 443))
    client_ssl = Connection(Context(SSLv23_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(hostname.encode('utf-8'))
    client_ssl.do_handshake()
    return client_ssl
Ejemplo n.º 4
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()))
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
def testWeakCipher(host,port,protocolList):
	# Create a list to put all analysed data
	protoDataList = []

	# Test the size of the cipher for each protocol avaiable  and get the Cipher Suite
	for proto in protocolList:
		try:
			# Construct the socket
			client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
			client.connect((host, port))	
			
			# Estabilish a SSL connection
			client_ssl = Connection(Context(methods[proto]), client)
			client_ssl.set_connect_state()
			client_ssl.set_tlsext_host_name(host)
			
			# Try to perform an SSL handshake
			client_ssl.do_handshake()

			# Obtain the name of the protocol being used
			protoName = (client_ssl.get_protocol_version_name())

			# Obtain the size of the cipher being used by the protocol
			bitSize = (client_ssl.get_cipher_bits())

			# Obtain the Cipher Suite
			suite = client_ssl.get_cipher_name()

			# Create a compiled data
			data = (protoName,bitSize,suite)
			
			# Put the data obtained on the list
			protoDataList.append(data)

			# Close the connection
			client_ssl.close()
			client.close()
		except openSSLError as e: # Server may be down or avoiding SSL connection
			print _('Servidor nao esta respondendo')
			return
		except ValueError as e: # Not configured or not allowed
			print _('Servidor nao esta configurado')
			return

	# Print the results
	print bcolors.BOLD + _("Protocolo\tTamanho da Cifra\tCifra") + bcolors.ENDC
	for protoData in protoDataList:
		print protoData[0] + '\t\t' + str(protoData[1]) + ' bits' + ( '(OK)' if (protoData[1] >=128) else _('(FRACA)')) + '\the\t' + str(protoData[2])
Ejemplo n.º 7
0
    def verify_context_info_cb(
        self, ssl_connection: SSL.Connection, where: int
    ) -> None:
        if where & SSL.SSL_CB_HANDSHAKE_START and not self._is_ip_address:
            ssl_connection.set_tlsext_host_name(self._hostnameBytes)

        if where & SSL.SSL_CB_HANDSHAKE_DONE and self._verify_certs:
            try:
                if self._is_ip_address:
                    verify_ip_address(ssl_connection, self._hostnameASCII)
                else:
                    verify_hostname(ssl_connection, self._hostnameASCII)
            except VerificationError:
                f = Failure()
                tls_protocol = ssl_connection.get_app_data()
                tls_protocol.failVerification(f)
Ejemplo n.º 8
0
def identifyProtocol(host,port):
	# Create a list to put all analysed data
	protoDataList = []
	try:
		# Construct the socket
		client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
		client.connect((host, port))	
		
		# Estabilish a SSL connection using the server's preferred connection
		client_ssl = Connection(Context(SSLv23_METHOD), client)
		client_ssl.set_connect_state()
		client_ssl.set_tlsext_host_name(host)
		
		# Try to perform an SSL handshake
		client_ssl.do_handshake()

		# Obtain the name of the protocol being used
		protoName = (client_ssl.get_protocol_version_name())

		# Obtain the size of the cipher being used by the protocol
		bitSize = (client_ssl.get_cipher_bits())

		# Obtain the Cipher Suite
		suite = client_ssl.get_cipher_name()

		# Create a compiled data
		data = (protoName,bitSize,suite)
		
		# Put the data obtained on the list
		protoDataList.append(data)

		# Close the connection
		client_ssl.close()
		client.close()

		# Shpw the data
		print _('Preferido: ') + str(protoName) + _('\nCifra: ') + str(suite) + _('\nTamanho em bits: ') + str(bitSize)
		
		# Return the protocol method used by pyOpenSSL
		return methodName[protoName]
	except openSSLError as e: # Server may be down or avoiding SSL connection
		print _('\nNao foi possivel identificar o protocolo padrao\n')
		return 0
	except ValueError as e: # Not configured or not allowed
		print _('\nNao foi possivel identificar o protocolo padrao\n')
		return 0
Ejemplo n.º 9
0
def get_certificate(hostname, port=443):
    """
    Return TLS certificate (f.i. for https or smtps)
    """

    client = socket()
    client.connect((hostname, port))

    client_ssl = Connection(Context(TLSv1_2_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(hostname.encode("ascii"))  # SNI
    client_ssl.do_handshake()

    cert = client_ssl.get_peer_certificate()

    client_ssl.close()

    return cert
Ejemplo n.º 10
0
def get_ssl(url):
    print(Fore.RED+"[+] ssl certificate:"+Fore.GREEN)
    first_try = re.findall(r":([0-9]+)", str(url))
    if len(first_try) != 0:
        for i in range(len(first_try)):
            port = ''.join(first_try[i])
    else:
        port = int('443')       
    second_try = re.findall(r"/([0-9a-zA-Z\.%&#]+)", str(url))
    if len(second_try) != 0:
        for i in range(len(second_try)):
            host = ''.join(second_try[i])         
    try:
        try:
            ssl_connection_setting = Context(SSLv3_METHOD)
        except ValueError:
            ssl_connection_setting = Context(TLSv1_2_METHOD)
        ssl_connection_setting.set_timeout(5)
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((host, int(port)))
            c = Connection(ssl_connection_setting, s)
            c.set_tlsext_host_name(str.encode(host))
            c.set_connect_state()
            c.do_handshake()
            cert = c.get_peer_certificate()
            print(Fore.RED+"    --> "+Fore.GREEN+"Is Expired: ", cert.has_expired())
            print(Fore.RED+"    --> "+Fore.GREEN+"Issuer: ", cert.get_issuer())
            subject_list = cert.get_subject().get_components()
            cert_byte_arr_decoded = {}
            for item in subject_list:
                cert_byte_arr_decoded.update({item[0].decode('utf-8'): item[1].decode('utf-8')})
            if len(cert_byte_arr_decoded) > 0:
                print(Fore.RED+"    --> "+Fore.GREEN+"Subject: ", cert_byte_arr_decoded)
            if cert_byte_arr_decoded["CN"]:
                print(Fore.RED+"    --> "+Fore.GREEN+"Common Name: ", cert_byte_arr_decoded["CN"])
            end_date = datetime.strptime(str(cert.get_notAfter().decode('utf-8')), "%Y%m%d%H%M%SZ")
            print(Fore.RED+"    --> "+Fore.GREEN+"Not After (UTC Time): ", end_date)
            diff = end_date - datetime.now()
            print(Fore.RED+"    --> "+Fore.GREEN+'Summary: "{}" SSL certificate expires on {} i.e. {} days.'.format(host, end_date, diff.days))
            c.shutdown()
            s.close()
    except:
        print(Fore.RED+"    --> "+Fore.GREEN+"Not found")
        pass 
Ejemplo n.º 11
0
class OpenSSLSNI(object):
    """This class implements the functionality of obtaining certificates secure connection using
        apache TLS Extension Server Name Indication (SNI)
    """
    def connection(func):
        def wrapped(self):
            self._connect()
            try:
                return func(self)
            finally:
                self._close()
        return wrapped

    def __init__(self, host, port):
        #Set host name
        self._host = str(host).split('//')[-1].split(':')[0]
        #Set port
        self._port = int(port) if str(port).isdigit() else 443

    def _connect(self):
        """This method implements the functionality of establishing a secure connection using TLS Extension"""
        self._socket_client = socket()
        self._socket_client.connect((self._host, self._port))
        self._ssl_client = Connection(Context(TLSv1_METHOD), self._socket_client)
        self._ssl_client.set_connect_state()
        self._ssl_client.set_tlsext_host_name(self._host)
        self._ssl_client.do_handshake()

    def _close(self):
        """This method implements the functional termination created connection"""
        self._ssl_client.close()
        del self._socket_client

    @property
    @connection
    def serial_number(self):
        """Returns  certificates serial number"""
        return self._ssl_client.get_peer_certificate().get_serial_number()

    @property
    @connection
    def certificate(self):
        """Returns  certificate"""
        return OpenSSL.crypto.dump_certificate(FILETYPE_PEM, self._ssl_client.get_peer_certificate())
Ejemplo n.º 12
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
Ejemplo n.º 13
0
 def netflix_openssl_test_retry(ip):
     client = socket()
     
     print 'Connecting...',
     stdout.flush()
     client.connect((ip, 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()
     cert = client_ssl.get_peer_certificate().get_subject()
     cn = [comp for comp in cert.get_components() if comp[0] in ['CN']]
     client_ssl.close()
     print cn
     if hostname in cn[0][1]:
         return True
     else:
         return False
Ejemplo n.º 14
0
    def netflix_openssl_test_retry(ip):
        client = socket()

        print 'Connecting...',
        stdout.flush()
        client.connect((ip, 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()
        cert = client_ssl.get_peer_certificate().get_subject()
        cn = [comp for comp in cert.get_components() if comp[0] in ['CN']]
        client_ssl.close()
        print cn
        if hostname in cn[0][1]:
            return True
        else:
            return False
Ejemplo n.º 15
0
    def _validate_certificate_hostname_pyopenssl(self):
      """ Use pyOpenSSL check if the host's certifcate matches the hostname.

      Python < 2.7.9 is not able to provide a server hostname for SNI, so this
      is a fallback that opens an additional connection if the initial
      validation failed.

      Returns:
        bool: Whether or not the hostname is valid on the certificate.
      """
      client = socket.socket()
      client.connect((self.host, self.port))
      client_ssl = Connection(Context(TLSv1_METHOD), client)
      client_ssl.set_connect_state()
      client_ssl.set_tlsext_host_name(self.host)
      client_ssl.do_handshake()
      cert = client_ssl.get_peer_certificate()
      client_ssl.close()

      common_name = cert.get_subject().commonName
      return self._cert_host_matches_hostname(common_name, self.host)
Ejemplo n.º 16
0
 def domain_ssl_connect(self, domain):            
     logging.basicConfig(filename=self.basedir+'/output/log/get_cert_from_domain.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
     try:
         sslcontext = Context(TLSv1_METHOD)
         sslcontext.set_timeout(30)
         s = socket()
         s.connect((domain, 443))
         c = Connection(sslcontext, s)
         c.set_connect_state()
         c.set_tlsext_host_name(domain.encode('utf-8'))
         logging.info("try to establish handshake with %s..." % domain)
         c.do_handshake()
         cert = c.get_peer_certificate()
         logging.info("got certificate!")
         c.shutdown()
         s.close()
         return cert
     except Exception as e:
         logging.info(e)
         logging.info("fail to connect to port 443 with %s" % domain)
         return None
Ejemplo n.º 17
0
        def _validate_certificate_hostname_pyopenssl(self):
            """ Use pyOpenSSL check if the host's certifcate matches the hostname.

      Python < 2.7.9 is not able to provide a server hostname for SNI, so this
      is a fallback that opens an additional connection if the initial
      validation failed.

      Returns:
        bool: Whether or not the hostname is valid on the certificate.
      """
            client = socket.socket()
            client.connect((self.host, self.port))
            client_ssl = Connection(Context(TLSv1_METHOD), client)
            client_ssl.set_connect_state()
            client_ssl.set_tlsext_host_name(self.host)
            client_ssl.do_handshake()
            cert = client_ssl.get_peer_certificate()
            client_ssl.close()

            common_name = cert.get_subject().commonName
            return self._cert_host_matches_hostname(common_name, self.host)
Ejemplo n.º 18
0
def check_cerificate_invalidtime(domain, port=443):
    from datetime import datetime
    from OpenSSL.SSL import TLSv1_METHOD, Context, Connection
    import socket
    client = socket.socket()
    try:
        client.connect((domain, port))
        ssl = Connection(Context(TLSv1_METHOD), client)
        ssl.set_connect_state()
        ssl.set_tlsext_host_name(domain.encode('utf-8'))
        ssl.do_handshake()
        cerificate = ssl.get_peer_certificate()

        invalid = cerificate.get_notAfter().decode()[0:-1]
        invalidtime = datetime.strptime(invalid, '%Y%m%d%H%M%S')
        diff_day = invalidtime - datetime.now()
        return True, {"invaliddate": invalidtime, "invalidday": diff_day.days}
    except Exception as e:
        return False, e.args
    finally:
        client.close()
        pass
Ejemplo n.º 19
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>' % (argv[0],)
        return 1

    client = socket()

    print 'Connecting...',
    stdout.flush()
    client.connect(('127.0.0.1', 8443))
    print 'connected', client.getpeername()

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(argv[1])
    client_ssl.do_handshake()
    print 'Server subject is', client_ssl.get_peer_certificate().get_subject()
    client_ssl.close()
Ejemplo n.º 20
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>' % (argv[0], )
        return 1

    client = socket()

    print 'Connecting...',
    stdout.flush()
    client.connect(('127.0.0.1', 8443))
    print 'connected', client.getpeername()

    client_ssl = Connection(Context(TLSv1_METHOD), client)
    client_ssl.set_connect_state()
    client_ssl.set_tlsext_host_name(argv[1])
    client_ssl.do_handshake()
    print 'Server subject is', client_ssl.get_peer_certificate().get_subject()
    client_ssl.close()
Ejemplo n.º 21
0
def verifyOpenProtocol(host,port,proto):
	try:
		# Construct the socket
		client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
		client.connect((host, port))	
		
		# Estabilish a SSL connection
		client_ssl = Connection(Context(proto), client)
		client_ssl.set_connect_state()
		client_ssl.set_tlsext_host_name(host)
		
		# Try to perform an SSL handshake
		client_ssl.do_handshake()
		
		# Close the connection
		client_ssl.close()
		client.close()
	except openSSLError as e: # Server not configured to use
		return False
	except ValueError as e: # Not present
		return False
	
	# Success
	return True		
Ejemplo n.º 22
0
def checkCertificate(url_base, url_rest, req_headers={}, request_type='GET'):
    connection = http.client.HTTPSConnection(url_base, timeout=1)
    certificate_is_valid = None
    certificate_host_names = None
    try:
        client = socket.socket()
        client.connect((url_base, 443))
        client_ssl = Connection(Context(TLSv1_2_METHOD), client)
        client_ssl.set_connect_state()
        client_ssl.set_tlsext_host_name(url_base.encode('UTF-8'))
        client_ssl.do_handshake()
        certificate_host_names = get_certificate_hosts(
            client_ssl.get_peer_certificate())
    except:
        pass
    finally:
        if client:
            client.close()
    try:
        connection.request(request_type, url_rest, headers=req_headers)
        certificate_is_valid = True
    except:
        certificate_is_valid = False
    return (certificate_is_valid, certificate_host_names)
Ejemplo n.º 23
0
                return item[1]
        return ''

    def __read_cert(self, domain_str):
        sslcontext = Context(TLSv1_METHOD)
        sslcontext.set_timeout(30)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print domain_str
        try:
            s.connect((domain_str, 443))
        except Exception, e:
            print e
            return ''
        try:
            c = Connection(sslcontext, s)
            c.set_tlsext_host_name(str(domain_str))
            c.set_connect_state()
            c.do_handshake()
            cert = c.get_peer_certificate()
            issuer = cert.get_issuer().get_components()
            result = self.__get_CN(issuer), self.__get_CN(
                cert.get_subject().get_components()), cert.get_notAfter()
            c.shutdown()
        except Exception, e:
            print e
            return ''
        s.close()
        return result

    def __get_ssl_info(self, domain_str):
        if self.__test_domain_conn(domain_str) > 0:
Ejemplo n.º 24
0
        port = int(port[1:len(port)])
    from socket import socket, gethostbyname
    from OpenSSL.SSL import Connection, Context, TLSv1_METHOD, WantReadError, VERIFY_PEER
    try:
        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):
    """
Ejemplo n.º 25
0
 
 print '\nChecking DNS for CAA records . . .\n'
 answers = dns.resolver.query(domain, 'CAA')
 print 'The following records were found:\n'
 for rdata in answers:
     print domain, 'in CAA', rdata.flags, rdata.value
 print '\nNow checking certificate . . . \n'
 print 'Using server name:', host, 'on port', port, 'for SNI ...'
 client = socket()
 stdout.flush()
 client.connect(('{0}'.format(host), int(port)))
 print 'Connected to', client.getpeername(), '\n'
 
 client_ssl = Connection(Context(TLSv1_METHOD), client)
 client_ssl.set_connect_state()
 client_ssl.set_tlsext_host_name(host)
 client_ssl.do_handshake()
 issuer = client_ssl.get_peer_certificate().get_issuer()
 issr = str(issuer)
 issr = issr.strip('<>')
 issr = issr.replace('X509Name object', 'Certificate Information: ')
 issr = issr.replace('C=', 'Country: ')
 issr = issr.replace('O=', 'Organization: ')
 issr = issr.replace('CN=', 'Common Name: ')
 issr = issr.split('/')
 for issr in issr:
     print issr
 print '\n'
 client_ssl.close()
 exit()
Ejemplo n.º 26
0
        def do_POST(self):
            content_len = int(self.headers.get('Content-Length', 0))
            post_body = self.rfile.read(content_len)

            try:
                json_body = json.loads(post_body)
                request_type = 'GET'

                if 'type' in json_body:
                    request_type = json_body['type']

                if 'url' not in json_body or (request_type == 'POST'
                                              and 'content' not in json_body):
                    self.send_result(200, prepare_output('invalid json'))

                request_url = json_body['url']
                request_headers = json_body[
                    'headers'] if 'headers' in json_body else dict()
                request_content = json_body[
                    'content'] if request_type == 'POST' else None
                request_timeout = json_body[
                    'timeout'] if 'timeout' in json_body else 1

                request_headers = {
                    k.lower(): v
                    for k, v in request_headers.items()
                }
                if 'content-type' not in request_headers:
                    request_headers['content-type'] = 'text/plain'

                new_request = request.Request(
                    url=request_url,
                    data=bytes(request_content, 'UTF-8')
                    if request_content else None,
                    headers=request_headers,
                    method=request_type)

                # TU ZACINA GRCKA SORRY.
                # cert_raw = ssl.get_server_certificate(('google.com', 443))
                # cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_raw)
                # print(dict(cert.get_subject().get_components()))

                certificate_common_names = None
                certificate_is_valid = None
                if request_url.startswith('https://'):
                    client = None
                    try:
                        client = socket.socket()
                        # print('Connecting...')
                        client.connect(
                            (parse.urlparse(request_url).netloc, 443))
                        client_ssl = Connection(Context(TLSv1_2_METHOD),
                                                client)
                        client_ssl.set_connect_state()
                        client_ssl.set_tlsext_host_name(
                            parse.urlparse(request_url).netloc.encode('UTF-8'))
                        client_ssl.do_handshake()
                        # print('Server subject is', dict(client_ssl.get_peer_certificate().get_subject().get_components()))
                        certificate_common_names = get_certificate_san(
                            client_ssl.get_peer_certificate())
                    except:
                        pass
                    finally:
                        if client:
                            client.close()

                    try:
                        with request.urlopen(
                                new_request,
                                timeout=request_timeout) as response:
                            certificate_is_valid = True
                    except:
                        certificate_is_valid = False
                # TU KONCI GRCKA.

                try:
                    ctx = ssl.create_default_context()
                    ctx.check_hostname = False
                    ctx.verify_mode = ssl.CERT_NONE

                    with request.urlopen(new_request,
                                         timeout=request_timeout,
                                         context=ctx) as response:
                        res_content = response.read().decode('UTF-8')
                        output = prepare_output(response.status,
                                                response.getheaders(),
                                                res_content,
                                                certificate_is_valid,
                                                certificate_common_names)

                        self.send_result(200, output)
                except HTTPError as err:
                    self.send_result(200, prepare_output(err.code, None, None))
                except:
                    return self.send_result(
                        200, prepare_output('timeout', None, None))

            except ValueError:
                # import traceback
                # traceback.print_exc()
                self.send_result(200, prepare_output('invalid json'))
Ejemplo n.º 27
0
        def do_GET(self):
            get_params = parse.urlparse(self.path).query

            get_url = input_target_url
            if get_params:
                get_url = '%s?%s' % (get_url, get_params)

            new_headers = dict(self.headers)
            if 'Host' in new_headers:
                del new_headers['Host']

            new_request = request.Request(url=get_url,
                                          data=None,
                                          headers=new_headers,
                                          method='GET')

            # TU ZACINA GRCKA SORRY.
            certificate_common_names = None
            certificate_is_valid = None
            if get_url.startswith('https://'):
                client = None
                try:
                    client = socket.socket()
                    # print('Connecting...')
                    client.connect((parse.urlparse(get_url).netloc, 443))
                    client_ssl = Connection(Context(TLSv1_2_METHOD), client)
                    client_ssl.set_connect_state()
                    client_ssl.set_tlsext_host_name(
                        parse.urlparse(get_url).netloc.encode('UTF-8'))
                    client_ssl.do_handshake()
                    # print('Server subject is', dict(client_ssl.get_peer_certificate().get_subject().get_components()))
                    certificate_common_names = get_certificate_san(
                        client_ssl.get_peer_certificate())
                except:
                    pass
                finally:
                    if client:
                        client.close()

                try:
                    with request.urlopen(new_request, timeout=1) as response:
                        certificate_is_valid = True
                except:
                    certificate_is_valid = False
            # TU KONCI GRCKA.

            try:
                ctx = ssl.create_default_context()
                ctx.check_hostname = False
                ctx.verify_mode = ssl.CERT_NONE

                with request.urlopen(new_request, timeout=1,
                                     context=ctx) as response:
                    res_content = response.read().decode('UTF-8')
                    output = prepare_output(response.status,
                                            response.getheaders(), res_content,
                                            certificate_is_valid,
                                            certificate_common_names)

                    self.send_result(200, output)
            except HTTPError as err:
                self.send_result(200, prepare_output(err.code, None, None))
            except:
                return self.send_result(200,
                                        prepare_output('timeout', None, None))
Ejemplo n.º 28
0
    try:
        soc = socket.socket()
        soc.connect((host, int(port)))

    except socket.error, err:
        log(("Socket Error Encountered : %s" % err), sink)
        exit(1)
    pass

    # --- Connect to remote host

    soc_context = Context(SSLv23_METHOD)
    soc_ssl = Connection(soc_context, soc)
    soc_ssl.set_connect_state()
    soc_ssl.set_tlsext_host_name(argv[1])

    try:
        soc_ssl.do_handshake()
    except OpenSSL.SSL.Error, msg:
        print " \n\n Unable to complet the SSL Handshake %s" % msg
        exit(1)
    pass

    #--- Get the remote host name

    rhost = soc.getpeername()

    log(("\nRemote Host name :" + host), sink)
    log(("\nRemote Host IPv4 :" + rhost[0]), sink)
    log(("\nRemote Host Port :" + str(rhost[1])), sink)
Ejemplo n.º 29
0
 def _identityVerifyingInfoCallback(self, connection: SSL.Connection,
                                    where: int, ret: int) -> None:
     # Literal IPv4 and IPv6 addresses are not permitted
     # as host names according to the RFCs
     if where & SSL.SSL_CB_HANDSHAKE_START and self._sendSNI:
         connection.set_tlsext_host_name(self._hostnameBytes)
Ejemplo n.º 30
0
    try:
        soc = socket.socket()
        soc.connect((host, int(port)))

    except socket.error, err:
        log(("Socket Error Encountered : %s" % err), sink)
        exit(1)
    pass

    # --- Connect to remote host

    soc_context = Context(SSLv23_METHOD)
    soc_ssl = Connection(soc_context, soc)
    soc_ssl.set_connect_state()
    soc_ssl.set_tlsext_host_name(argv[1])

    try:
        soc_ssl.do_handshake()
    except OpenSSL.SSL.Error, msg:
        print " \n\n Unable to complet the SSL Handshake %s" % msg
        exit(1)
    pass

    #--- Get the remote host name

    rhost = soc.getpeername()

    log(("\nRemote Host name :" + host), sink)
    log(("\nRemote Host IPv4 :" + rhost[0]), sink)
    log(("\nRemote Host Port :" + str(rhost[1])), sink)