How to validate the SSL server certificate in twisted SSL client - python

How do I validate the SSL server certificates in my twisted SSL client?
I am very much beginner to the SSL, I have gone through the twisted SSL tutorials but still I am unclear about some things.
My queries are:
How should I validate the SSL server certificate using twisted.internet.ssl module,
How ssl.ClientContextFactory.getContext method is useful while dealing with SSL,
How can I tell twisted SSL client about the location of the public key file?

Since Twisted 14.0, optionsForClientTLS is the best way to do this:
from twisted.internet.ssl import optionsForClientTLS
from twisted.internet.endpoints import SSL4ClientEndpoint
ctx = optionsForClientTLS(hostname=u"example.com")
endpoint = SSL4ClientEndpoint(reactor, host, port, ctx)
factory = ...
d = endpoint.connect(factory)
...
optionsForClientTLS takes other (optional) arguments as well which may also be useful.
Prior to Twisted 14.0, the process was a bit more involved:
After the connection is established and the SSL handshake has completed successfully (which means the certificate is currently valid based on its notBefore and notAfter values and that it is signed by a certificate authority certificate which you have indicated is trusted) you can get the certificate from the transport:
certificate = self.transport.getPeerCertificate()
The certificate is represented as a pyOpenSSL X509 instance. It has a method you can use to retrieve the certificate's subject name:
subject_name = certificate.get_subject()
The subject name is a distinguished name, represented as a pyOpenSSL X509Name instance. You can inspect its fields:
common_name = subject_name.commonName
This is a string, for example "example.com".
If you need to inspect the subjectAltName instead (which it's likely you do), then you can find this information in the extensions of the certificate:
extensions = certificate.get_extensions()
This is a list of pyOpenSSL X509Extension instances. You'll have to parse each one to find the subjectAltName and its value.

Related

Certificate for Client Authentication

I need your help.
I want to generate a certificate for a client for authorization on my api.
In my use case, I have an API that is hosted with python hypercorn and fastapi. Then I have multiple clients (also python (httpx)) that should request data from this api. For authentication between the client and the server, I want to use certificates. I want to provide the client with a certificate with which it can authorize itself with the server.
For generating the certificates i used this instruction: https://www.makethenmakeinstall.com/2014/05/ssl-client-authentication-step-by-step/
What did I do wrong, or how can I implement my use case?
server:
async def main():
config = Config.from_mapping(dict(
worker_class='trio',
certfile='server.cer',
keyfile='server.key',
verify_mode=VerifyMode.CERT_REQUIRED,
bind=f"0.0.0.0:{8000}"))
async with trio.open_nursery() as nursery:
nursery.start_soon(serve, app, config)
client:
import httpx
res = httpx.get("https://localhost:8000/", verify=True, cert=("client.cer", "client.key"))
res
When I execute the request in the client I get the following error:
ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1123)
let's simplify how certificates work.
certificates used for authentication and authorization and this is what you're exactly doing in your case. your backend-server has its own certificate, and your client has his own certificate. your applications is set to recognize each other using these certificates and you're doing it in a great way.
but certificates are vulnerable and can be created locally, so I myself can create a certificate that says that I'm facebook or google. and here is the validation's role come; a well know authority that's already implemented in all browsers and OS - and we call it CA for a certification authority - signs your certificates, so when your server send its cert to a client, the client's browser would recognize the signature and tells you that the certificate is valid.
in your case here you have a self signed certificate, which means that for development purpose you've signed your cert by yourself "instead of the recognized CAs".
Overcoming such an issue would be in two ways.
you disable the validation in your code and in your client side as well. suits for development purpose or intra network.
sign your certificate and your client's certificate with a recognized authority like digicert, and add your CA in your trust-store.

Python Eclipse Paho Client - TLS Connection to MQTT Broker Exception: No ciphers available

