Traceback (most recent call last):
File "ssl-common.py", line 14, in
s = ctx.wrap_socket(s, server_hostname=dst[0])
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 363, in wrap_socket
_context=self)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 611, in init
self.do_handshake()
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 840, in do_handshake
self._sslobj.do_handshake()
socket.error: [Errno 54] Connection reset by peer
I am getting the above errors when I try to run the below script on my Mac. I have reinstalled openssl through homebrew, as well as through pip
import socket
import ssl
import OpenSSL.crypto as crypto
dst = ('1.2.3.4',443)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ret = s.connect_ex(dst)
if ret == 0 :
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
s = ctx.wrap_socket(s, server_hostname=dst[0])
# get certificate
cert_bin = s.getpeercert(True)
x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,cert_bin)
print(x509.get_subject().CN)
else :
print "socket.connect_ex returned ", ret
[Errno 54] Connection reset by peer
It seems like a problem on where you want to connect. Check your connectivity by pinging and etc.
Please do check this out: What does "connection reset by peer" mean?
Related
I'm trying to create a program that uses ssl to protect chat communications, I use OpenSsl for the certificate, the idea is to add more and more encryption and I know how I'm going to do it but when I add the ssl it gives me an error when making the connection (I don't know much about SSL)
server.py:
from socket import *
from threading import *
from ssl import *
context = SSLContext(PROTOCOL_TLSv1)
context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem")
host = '127.0.0.1'
port = int(input("Enter a port: "))
server = socket(AF_INET, SOCK_STREAM)
server.bind((host,port))
server.listen()
print(f"Server running on {host}:{port}")
clients = []
usernames = []
def broadcast(msg, _client):
for client in clients:
if client != _client:
client.send(msg)
def handle_messages(client,address):
while True:
try:
msg = client.recv(1024)
broadcast(msg, client)
except:
index = clients.index(client)
username = usernames[index]
broadcast(f"ChatBot: {username} disconnected".encode('utf-8'),client)
clients.remove(client)
usernames.remove(username)
client.close()
print(f"{username} disconnected from {str(address)}")
break
def recive_conn():
while True:
client, address = server.accept()
ssl_client = context.wrap_socket(client, server_side=True, ciphers="ADH-AES256-SHA")
ssl_client.send("#username!".encode('utf-8'))
username = ssl_client.recv(1024).decode('utf-8')
clients.append(ssl_client)
usernames.append(username)
print(f"{username} connected from {str(address)}")
msg = f'ChatBot: {username} joined the chat.'.encode('utf-8')
broadcast(msg, ssl_client)
ssl_client.send("Successful connection".encode('utf-8'))
thread = Thread(target=handle_messages, args=(ssl_client,address))
thread.start()
recive_conn()
client.py:
from socket import *
from threading import *
from playsound import playsound
from ssl import *
ACCEPTED_CHARS = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0','_','.')
NOTIFICATION = 'notification.mp3'
ctl = 0
while True:
user = input("Enter your username: ")
for i in user:
if i not in ACCEPTED_CHARS:
ctl += 1
if ctl != 0:
print('Error: invalid character(s)')
else:
break
host = input("Enter an ip: ")
while True:
try:
port = int(input("Enter a port: "))
break
except:
print("Error: Invalid port")
context = SSLContext(PROTOCOL_TLSv1)
context.verify_mode = CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem")
client = socket(AF_INET, SOCK_STREAM)
ssl_client = context.wrap_socket(client, server_hostname=host, ciphers="ADH-AES256-SHA")
ssl_client.connect((host,port))
def recive_msg():
while True:
try:
msg = ssl_client.recv(1024).decode('utf-8')
if msg == "#username!":
ssl_client.send(user.encode('utf-8'))
else:
print(msg)
playsound(NOTIFICATION)
except:
print("An unexpected error has occurred!")
ssl_client.close()
break
def write_msg():
while True:
entry = input('')
msg = f'#{user}: {entry}'
ssl_client.send(msg.encode('utf-8'))
recv_thread = Thread(target=recive_msg)
recv_thread.start()
write_thread = Thread(target=write_msg)
write_thread.start()
But at the time of connection I get the following errors
server.py:
Traceback (most recent call last):
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\server.py", line 63, in <module>
recive_conn()
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\server.py", line 47, in recive_conn
ssl_client = context.wrap_socket(client, server_side=True)
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1040, in _create
self.do_handshake()
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca (_ssl.c:1129)
client.py:
Traceback (most recent call last):
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\client.py", line 48, in <module>
ssl_client.connect((host,port))
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1333, in _real_connect
self.do_handshake()
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1129)
Well now install the certificate in the trusted certificates folder and now I get this:
server.py:
Traceback (most recent call last):
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\server.py", line 61, in <module>
recive_conn()
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\server.py", line 45, in recive_conn
ssl_client = context.wrap_socket(client, server_side=True)
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1040, in _create
self.do_handshake()
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_BAD_CERTIFICATE] sslv3 alert bad certificate (_ssl.c:1129)
client.py:
Traceback (most recent call last):
File "C:\Users\delaf\OneDrive\Escritorio\armadillo\client.py", line 47, in <module>
ssl_client.connect((host,port))
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1333, in _real_connect
self.do_handshake()
File "C:\Users\delaf\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '127.0.0.1'. (_ssl.c:1129)
I have been trying to connect to the google-geocoder api through lower-level socket module with ssl encryption. In the place API_key_here, I actually have my own API in the script.
Every time I execute the script I get the following error from ssl "ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:847)"
I am running Linux Mint and Python is 3.6.
import socket
from urllib.parse import quote_plus
import ssl
key = "API_key_here"
text = """\
GET /maps/api/geocode/json?key={}&address={}&sensor=false HTTP/1.1\r\n
Host: maps.google.com:80\r\n
User-Agent: 1-4-socket-geocoding-py-network.py\r\n
Connection: close\r\n
"""
def geocode(address):
sock = socket.socket()
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
sock_ssled = context.wrap_socket(sock, server_hostname="maps.google.com")
print(sock_ssled.version)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
sock_ssled.connect(("maps.google.com", 80))
request = text.format(key, quote_plus(address))
sock_ssled.sendall(request.encode("ascii"))
rawreply =b""
while True:
more = sock_ssled.recv(4096)
if not more:
break
rawreply += more
print (rawreply.decode("utf-8"))
if __name__ == "__main__":
geocode ('207 N. Defiance St, Archbold, OH')
below are the error output
<bound method SSLSocket.version of <ssl.SSLSocket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 0)>>
Traceback (most recent call last):
File "/home/user1/pyenv1/scripts/1-4-socket-geocoding-py-network.py", line 36, in <module>
geocode ('207 N. Defiance St, Archbold, OH')
File "/home/user1/pyenv1/scripts/1-4-socket-geocoding-py-network.py", line 23, in geocode
sock_ssled.connect(("maps.google.com", 80))
File "/usr/lib/python3.6/ssl.py", line 1109, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.6/ssl.py", line 1100, in _real_connect
self.do_handshake()
File "/usr/lib/python3.6/ssl.py", line 1077, in do_handshake
self._sslobj.do_handshake()
File "/usr/lib/python3.6/ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:847)
You should probably connect to port 443 instead of 80. 80 is for plain HTTP, 443 is for HTTPS.
Hello I would ask if i could do connection to extract some data from Tool Server.
so i making this code but i need to modify it to open this tool with username and password and extract data from My tool server.
import socket
import ssl
HOST, PORT = '10.74.159.82', 31039
def handle(conn):
conn.write(b'GET / HTTP/1.1\n')
print(conn.recv() . decode())
def main():
sock = socket.socket(socket.AF_INET)
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
conn = context.wrap_socket(sock, server_hostname=HOST)
try:
conn.connect((HOST, PORT))
handle(conn)
finally:
conn.close()
if __name__ == '__main__':
main()
RESULT
!! C:\Users\Admin\.PyCharmCE2018.1\config\venv\Scripts\python.exe!! C:/Users/Admin/.PyCharmCE2018.1/config/codestyles/Under_Building.py
Traceback (most recent call last):
File "C:/Users/Admin/.PyCharmCE2018.1/config/codestyles/Under_Building.py", line 22, in <module>
main()
File "C:/Users/Admin/.PyCharmCE2018.1/config/codestyles/Under_Building.py", line 16, in main
conn.connect((HOST, PORT))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1141, in connect
self._real_connect(addr, False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1132, in _real_connect
self.do_handshake()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1108, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)
Process finished with exit code 1
I'm Beginner so i need to learn and supporting
It's hard to see exactly, but it seems the server you're connecting to (on https://10.74.159.82:31039) is using a self-signed certificate (or its CA is, perhaps).
It's perhaps better to create or buy a proper (non-self-signed) certificate, but assuming this is a test server this is fine.
So with what you have, your best bet is to allow self-signed certs in your SSL Context (and also, not to check the hostname - that will probably fail too as you're using an IP address):
context = ssl.create_default_context()
context.check_hostname=False
context.verify_mode=ssl.CERT_NONE
# etc...
My code
I've gone over it and had a friend of mine look at it. At this point we're both stumped and would appreciate some help.
import os
import socket
import ssl
HSM = raw_input('Please enter the IP address of the machine you are connecting to.')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sslSocket = ssl.wrap_socket(sock,
keyfile="AKMClientPrivateKey.pem",
certfile="AKMClientSignedCert.pem",
ca_certs="TCASelfSignedCert.pem",
cert_reqs=ssl.CERT_REQUIRED)
sslSocket.connect(('192.168.160.128', 6000))
print "Connection is successful!"
The error I keep getting
I have all of the keys and certs I'm referencing in the same folder as my python file.
I've double checked the IP address and port.
Traceback (most recent call last):
File "connect.py", line 12, in <module>
sslSocket.connect(['192.168.160.128', 6000])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 333, in connect
self._real_connect(addr, False)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 314, in _real_connect
self.ca_certs, self.ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL
routines:SSL_CTX_use_PrivateKey_file:system lib
I'm really new to networking in general and I'm trying to set up a simple exchange between a python server and client.
This is the code for the server
import socket, ssl
def do_something(connstream, data):
print "HALLO"
def deal_with_client(connstream):
data = connstream.read()
# null data means the client is finished with us
while data:
if not do_something(connstream, data):
# we'll assume do_something returns False
# when we're finished with client
break
data = connstream.read()
# finished with client
bindsocket = socket.socket()
bindsocket.bind(('127.0.0.1', 10024))
bindsocket.listen(5)
while True:
newsocket, fromaddr = bindsocket.accept()
print "Setting up connection"
connstream = ssl.wrap_socket(newsocket,
server_side=True,
ca_certs=None,
certfile="cert.pem",
keyfile="privatekey.pem",
ssl_version=ssl.PROTOCOL_TLSv1)
try:
deal_with_client(connstream)
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
Here is the code for the client.py
import socket, ssl
clientsocket = socket.socket()
ssl_sock = ssl.wrap_socket(clientsocket,
certfile="cert.pem",
cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('127.0.0.1', 10024))
print ssl_sock.getpeername()
print ssl_sock.getpeercert()
data = ssl_sock.recv(1024)
ssl_sock.close()
print 'Received', repr(data)
I generated the "cert.pem" and the "privatekey.pem" using openssl.
Traceback (most recent call last):
File "server.py", line 30, in <module>
ssl_version=ssl.PROTOCOL_TLSv1)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 344, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 121, in __init__
self.do_handshake()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 283, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [Errno 8] _ssl.c:499: EOF occurred in violation of protocol
I was wondering if somehow who knows more could point me in the right direction. I really want to do this using SSL btw, but I would be willing to switch to TLS if that is the better approach.
It could be that the sockets are not running with a compatible ssl version, you should put a "ssl.PROTOCOL_TLSv1" compatible version in your client too (or removing it from server and use the default value too).
Googling you can find many examples of socket comunication