def __init__(self, ip, port, requested_spdy_version): self.sock = networking.create_tcp_socket(ip, port, 3) self.tls_conn = tlslite.TLSConnection(self.sock) if 'auto' == requested_spdy_version: nextProtos = ['spdy/3', 'spdy/2'] elif 'spdy/2' == requested_spdy_version: nextProtos = ['spdy/2'] elif 'spdy/3' == requested_spdy_version: nextProtos = ['spdy/3'] else: raise Exception('unknown requested spdy version: %s' % requested_spdy_version) self.tls_conn.handshakeClientCert(nextProtos=nextProtos) LOGGER.info('negotiated protocol: %s' % self.tls_conn.next_proto) if 'spdy/2' == self.tls_conn.next_proto: self.spdy_version = SPDY_2 elif 'spdy/3' == self.tls_conn.next_proto: self.spdy_version = SPDY_3 else: raise Exception('not spdy') self.spdy_context = spdy.context.Context(spdy.context.CLIENT, version=self.spdy_version) self.remote_initial_window_size = 65536 self.streams = {} self.send( spdy.frames.Settings(1, { spdy.frames.INITIAL_WINDOW_SIZE: (0, LOCAL_INITIAL_WINDOW_SIZE) }))
def connect(self): conn = self._new_conn() self._prepare_conn(conn) self.sock = tlslite.TLSConnection(conn) self.sock.handshakeClientCert() # Not really, but shuts things up. self.is_verified = True
def accept(self): import tlslite while 1: conn0, addr = server.accept(self) conn = tlslite.TLSConnection(conn0) conn.ignoreAbruptClose = True conn.handshakeServer(certChain=self.chain, privateKey=self.private, **self.handshake_args) return conn, addr
def getSigFromHost(urlPath): url = urlparse.urlparse(urlPath) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((url.netloc, 443)) conn = tlslite.TLSConnection(sock) conn.handshakeClientCert() import pdb pdb.set_trace() print conn.session.serverCertChain.x509List return genHash(conn.session.serverCertChain.x509List[0])
def connect(hostname, port: int = PORT, check: str = None, min_version: Tuple[int, int] = (3, 0), max_version: Tuple[int, int] = (3, 4), cipher_names: List[str] = None, key_exchange_names: List[str] = None, anon: bool = False, scsv: bool = False)\ -> Generator[tlslite.TLSConnection, None, None]: """ Establish a SSL/TLS connection. :param hostname: Host name to connect to. :param port: Port to connect. Defaults to 443. :param check_poodle_tls: Depending on this, choose padding method. :param min_version: Minimum SSL/TLS version acceptable. (Default TLS 1.0) :param max_version: Minimum SSL/TLS version acceptable. (Default TLS 1.2) :param cipher_names: List of allowed ciphers. :param key_exchange_names: List of exchange names. :param anon: Whether to make the handshake anonymously. """ if check == 'POODLE': tlslite.recordlayer.RecordLayer.addPadding = _my_add_padding_poodle else: tlslite.recordlayer.RecordLayer.addPadding = ORIG_METHOD sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) connection = tlslite.TLSConnection(sock) connection.ignoreAbruptClose = True settings = tlslite.HandshakeSettings() settings.minVersion = min_version settings.maxVersion = max_version settings.sendFallbackSCSV = scsv if cipher_names: settings.cipherNames = cipher_names if key_exchange_names: settings.keyExchangeNames = key_exchange_names if tlslite.utils.dns_utils.is_valid_hostname(hostname): if anon: connection.handshakeClientAnonymous(settings=settings, serverName=hostname) else: connection.handshakeClientCert(settings=settings, serverName=hostname) else: if anon: connection.handshakeClientAnonymous(settings=settings) else: connection.handshakeClientCert(settings=settings) yield connection connection.close()
def starttls(self, *future_cert_params): import tlslite self.exit_recv_thread = True reply = self.send_message(encode_starttls()) if reply[2] == 0: conn = tlslite.TLSConnection(self.sock) # does ldap allow client-cert authentication? conn.handshakeClientCert() self.osock = self.sock self.sock = conn # restart recv thread (maybe) with TLS socket wrapper self.exit_recv_thread = False self.recv_thread_ob = coro.spawn(self.recv_thread) return reply
def allows_modified_mac(site: str, port: int = PORT) -> bool: """ Check if site allows messages with modified MAC. :param site: Address to connect to. :param port: If necessary, specify port to connect to. """ orig_method = \ copy.deepcopy(tlslite.tlsconnection.TLSConnection._sendFinished) tlslite.tlsconnection.TLSConnection._sendFinished = _my_send_finished result = False failed_bits = list() for mask_bit in range(0, 96): mask = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) mask_index = int((mask_bit - (mask_bit % 8)) / 8) mask[mask_index] = (0x80 >> (mask_bit % 8)) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((site, port)) tls = tlslite.TLSConnection(sock) tls.macTweak = bytearray(mask) tls.handshakeClientCert() tls.send(b"GET / HTTP/1.0\n\n\n") tls.read() except (tlslite.TLSRemoteAlert, tlslite.TLSAbruptCloseError, tlslite.errors.TLSLocalAlert, socket.error): continue else: result = True failed_bits.append(mask_bit) tlslite.tlsconnection.TLSConnection._sendFinished = orig_method if result: show_open('Server allowed messages with modified MAC', details=dict(server=site, port=port, failed_bits=", ".join( [str(x) for x in failed_bits]))) else: show_close('Server rejected messages with modified MAC', details=dict(server=site, port=port)) return result
sock.listen() sock_list.append(sock) while True: with lib.spinner.Spinner(" Listening on port {}".format(arg.port)): client, addr = sock.accept() sock_list.append(client) print("[*] Client connected: {}:{}".format(addr[0], addr[1])) # Checker object to always reject the client's certificate (compares fingerprint to 0) # Inner try block to catch the auth exception thrown by the library try: try: checker = tlslite.Checker(x509Fingerprint="0") conn = tlslite.TLSConnection(client) conn.handshakeServer(certChain=certChain, privateKey=privateKey, reqCert=True, checker=checker) except tlslite.TLSFingerprintError: pass # Stores all the decoded bytes of the file file_bytes = bytearray() file_name = str(conn.session.clientCertChain.getFingerprint()) # The first certificate has an additional "DNS:" entry with the file extension, so we load it separately first_cert = conn.session.clientCertChain.x509List.pop(0) first_parsed = cryptography.x509.load_der_x509_certificate( first_cert.bytes,
order = ecdsa.SECP256k1.generator.order() point = vk.pubkey.point x = (b'\x1c\x02', b'\x1c\x03')[point.y() & 1] + ecdsa.util.number_to_string( point.x(), order) y = SHA256CHK(x) #checksum bytes x += y #encode node key into standard base58 notation using the ripple alphabet b58pk = base58r.b58encode(x).decode('utf-8') #open the socket sock = socket(AF_INET, SOCK_STREAM) sock.connect((server, port)) #attach the tls class / this tls lib has been modified to expose the finished messages for use in the rippled cookie connection = tlslite.TLSConnection(sock) connection.handshakeClientCert() #extract and calculate message hashes cookie1 = SHA512(connection.remoteLastMessage()) cookie2 = SHA512(connection.localLastMessage()) cookie = SHA512H(XOR(cookie1, cookie2)) #the cookie must be signed with our private key sig = base64.b64encode( sk.sign_digest(cookie, sigencode=ecdsa.util.sigencode_der)).decode('utf-8') #finally construct the GET request which will allow us to say hello to the rippled server request = 'GET / HTTP/1.1\r\n' request += 'User-Agent: rippled-1.3.1\r\n' request += 'Upgrade: RTXP/1.2\r\n'
def _setup_https_tunnel(self): sock = self.sock host = self._tunnel_host port = self._tunnel_port try: lines = [] lines.append('CONNECT %s:%d HTTP/1.1' % (host, port)) lines.append('Host: %s:%d' % (host, port)) if self._tunnel_headers: for item in self._tunnel_headers.items(): lines.append('%s: %s' % item) data = '\r\n'.join(lines) + '\r\n\r\n' sock.sendall(data.encode()) data = b'' code = 0 pos = -1 while True: s = sock.recv(4096) if not s: if code == 0: raise SocketError("Tunnel connection failed: %r" % data) break data += s if code == 0 and b'\r\n' in data: version, code, message = data.split(b' ', 2) if code != b'200': sock.close() raise SocketError("Tunnel connection failed: %s %s" % (code, message.strip())) pos = data.find(b'\r\n\r\n') if pos > 0: break tls_conn = tlslite.TLSConnection(sock) try: tls_conn.handshakeClientCert(serverName=host) except Exception: sock.close() raise try: ssl.match_hostname(tlslite_getpeercert(tls_conn), host) except Exception: tls_conn.close() raise except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) # patch fileno, # let urllib3.util.connection.is_connection_dropped work as expected # tls_conn.fileno = partial(self._origin_sock.fileno) # here we always got fileno = -1 tls_conn.fileno = partial(sock.fileno) # patch getpeercert tls_conn.getpeercert = partial(tlslite_getpeercert, tls_conn) self.sock = tls_conn