I am trying to create a connection to a TLS (TLSv1) secured MQTT Broker(Rabbitmq with MQTT Plugin enabled) with the python implementation of the eclipse paho client. The same works fine with the MQTTFX application which is based on the java implementation of paho. For this i am using self signed certificates.
Java version uses:
CA-File: ca_certificate.crt
Client Certificate client_cert.crt
Client Key File: client_key.key
Python Version should use:
CA-File: ca_certificate.pem
Client Certificate: client_cert.pem
Client key file: client_key.key
I tried to establish a connection like this:
import ssl
import paho.mqtt.client as paho
# Locations of CA Authority, client certificate and client key file
ca_cert = "ca_certificate.pem"
client_cert = "client_certificate.pem"
client_key = "client_key.pem"
# Create ssl context with TLSv1
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_verify_locations(ca_cert)
context.load_cert_chain(client_cert, client_key)
# Alternative to using ssl context but throws the exact same error
# client.tls_set(ca_certs=ca_cert, certfile=client_cert, keyfile=client_key, tls_version=ssl.PROTOCOL_TLSv1)
client = paho.Client()
client.username_pw_set(username="USER", password="PASSWORD")
client.tls_set_context(context)
client.tls_insecure_set(False)
client.connect_async(host="HOSTNAME", port="PORT")
client.loop_forever()
Which results in the following error:
ssl.SSLError: [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:997)
Could it be that I need to explicitly pass a cipher that the broker supports or could it be due of an older openssl version? I am a little bit lost right now, maybe someone has a clue on how to solve this.
Edit: I got it to work by myself but still not sure why exactly it works now.
Changed context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
to context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Changed client.tls_insecure_set(False)
to client.tls_insecure_set(True)
PROTOCOL_TLSv1 forces the client to only use TLS v1.0 which is old and unless you have explicitly forced your broker to only use the same version unlikely to match.
Using PROTOCOL_TLS_CLIENT will allow Python to negotiate across the full range of TLS v1.0 to TLS v1.3 until it finds one that both the client and the broker support.
Why you are having to set client.tls_insecure_set(True) is hard to answer without knowing more about the certificates you are using with the broker. Does it container a CA/SAN entry that matches the HOSTNAME you are using to connect? The documentation says it will explicitly enforce the hostname check.
ssl.PROTOCOL_TLS_CLIENT
Auto-negotiate the highest protocol version that both the client and
server support, and configure the context client-side connections. The
protocol enables CERT_REQUIRED and check_hostname by default.

Verify SSL certificate from the custom path using python

I have installed apache web server. Generated SSL for the apache website. Got cert file and key. I wrote a python snippet to validate the ssl file for the website. The certificate file path is stored in cer_auth. My code will access file in the cer_auth,validates it and provide the result. But it is showing error. How to solve it?
Here's the code:
import requests
host = '192.168.1.27'
host1 = 'https://'+host
#cer_auth = '/etc/ssl/certs/ca-certificates.crt'
cer_auth = '/home/paulsteven/Apache_SSL/apache-selfsigned.crt'
print(host1)
try:
requests.get(host1, verify= cer_auth)
print("SSL Certificate Verified")
except:
print("No SSL certificate")
Error i got:
https://192.168.1.27
/home/paulsteven/.local/lib/python3.5/site-packages/urllib3/connection.py:362: SubjectAltNameWarning: Certificate for 192.168.1.27 has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 for details.)
SubjectAltNameWarning
No SSL certificate
The old way of pointing certificates to hostnames was through the CommonName or CN field. This practice is rapidly changing due to changes in how browsers handle certificates. The current expectation is to have all hostnames and IPs in x509v3 extended fields in the certificate, named subjectAlternativeNames. The instructions you have followed were probably outdated.
Here's a mediocre guide into doing just that with OpenSSL
https://support.citrix.com/article/CTX135602
If you want to sign for some IP addresses, the field name is IP.1 instead of DNS.1 like in the link above.

Connect to FTP TLS 1.2 Server with ftplib

