XMPP SSL Handshake failed - python

I am having difficulty in establishing a connection with XMPP (Prosody) . But if I use PSI it works fine and request for your suggestions.
Here is the code snippet of my python :
client = xmpp.Client(host)
client.connect(server=(host,port))
client.auth(username, passwd,resource='', sasl=1)
client.sendInitPresence()
In debug mode :
DEBUG: dispatcher warn Registering protocol "error" as <class 'xmpp.protocol.Protocol'>(http://etherx.jabber.org/streams)
DEBUG: socket sent <?xml version='1.0'?><stream:stream xmlns="jabber:client" to="localhost" version="1.0" xmlns:stream="http://etherx.jabber.org/streams" >
DEBUG: socket error Socket error while receiving data
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/xmpp/transports.py", line 161, in receive
try: received = self._recv(BUFLEN)
error: [Errno 104] Connection reset by peer
DEBUG: client stop Disconnect detected
DEBUG: socket error Socket operation failed
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/xmpp/transports.py", line 161, in receive
try: received = self._recv(BUFLEN)
error: [Errno 104] Connection reset by peer
DEBUG: socket error Socket error while receiving data
DEBUG: client stop Disconnect detected
**Prosody logs :**
Oct 20 23:46:39 c2s94ba718 info Client connected
Oct 20 23:46:39 c2s94ba718 info Client disconnected: ssl handshake failed
Oct 20 23:46:39 c2s94ba718 info Destroying session for (unknown) ((unknown)#(unknown))
Oct 20 23:48:57 c2s96052a0 info Client connected
Oct 20 23:48:57 c2s96052a0 info Client disconnected: ssl handshake failed
Oct 20 23:48:57 c2s96052a0 info Destroying session for (unknown) ((unknown)#(unknown))
Any suggestions on this would be much appreciated. Aim is to connect to a XMPP server and join a MUC through python.

As I see that you are using Python 2.7, be sure you updated to the latest version (2.7.11) because there are some recently SSL changes that could break a LOT of code.

I had this error in Pidgin (libpurple 2.10.11) when I did not provide a certificate chain on the server-side.
I solved this by adding the CA-bundle (i.e. intermediate certificate) at the end of the certificate on the server:
cat /path/to/ica.crt >> /path/to/prosody.crt
Also see https://prosody.im/doc/certificates#certificate_chains for further information

Related

Python SSL module: how to turn on debug to display handshake in detail

In Perl, I can do
perl -MIO::Socket::SSL=debug4 my_program.pl
This displays SSL handshake in detail
DEBUG: .../IO/Socket/SSL.pm:2649: new ctx 98842176
DEBUG: .../IO/Socket/SSL.pm:562: socket not yet connected
DEBUG: .../IO/Socket/SSL.pm:564: socket connected
DEBUG: .../IO/Socket/SSL.pm:586: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:619: using SNI with hostname fundresearch.fidelity.com
DEBUG: .../IO/Socket/SSL.pm:654: request OCSP stapling
DEBUG: .../IO/Socket/SSL.pm:673: set socket to non-blocking to enforce timeout=180
DEBUG: .../IO/Socket/SSL.pm:686: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:689: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:699: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:709: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:729: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:686: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:2552: did not get stapled OCSP response
DEBUG: .../IO/Socket/SSL.pm:2505: ok=0 cert=102327360
DEBUG: .../IO/Socket/SSL.pm:689: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:692: SSL connect attempt failed
DEBUG: .../IO/Socket/SSL.pm:692: local error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../IO/Socket/SSL.pm:695: fatal SSL error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../lib/Net/HTTPS.pm:69: ignoring less severe local error 'IO::Socket::IP configuration failed', keep 'SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed'
DEBUG: .../IO/Socket/SSL.pm:2682: free ctx 98842176 open=98842176
DEBUG: .../IO/Socket/SSL.pm:2687: free ctx 98842176 callback
DEBUG: .../IO/Socket/SSL.pm:2694: OK free ctx 98842176
Error GETing https://fundresearch.fidelity.com/mutual-funds/fees-and-prices/316343201: Can't connect to fundresearch.fidelity.com:443 at -e line 1.
see example in Perl SSL debug mode
I'd like to use something similar to this in Python, from command line or inside python script, to display SSL handshake in detail.
Thank you

grpc python client authentication throwing SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED

I am building one grpc based application with secure authentication, is there any issue with grpc python client or i am missing anything ? because on documentation it don't say much things.
My environment is following:
OS: "Ubuntu 18.04.5 LTS"
python 3.7
openssl V 1.1.1-1ubuntu2.1~18.04.13
grpcio==1.39.0
grpcio-tools==1.39.0
protobuf==3.17.3
I am always getting SSL_ERROR_SSL: CERTIFICATE_VERIFY_FAILED
E0901 13:16:05.996420843 13512 ssl_transport_security.cc:1468] Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
E0901 13:16:06.495380631 13512 ssl_transport_security.cc:1468] Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
E0901 13:16:06.953751870 13512 ssl_transport_security.cc:1468] Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
E0901 13:16:07.407166253 13512 ssl_transport_security.cc:1468] Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
Traceback (most recent call last):
File "grpc-client.py", line 21, in <module>
main()
File "grpc-client.py", line 11, in main
response = stub.ApiEndpoint(request)
File "/home/ggarg/.local/lib/python3.7/site-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/ggarg/.local/lib/python3.7/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses"
my proto file is:
syntax = "proto3";
service Api{
rpc ApiEndpoint(ApiRequest) returns (ApiResponse);
}
message ApiRequest{
string name = 1;
string message = 2;
}
message ApiResponse{
string reply = 1;
}
server code is:
import grpc
from concurrent import futures
import time
import api_pb2
import api_pb2_grpc
import os
class ChatBox(api_pb2_grpc.ApiServicer):
def ApiEndpoint(self, request, context):
response = api_pb2.ApiResponse()
response.reply = "Hi {}, myself {} , Thanks for this message : {}".format(
request.name, os.getenv("POD_NAME"), request.message)
return response
if __name__ == '__main__':
# create a gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
with open('cert/server.key', 'rb') as f:
private_key = f.read()
with open('cert/server.crt', 'rb') as f:
certificate_chain = f.read()
server_credentials = grpc.ssl_server_credentials(
((private_key, certificate_chain), ))
# add the servier created above tp the server
api_pb2_grpc.add_ApiServicer_to_server(ChatBox(), server)
# listen on port 50051
print('Starting server. Listening on port 50051.')
server.add_secure_port('[::]:50051', server_credentials)
server.start()
# since server.start() will not block,
# a sleep-loop is added to keep alive
try:
while True:
time.sleep(86400)
except KeyboardInterrupt:
server.stop(0)
and client code is:
import grpc
import api_pb2_grpc
import api_pb2
import time
def main():
request = api_pb2.ApiRequest(
name="timus",
message="You are awesome")
response = stub.ApiEndpoint(request)
print(response)
if __name__ == '__main__':
with open('cert/server.crt', 'rb') as f:
creds = grpc.ssl_channel_credentials(f.read())
#channel = grpc.secure_channel('www.timus.com:443', creds)
channel = grpc.secure_channel('0.0.0.0:50051', creds)
stub = api_pb2_grpc.ApiStub(channel)
while True:
main()
time.sleep(2)
I used following openssl command to generate crt.
openssl req -newkey rsa:4096 -nodes -sha512 -x509 -days 3650 -nodes -out server.crt -keyout server.key
I pasted above code as a example. for simplicity i am using same certificate on client and server. Initially i used ca/server/client certificate differently but I was having this issue and just for testing i used server certificate on both client and server side. but still getting same issue ? did anyone encounter similar issue ? thanks in advance.
It seems you are trying to assign the server certificate as the client's trust certificate. That will require the certificate to be a self-signed certificate. You will have to check that.
Even if it is self-signed, it is not the usual way for us to establish TLS connections. That can leave your applications to man-in-the-middle attack. You will want to have your client set a trust certificate that is issued by a CA, and have the CA sign the server's certificate. That can make sure there is a trustworthy third-party making sure the authentication is good.
You will also make sure the syntax is correct(sorry I am not that familiar with the Python syntax). We allow certs, root certs in both client and server for mutual TLS, but for single TLS, you only need to set certs for server, and root certs for client.

