python wrong number ssl - python

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.

Related

SSL Handshake issue with asyncio motor driver Mongodb Python

I am trying to connect Mongodb using AWS lambda but results SSL handshake error. I am using motor and Python 3.8 . There is successful connection to database most of time. When I look AWS cloud watchlogs , I found a error connecting to database in some logs.
This is code for connecting database.
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient
from .mongodb import db
import certifi
from app.utility.config import MONGODB_URL
async def connect_to_mongo(app: FastAPI) -> None
db.client = AsyncIOMotorClient(str(MONGODB_URL),tls = True, tlsCAFile= certifi.where(),
maxPoolSize=MAX_CONNECTIONS_COUNT,
minPoolSize=MIN_CONNECTIONS_COUNT,
waitQueueMultiple = MAX_DB_THREADS_WAIT_COUNT,
waitQueueTimeoutMS = MAX_DB_THREAD_QUEUE_TIMEOUT_COUNT )
async def close_mongo_connection(app: FastAPI) -> None:
db.client.close()
Traceback
File "/var/task/pymongo/pool.py", line 1040, in _configured_socket
sock = ssl_context.wrap_socket(sock, server_hostname=host)
File "/var/lang/lib/python3.8/ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "/var/lang/lib/python3.8/ssl.py", line 1040, in _create
self.do_handshake()
File "/var/lang/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1114: The handshake operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/var/task/pymongo/mongo_client.py", line 1869, in _process_periodic_tasks
self._topology.update_pool(self.__all_credentials)
File "/var/task/pymongo/topology.py", line 456, in update_pool
server.pool.remove_stale_sockets(generation, all_credentials)
File "/var/task/pymongo/pool.py", line 1252, in remove_stale_sockets
sock_info = self.connect(all_credentials)
File "/var/task/pymongo/pool.py", line 1280, in connect
sock = _configured_socket(self.address, self.opts)
File "/var/task/pymongo/pool.py", line 1053, in _configured_socket
_raise_connection_failure(address, exc, "SSL handshake failed: ")
File "/var/task/pymongo/pool.py", line 238, in _raise_connection_failure
raise NetworkTimeout(msg)
pymongo.errors.NetworkTimeout: SSL handshake failed: cluster0-***-******mongodb.net:******: _ssl.c:1114: The handshake operation timed out

"[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate" and "[SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca"

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)

smpt lib multiple module error with a macbookpro

My code I have copied and pasted from real python.com
import smtplib, ssl
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "sender#gmail.com"
receiver_email = "reciever#gmail.com"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
this somehow simple code to send an email produces a large list of errors which i cant track down.It seems to be an error with the module but im unaware how to resolve or trouble shoot these errors. I cant find any information on it as well; ive been looking for the past hour?
Traceback (most recent call last):
File "/Users/kaiwhitehouse/Documents/RetailEmailapp/lhbhbhlbhjbhjlbjljklhkjh.py", line 16, in <module>
server.starttls(context=context)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 774, in starttls
self.sock = context.wrap_socket(self.sock,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1040, in _create
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)
Im running on mac os with a 2020 macbook pro but does anyone know the solution to my problem?

How i could to make SSl Connection server using username, password by python?

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...

Getting file errors after creating python script titled ssl.py

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?

Categories