How to disable session resumption in pyOpenSSL? - ssl

The Tripple Handshake Issue was disclosed lately. Wether disabling session resumption will mitigate this or not, is a topic for another question. Let's assume I want to disable it for whatever reason (basicly my paranoia).
To disable this in C, it seems like one should use this:
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
Can someone please confirm this?
But how to do this in pyopenssl?

Starting with pyOpenSSL 0.14 this is possible:
from OpenSSL.SSL import TLSv1_2_METHOD SESS_CACHE_OFF, Context, Connection
ctx = Context(TLSv1_2_METHOD)
ctx.set_session_cache_mode(SESS_CACHE_OFF)
conn = Connection(ctx, ...)
Earlier versions of pyOpenSSL do not expose these APIs.
If you also need to turn off session tickets then:
from OpenSSL.SSL import OP_NO_TICKET
...
ctx.set_options(OP_NO_TICKET)

Can someone please confirm this?
I believe Dr. Henson answered this over at the OpenSSL User Mailing list.
the attack described in https://secure-resumption.com/ breaks also tls
channel binding tls-unique RFC 5929.
I would still like to use tls-unique for channel binding as defined in
SCRAM (RFC 5802). Can OpenSSL be used for channel binding and protect
against this attack if the session caching is disabled?
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF)
Is it necessary to disable resumption using a different function?
You'd also need to disable session tickets too.
Note the initiial phase of the attack requires that the attacker
possess a private key and certificate the client trusts. I'd be
interested to know how that could happen under your circumstances.
So, according to Dr. Henson, you also need to call SSL_CTX_set_options with SSL_OP_NO_TICKET. See the OpenSSL docs at
SSL_CTX_set_options(3).
I don't know how to do it in Python, though.

Related

Standalone alternative to express-session for use in serverless context (w/ DynamoDB)

Background: why use cookies with Lambdas?
OWASP is very clear that cookies are the best option for session management:
.. cookies .. are one of the most extensively used session ID exchange mechanisms, offering advanced capabilities not available in other methods.
However AWS's API Gateway literature often talks about using JWTs for authentication rather than cookies. While some tech blogs out there seem to think it's ok to use JWTs in this way, there are definitely recognised issues with JWTs. Two issues of particaular note are:
(a) you can't easily invalidate a JWT. At best you can keep a server-side database of blocked JWTs and make sure any service validating JWTs also implements a check against this block list. That sounds a lot like implementing regular old sessions, largely defeating the point of using JWTs.
(b) if your want to use JWTs for authorization as well as authentication, you'll run into issues when you need to update the authorization and it's not a change being driven by the enduser themselves. Scenarios in this category include: a system administrator or account manager changes the user's access level; a trial/contract is ended by a cron job; a webhook is triggered by a 3rd party SaaS integration (e.g. Stripe). You might say, "in that case use a separate mechanism for authorization", but then again you're back to good old sessions.
To be clear, I understand the value of JWTs in letting one server communicate its trust in a user's identity to another server, but that's a very different purpose to session management.
Session management in Node
All roads seem to lead to express-session as the most battle-tested implementation of sessions in Node. It offers a wide range of storage options to choose from*.
In the context of Lambdas, in principle you could try and use express-session as though it were just a function factory, for functions with the signature (req,res,next)=>void, that's rather hacky, and in no way recommended by express-sessions. It's also not entirely clear how best to match that call signature to the objects you get in an AWS Lambda, nor which storage mechanisms are optimised for lambdas (which are ephemeral and need to start quickly).
I would really like a lightweight node module that lets you do something like the following:
import {Sessions} from 'sessions';
// configure session management. Should be super lightweight for use in Lambda.
const sessions = new Sessions({
/* ..basic cookie & expiration config, */
secret: "something", // extra security recommended by express
store: { // object with following interface:
createSession(sessionId, metadata),
getFromSessionId(sessionId),
updateSession(sessionId, metadata),
customIndexedProperties: ['userId'], // in addition to sessionId
getSessionIdsFromIndexedProperty(propertyName, propertyValue),
}
});
// create session. Note the api is not opinionated about response header mechanics.
response.headers['set-cookie'] = await sessions.createCookieForSession({
userId: 'user1',
/*...other user info */
});
// get user's session. Again not opinionated about where cookie comes from.
const userSessionInfo = await sessions.getSessionFromCookie(request.header['cookies']);
// update a user's session, but not initiated by the user themselves
const sessionIds = await sessions.getSessionIdsFromIndexedProperty('userId', 'user1');
await sessions.updateSession(sessionIds[0], {something: 'has change'});
Questions
Is my above thinking reasonable?
Are there any node packages I've not encountered that might be helpful.
If not, why not? I have come across a few people with closely related problems, but it must be a fairly common issue when working with serverless.
If I were to implement a module to my own liking how do I get any confidence that I've done a good job security-wise? I could use pieces of express-session that are relevant, but that's not a great long-term solution for good security.
Related to 4, if I were to try and hook into express-sessions, but just build my own store that does what I need, how would I get confidence in the security? Also, I haven't managed to find any docs on what the official api is for an express-session store, which I find amazing given that express-sessions seems to be the go to for sessions in Node.
Any help would be massively appreciated, thanks!
P.S. I appreciate a lot of what I'm discussing relates to open source projects that are often poorly funded. However, I was very surprised to have reached the above conclusions about the state of the ecosystem and wondered if I was missing something.
*Annoyingly, the suggested DynamoDb store package isn't great. Two of the features we'd want from it are not support, indeed PRs seem to have been opened back in 2019 but never looked at by the maintainer. Technically we don't absolutely have to use DynamoDb as our store, but it is does offer a lot of features we like.