HTTPS connection closed after SSL handshake with no exception

I'm using a library (sentry.io observer) that should connect to a remote server via https and upload some data. I do not control the server, but I can see that no data is uploaded. I set the urllib logger level to debug and I see two log messages
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): <server_url>:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (2): <server_url>:443
but no exception is thrown. I used wireshark to sniff packets and I see two SSL handshakes are executed, but the FIN packet is sent right after server finishes the handshake. Packets exchange looks like:
< - client sends message
> - server sends message
< TCP handshake [syn, syn ack, ack]
< Client hello
> Server hello, certificate, server key exchange, server hello done
< Client key exchange, change cipher spec, finished
> New session ticket, change cipher spec, finished
< TCP connection termination [fin ack, fin ack, ack]
This packet exchange is done twice, as urllib tries to connect to the remote server twice. The server certificate is valid, but the connection is cancelled by client. I set the library and urllib loggers to debug, but no error messages or anything that could help me narrow the issue down appears.
The issue only appears when requests are done from docker (based on centos 7), but when launching the app on ubuntu host it works fine, connection is established and data is uploaded. What could be the cause of the issue?

Using Tor and Meteor DDP

I am trying to use the a meteor ddp client to use the data from a meteor app in my python script. IT is a script that uses the Tor proxy API called stem. This is how my tor communicator looks like which works if ran separately:
Tor communicator (taken from the tor tutorial page with minor alterations):
import socket
import socks
import stem.process
import requests
from stem.util import term
from requestData import requestData
SOCKS_PORT = 7000
# Set socks proxy and wrap the urllib module
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
socket.socket = socks.socksocket
# Perform DNS resolution through the socket
def getaddrinfo(*args):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo
def query(itemId):
"""
Uses requests to fetch a site using SocksiPy for Tor over the SOCKS_PORT.
"""
try:
return requestData(itemId)
except:
return "Unable to get data"
# Start an instance of Tor configured to only exit through Russia. This prints
# Tor's bootstrap information as it starts. Note that this likely will not
# work if you have another Tor instance running.
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(line)
print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
config = {
'SocksPort': str(SOCKS_PORT),
'ExitNodes': '{ru}',
},
init_msg_handler = print_bootstrap_lines,
)
tor_process.kill() # stops tor
The above script is being ran from this script:
import Communicator
from MeteorClient import MeteorClient
client = MeteorClient('ws://127.0.0.1:3000/websocket')
client.connect()
def subscription_callback(error):
if error:
print(error)
client.subscribe('accounts', callback=subscription_callback)
all_posts = client.find('accounts')
print(all_posts)
Communicator.query("190aqe41vbewh7367f2hf27521")
But it is then giving me this result:
[1mStarting Tor:
[0m
May 10 13:21:45.000 [notice] Bootstrapped 0%: Starting
May 10 13:21:45.000 [notice] Bootstrapped 80%: Connecting to the Tor network
May 10 13:21:46.000 [notice] Bootstrapped 85%: Finishing handshake with first hop
May 10 13:21:46.000 [notice] Bootstrapped 90%: Establishing a Tor circuit
May 10 13:21:47.000 [notice] Bootstrapped 100%: Done
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\socks.py", line 663, in connect
_BaseSocket.connect(self, proxy_addr)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\gatsu\My Documents\LiClipse Workspace\TorCommunicator\MeteorDDP.py", line 5, in <module>
client.connect()
File "C:\Python34\lib\site-packages\python_meteor-0.1.6-py3.4.egg\MeteorClient.py", line 55, in connect
File "C:\Python34\lib\site-packages\python_ddp-0.1.5-py3.4.egg\DDPClient.py", line 119, in connect
File "C:\Python34\lib\site-packages\ws4py-0.3.4-py3.4.egg\ws4py\client\__init__.py", line 209, in connect
File "C:\Python34\lib\site-packages\socks.py", line 674, in connect
raise ProxyConnectionError(msg, error)
socks.ProxyConnectionError: Error connecting to SOCKS5 proxy 127.0.0.1:7000: [WinError 10061] No connection could be made because the target machine actively refused it
I solved this by importing the Communicator after I had done my Meteor stuff, right before I call a method in the Communicator.
from MeteorClient import MeteorClient
client = MeteorClient('ws://127.0.0.1:3000/websocket')
client.connect()
def subscription_callback(error):
if error:
print(error)
client.subscribe('accounts', callback=subscription_callback)
all_posts = client.find('accounts')
print(all_posts)
import Communicator
Communicator.query("190aqe41vbewh7367f2hf27521")

XMPPPY with Openfire

I'm trying to simply connect XMPPPY to Openfire, send a message, then close. The problem is that I keep getting
(Python 2.6)
import xmpp
pwd = "password"
jid=xmpp.protocol.JID("testuser#localhost")
cl=xmpp.Client(jid.getDomain()) #which translates to 'localhost'
cl.connect()
DEBUG: socket start Plugging <xmpp.transports.TCPsocket instance at 0x190ea1b8> into <xmpp.client.Client instance at 0x190e5320>
DEBUG: socket start Successfully connected to remote host ('localhost', 5222)
DEBUG: dispatcher start Plugging <xmpp.dispatcher.Dispatcher instance at 0x190ea2d8> into <xmpp.client.Client instance at 0x190e5320>
cl.auth(jid.getNode(),pwd) #translates to 'testuser' / 'password'
DEBUG: sasl error Failed SASL authentification: <not-authorized />
DEBUG: sasl stop Plugging <xmpp.auth.SASL instance at 0x190f0320> out of <xmpp.client.Client instance at 0x190e5320>.
I'm 100% sure that the username and password are correct as I've tried many times and can connect via Spark.
Is there a setting somewhere that I'm missing / has anyone has success with this?
lookup your jid format
jid=xmpp.protocol.JID("testuser#localhost")
the xmpp server name should same as name after '#'
check the xmpp server name at http://localhost:9090/index.jsp

Categories