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
Related
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.
In python 3 Given an IP address, I want to check if a specefic port is open for TCP Connection. How can I do that?
Please Note, I don't want to wait at all. If no response was recieved immediately then just report it's closed.
This is a Python3 example I got from https://www.kite.com/python/answers/how-to-check-if-a-network-port-is-open-in-python
import socket
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8080
location = ("127.0.0.1", port)
check = a_socket.connect_ex(location)
if check == 0:
print("Port is open")
else:
print("Port is not open")
You can use simple script
#!/usr/bin/python
import socket
host = "127.0.0.1"
port = 9003
# try to connect to a bind shell
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(f"Port {port} is open")
s.close()
except socket.error:
print(f"Port {port} closed.")
Constant socket.SOCK_STREAM here response for TCP connection.
You can do something like this to check if a port is taken or if it's open:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = ("127.0.0.1", 80)
result = sock.connect_ex(location)
if result == 0:
print("Port is open")
else:
print("Port is closed")
In this, the socket.AF_INET specifies the IP address family (IPv4) and socket.SOCK_STREAM specifies the socket type (TCP).
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())
I need to be able to send a message as client to the server and get the message back from the server in my client's console.
However when I try to implement this I keep getting the error:
line 64, in <module>
s.send(message.encode('utf-8'))
OSError: [Errno 9] Bad file descriptor
My client:
import socket
HOST = 'localhost' # The server's hostname or IP address
PORT = 12000 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
while True:
message = input("write something:")
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print("Recieved from server: " + data)
My server:
import socket
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 12000 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
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