TLS handshake not completing - python

I have a client and server application with self-signed certificates. The do_handshake method is not working properly. In the client the SSL negotiation is finished successfully, but not on the server. The server says before SSL initialization all the time (using get_state_string()).
See the code.
Client
from OpenSSL import SSL, crypto
import socket
HOST = "localhost"
PORT = 8080
def verify_cb(conn, cert, errnum, depth, ok):
print(f"Got certificate: %s {cert.get_subject()}")
print(f"Issued by: {cert.get_issuer()}")
return ok
# Initialise SSL context:
ctx = SSL.Context(SSL.TLSv1_2_METHOD)
ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a server certificate
ctx.load_verify_locations("serverpath.pem")
ctx.use_privatekey_file('clientkey.pem')
ctx.use_certificate_file('clientpath.pem')
# Set up client:
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect((HOST, PORT))
sock.set_connect_state()
print(sock.get_state_string())
while True:
try:
sock.do_handshake()
break
except SSL.WantReadError:
pass
print(sock.get_state_string())
sock.write("HELLO")
# Read response:
while True:
try:
print(sock.recv(4096))
except SSL.ZeroReturnError:
break
Server
from OpenSSL import SSL, crypto
import socket
HOST = "localhost"
PORT = 8080
def verify_cb(conn, cert, errnum, depth, ok):
print(f"Got certificate: %s {cert.get_subject()}")
print(f"Issued by: {cert.get_issuer()}")
return ok
# Initialise SSL context:
ctx = SSL.Context(SSL.TLSv1_2_METHOD)
ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a client certificate
ctx.load_verify_locations("clientpath.pem")
ctx.use_privatekey_file('serverkey.pem')
ctx.use_certificate_file('serverpath.pem')
# Set up sever:
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)
print("Waiting for connections.")
#Wait for clients to connect:
(conn, address) = sock.accept()
sock.set_accept_state()
print(f"Got connection from {address}")
print(sock.get_state_string())
while True:
try:
print(sock.get_state_string())
print(conn.recv(4096))
print(sock.get_state_string())
except SSL.ZeroReturnError:
break
Please, can anyone tell me what am I doing wrong?

(conn, address) = sock.accept()
sock.set_accept_state()
print(f"Got connection from {address}")
print(sock.get_state_string())
while True:
try:
print(sock.get_state_string())
print(conn.recv(4096))
print(sock.get_state_string())
You need to operate on the accepted socket conn and not on the server socket sock. While you read from the accepted socket you print the state of the server socket instead, which does not reflect the state of the connected socket. Also, you don't need to set the accept state since you've already called accept on the SSL server socket:
(conn, address) = sock.accept()
print(f"Got connection from {address}")
print(conn.get_state_string())
while True:
try:
print(conn.get_state_string())
print(conn.recv(4096))
print(conn.get_state_string())

Related

When I connect to vps I get an error: Connection refused

I wrote in vps- console two files, that work great (test message comes from the client and is displayed by the server script).
Server.py:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
sock.bind(('localhost', 8884))
while True:
try:
client, addr = sock.accept()
except KeyboardInterrupt:
sock.close()
break
else:
client.setblocking(True)
result = client.recv(1024)
client.close()
print('Message', result.decode('utf-8'))
Clien.py:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8884))
sock.send(b'Test message!')
sock.close()
But if I use Client.py from my home computer, I get an error:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('145.148.81.8', 8884)) #ConnectionRefusedError: [Errno 111] Connection refused
sock.send(b'Test message from my house!')
sock.close()
How to fix?
your server code:
sock.bind(('localhost', 8884))
means that the server is only listening for incoming connections on loopback device.
Change that localhost to 0.0.0.0 and then the server listens on all available network devices.

Socket server keeps listening but no response is received

I have the following code, and with any valid address or port, the code keeps listening, but either doesn't receive any response or doesn't print it.
import socket, threading
bind_ip = "127.0.0.1"
bind_port = 39832
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print(f"[*] Listening on {bind_ip}: {bind_port}")
def handle_client(client_socket):
response = client_socket.recv(1024)
print(f"[*] Recieved: {response}")
client_socket.send("ACK!")
client_socket.close()
while True:
client, addr = server.accept()
print(f"[*] Accepted connection from: {addr[0]}: {addr[1]}")
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
I can't find the problem as the book I am reading uses the same code but receives a response.