mbed TLS initialization

We have ported an app which was using OpenSSL to mbel TLS. The one issue with mbel TLS is the documentation which is far from complete and leaves details to assumption or exploration and risk of how things will change in future versions.
While we already ported, we still not clear on which initialization functions to be invoked one time and which initialization functions to be performed for every connections. Based on sample application, we are invoking following initialization functions for every connection.
mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_net_init( &server_fd );
mbedtls_ssl_init( &ssl );
mbedtls_ssl_config_init( &conf );
mbedtls_x509_crt_init( &ca );
mbedtls_entropy_init( &entropy );
Can someone comment if all these initialization functions to be invoked for every connection or some can be just one time only?
Thanks
If you follow the ssl_pthread_server example, you will see that only the mbedtls_ssl_context should be different per connection. The rest should be common for all connections, thus initiated once.
Regards,
Mbed TLS Team member
Ron

Parsing an X509 Certificate

I currently need to parse the CommonName from a packet. I have code that works up to a point, however am having trouble skipping over the "issuer" member of a Certificate record for TLSv1.2. I have done research on the format of the SSL records and have investigated the dump via wireshark. I've found the format is generally - Length, followed by the data. However when trying to find the issue length, I cannot seem to get it, and is inconsistent with the bytes presented. Any ideas..or a better way to skip over the issuer field, and go directly to the "subject" of an TLS 1.2 record. Coded in C..Thank you for useful responses.
You need to understand ASN.1. Go read this book (it is a free download). Once you have read and understood it, you can write your decoder, following the ASN.1 specification for certificates. This is doable, but requires great implementation care. In fact, this is a bad idea unless you are a demi-god of C programming.
Alternatively, use some library that already knows how to decode a certificate. Typically, OpenSSL.

OpenSSL: How to supply a custom pointer to the certificate verification callback

I want to use X509_STORE_set_verify_cb_func to receive certificate validation errors. I then want to store these errors in a list and process it later after SSL_connect returned.
However my application is multithreaded and I wanted to avoid any mutex locking for this callback. Any ways to pass a "void pointer" or store this somewhere in the X509_STORE_CTX so I can store the error inside the "right" location and don't have to use a global error list and lock that while doing the SSL_connect?
Thanks
AFAIK you are indeed stuck with that - just stuff it as an entry in there under your own id. The other option is to deal with the SSL callbacks a bit more generically - see for example ssl_hook in ssl_engine_kernel.c of Apache its SSL module. While a bit more work - it gives you complete control over the entire process - and entirely in your 'own process space'.
Thanks,
Dw.
If you are using C11 or later, you can define a global thread_local variable
thread_local void * openssl_verify_context;
Then
Set openssl_verify_context before setting the callback (i.e. before X509_STORE_set_verify_cb_func).
Use openssl_verify_context in the callback.
If needed read and unset openssl_verify_context after validating the certificate (i.e. after PKCS7_dataVerify).
The advantage of this solution is you do not need to know the details of the struct behind X509_STORE_CTX (it is hidden in recent versions of OpenSSL).

Terrible Performance with WCF and certificates (mutual authentication)

Guys / Gals we are having terrible performance with our website that uses WCF as the application later. We are using message level security and certificates (mutual authentication). We are caching the channel factory in the application object:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim loChannelFactor As New ChannelFactory(Of OurReference.IWCFChannel)("ClientEndpoint")
loChannelFactor.Open()
Application.Add("ChannelFactory", loChannelFactor)
End Sub
In every page that we need data we do the following:
Dim Proxy = DirectCast(voWebApp("ChannelFactory"), ChannelFactory(Of OurInfoReference.IOurInfoChannel)).CreateChannel
Proxy.DataCall()
If roWCFService IsNot Nothing Then
CType(roWCFService, ICommunicationObject).Close()
roWCFService = Nothing
End If
Also i have set establishsecuritycontext = true.
We are not wanting to cache the proxy because of having to mess with a faulted proxy state. As far as i know caching the channel stack should be enough anyways. When i turn on tracking i'm seeing a bunch of SCT commands instead of just for the first call like i would expect. Does anyone know whats going on. Are we caching the channel factory incorrectly?
thanks,
Ncage
Looks like you could solve it using a certificate from a ceritificate authority:
"MakeCert is a tool provided by Microsoft to create test certificates that can be used during the development of a product (For developing and testing purposes only). These certificates have also performance problems, certain cryptographic operations may perform slowly when they are used. Certificates issued from a true Certificate Authority do not have this problem, and it is a know issue."
http://weblogs.asp.net/cibrax/archive/2006/08/08/Creating-X509-Certificates-for-WSE-or-WCF.aspx
Edit: May be the extra activity is due to initial handshake when creating of a session. WCF default is per call, that is a new session is created for each call. You could try marking your contract with:
[ServiceContract(Session = true)]
That may maintain the session and avoid the initial handshake.
I remember a similar issue however it was a good 18 months ago. I found this whilst having a quick look for how i resolved the issue. It may help, I will edit my response when I find what I was looking for!
The additional SCT/RST calls are establishing the security context. If you recreate the proxy on each call, a security context is unneccesary overhead. Turn it off.
The way you use the factory is fine. However, your error handling and closing of the proxy is not. Make sure that you close or abort the proxy in any case. Check msdn for the recommended pattern.
Also can you provide some figures about how bad performance is?