I try to connect to a FTP Server which only supports TLS 1.2
Using Python 3.4.1
My Code:
import ftplib
import ssl
ftps = ftplib.FTP_TLS()
ftps.ssl_version = ssl.PROTOCOL_TLSv1_2
print (ftps.connect('108.61.166.122',31000))
print(ftps.login('test','test123'))
ftps.prot_p()
print (ftps.retrlines('LIST'))
Error on client side:
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:598)
Error on server side:
Failed TLS negotiation on control channel, disconnected. (SSL_accept():
error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol)
The credentials in the example are working for testing.
See the end of this post for the final solution. The rest are the steps needed to debug the problem.
I try to connect to a FTP Server which only supports TLS 1.2 Using Python 3.4.1
How do you know?
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:598)
I would suggest one of the many SSL problems between client and server, like the server not supporting TLS 1.2, no common ciphers etc. These problems are hard to debug because you either get only some SSL alert or the server will simply close the connection without any obvious reason. If you have access to the server look for error messages on the server side.
You may also try to not to enforce an SSL version but use the default instead, so that client and server will agree to the best SSL version both support. If this will still not work try with a client which is known to work with this server and make a packet capture of the good and bad connections and compare. If you need help with that post the packet captures to cloudshark.org.
Edit#1: just tried it with python 3.4.0 and 3.4.2 against a test server:
python 3.4.0 does a TLS 1.0 handshake, i.e. ignores the setting
python 3.4.2 does a successful TLS 1.2 handshake
In both versions ftplib has the minor bug, that it sends AUTH SSL instead of AUTH TLS if ftps.ssl_version is something else then TLS 1.0, i.e. SSLv3 or TLS1.1.+. While I doubt that this is the origin of the problem it might actually be if the FTP server handles AUTH TLS and AUTH SSL differently.
Edit#2 and Solution:
A packet capture shows that setting ftps.ssl_version has no effect and the SSL handshake will still be done with TLS 1.0 only. Looking at the source code of ftplib in 3.4.0 gives:
ssl_version = ssl.PROTOCOL_TLSv1
def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
certfile=None, context=None,
timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
....
if context is None:
context = ssl._create_stdlib_context(self.ssl_version,
certfile=certfile,
keyfile=keyfile)
self.context = context
Since __init__ is called when ftplib.FTP_TLS() is called the SSL context will be created with the default ssl_version used by ftplib (ssl.PROTOCOL_TLSv1) and not with your own version. To enforce another SSL version you must to provide your own context with the needed SSL version. The following works for me:
import ftplib
import ssl
ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1_2)
ftps = ftplib.FTP_TLS(context=ctx)
print (ftps.connect('108.61.166.122',31000))
print(ftps.login('test','test123'))
ftps.prot_p()
print (ftps.retrlines('LIST'))
Alternatively you could set the protocol version globally instead of only for this FTP_TLS object:
ftplib.FTP_TLS.ssl_version = ssl.PROTOCOL_TLSv1_2
ftps = ftplib.FTP_TLS()
And just a small but important observation: it looks like that ftplib does not do any kind of certificate validation, since it accepts this self-signed certificate which does not match the name without complaining. This makes a active man-in-the-middle attack possible. Hopefully they will fix this insecure behavior in the future, in which case the code here will fail because of an invalid certificate.
Firstly AFAIK no ftp supports SSL directly, for which ftps is introduced. Also sftp and ftps are two different concepts: http://en.wikipedia.org/wiki/FTPS .Now, your problem is regarding the programming and not related to SSL or FTPs or any such client-server communication
import ftplib
import ssl
ftps = ftplib.FTP_TLS()
#ftps.ssl_version = ssl.PROTOCOL_TLSv1_2
print (ftps.connect('108.61.166.122',31000))
print(ftps.login('test','test123'))
ftps.prot_p()
print (ftps.retrlines('LIST'))
as ftplib has no attribute PROTOCOL_TLSv1_2 besides which it works fine. and well, your host is not responding !
Hopefully it helps !

HTTPS request in twisted that checks the certificate

In my twisted app I want to make an asynchronous request to Akismet to check for spam. Akismet reasonably uses HTTPS, so I've been following the web client guide on SSL in the docs. But there's this part that worries me:
Here’s an example which shows how to use Agent to request an HTTPS URL with no certificate verification.
I very much want certificate verification to prevent Man-In-The-Middle attacks. So how do I add it?
My test code without verification is this:
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.internet.ssl import ClientContextFactory
class WebClientContextFactory(ClientContextFactory):
def getContext(self, hostname, port):
print( "getting context for {}:{}".format( hostname, port ) )
# FIXME: no attempt to verify certificates!
return ClientContextFactory.getContext(self)
agent = Agent( reactor, WebClientContextFactory() )
def success( response ):
print( "connected!" )
def failure( failure ):
print( "failure: {}".format( failure ) )
def stop( ignored ):
reactor.stop()
agent.request( "GET", "https://www.pcwebshop.co.uk/" )\ # uses self-signed cert
.addCallbacks( success, failure )\
.addBoth( stop )
reactor.run()
I'd like it to fail due to inability to verify the cert.
I'm using Twisted 15.1.0.
Actually, the default init function of Agent will pass in BrowserLikePolicyForHTTPS as contextFactory and have the ablility to verify server certificate.
Simply using this:
agent = Agent( reactor )
will produce the following error:
failure: [Failure instance: Traceback (failure with no frames):
<class 'twisted.web._newclient.ResponseNeverReceived'>:
[<twisted.python.failure.Failure <class 'OpenSSL.SSL.Error'>>]]
Make sure you installed service_identity package using pip.
If you need custom cert verification, you can create a custom policy by passing the pem in, as described here:
customPolicy = BrowserLikePolicyForHTTPS(
Certificate.loadPEM(FilePath("your-trust-root.pem").getContent())
)
agent = Agent(reactor, customPolicy)
Thanks for pointing this out. This seems to be a bug in the documentation. Prior to version 14.0, it was accurate; Twisted would not validate HTTPS, and that was a big problem. However, as you can see in the release notes for that version, Twisted (at least in versions 14.0 and greater) does validate TLS on HTTPS connections made with Agent. (It still does not do so for getPage, the old, bad, HTTP client; do not use getPage.)
I have filed this bug to track fixing the documentation to be accurate.

Categories

Resources