Wireshark not detecting TLS connection

I want to make a TLS communication, but when I want to check it with WireShark, it said that it is a normal TCP connection that does not use TLS. It shouldn't be, due to the certificate.
client:
import socket
import ssl
hostname = 'localhost'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('certificates/ca.pem')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock = context.wrap_socket(sock, server_hostname=hostname)
ssock.connect((hostname, 8080))
print(ssock.version())
ssock.send("TLSnotWorking".encode("UTF-8"))
ssock.close()
server:
import ssl
import socket
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('certificates/server.pem', 'certificates/server.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('127.0.0.1', 8080))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
try:
while True:
conn, addr = ssock.accept()
try:
while True:
msg = conn.recv(4096)
if not len(msg):
conn.close()
break
print(msg.decode("UTF-8"))
except Exception as e:
print(e)
except KeyboardInterrupt:
conn.close()
ssock.shutdown(socket.SHUT_RDWR)
ssock.close()
wireshark can tell if it is TLS but I just used a wrong port, for example "8443" at the port you can see if there is TLS communication

ssl server and client using python - client is closing the connection due to exception

I am newbie to socket and ssl programming in python.
Current requirement is that, Client and server shares the pre-shared key so the certificate exchange,authentication and verifying is not needed in both ends.
So,during handshake mechanism, there is no need to authenticate the server from client part but the minimal check is that Cipher suites needs to be send along with random number from client is > TLS_PSK_WITH_SHA256 and will be acknowledged by server.
In this case, i have created a custom socket instead of Create_default_socket() and passed the parameters TLSv1.2,CERT_NONE and same in client side as well.
But,when the client is executed, connection is refused due to exception.
Can you point the error in below code , it would certainly help me a lot.
(For testing, i am using HOST - localhost and port - 4443 )
Server code:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
import socket, ssl
HOST = '127.0.0.1'
PORT = 4443
def handle(conn):
#print(conn.recv())
print("entered to handle case")
def main():
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 # optional
context.check_hostname = False
context.set_ciphers('TLS_PSK_WITH_NULL_SHA256')
context.verify_mode=ssl.CERT_NONE
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(5)
while True:
conn = None
try:
ssock = context.wrap_socket(sock,server_side=True,
do_handshake_on_connect=False,
suppress_ragged_eofs=False,
session=None
)
print("created wrap socket")
conn, addr = ssock.accept()
handle(conn)
except ssl.SSLError as e:
print(e)
finally:
if conn:
conn.close()
print("Executing server main fn call")
main()
Client code:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.check_hostname=False
context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 # optional
context.verify_mode =ssl.CERT_NONE
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
conn = context.wrap_socket(sock,
server_side=False,
do_handshake_on_connect=False,
suppress_ragged_eofs=False,
server_hostname=HOST)
try:
conn.connect((HOST, PORT))
#handle(conn)
except ssl.SSLError as e:
print(e)
finally:
if conn:
conn.close()
print("client is closed due to exception")
Getting Errors in server side :
if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
OSError: [WinError 10038] An operation was attempted on something that is not a socket
Error in Client side - connection is closed due to exception.

Python socket: Bad File Descriptor for simple client connection script

My script is very simple.
1.) Server listens for an HTTP connection
2.) Client establishes connection
3.) Server prints our the client's HTTP request data
When a client connects to the server and makes a browser request it triggers the Socket error "Bad File Descriptor".
I'm not sure why it does this. Can anyone help me out?
import socket
host = ''
port = 1000
def proxy(connection,client):
request = connection.recv(MAX_DATA_RECV)
print request
connection.close()
def main():
try:
# create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# associate the socket to host and port
s.bind((host, port))
# listenning
s.listen(BACKLOG)
print("Listening for connections")
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket:", message
# get the connection from client
while 1:
try:
conn, client_addr = s.accept()
print("Received connection from " + str(client_addr))
proxy(conn,client_addr)
#thread.start_new_thread(proxy, (conn,client_addr))
if s:
s.close()
except socket.error, (value,message):
print value
print message
sys.exit(1)
main()
You are closing the server socket after first client. Don't do this.
while True:
try:
conn, client_addr = s.accept()
print("Received connection from " + str(client_addr))
proxy(conn,client_addr)
except socket.error, (value,message):
print value
print message

Categories

Resources