Unable to decode SSL msg_callback certificate data

I am using undocumented ssl msg_callback to log certificate error informations on TLS connection. This way I can know if the certificate is revoked, expired or unknown before the connection is refused.
I would like to add certificate common name in my logs.

I added the callback like this :

def TlsCallback(conn, direction, version, content_type, msg_type, data):
    info = (conn, direction, version, content_type, msg_type, data)
    sys.stdout.write(f"TLS : {info!r}\n")
    ...

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context._msg_callback = TlsCallback

At some point I get the client certificate through the callback, which printed output is :
TLS : (<ssl.SSLSocket fd=4, family=2, type=1, proto=0, laddr=(‘192.168.10.2’, 443), raddr=(‘192.168.10.2’, 60264)>, ‘read’, <TLSVersion.TLSv1_3: 772>, <_TLSContentType.HANDSHAKE: 22>, <TLSMessageType.CERTIFICATE: 11>, b"\x0b\x00\x01\x00\x0 …")
The last field is my data which is the certificate but it has additionnal bytes at the beginning and at the end.

Can someone tell me where I can find informations about the trailing bytes and how many I should remove to keep only the certificate ? I see the number varies between different certificates and I can’t find the certificate lenght in the data

You could try reading the sources of python, openssl, etc to see what is going on.
I find when working on this cert stuff that helps a lot.
We found we needed to use pyopenssl to do the sort of things you are doing.

Also try saving the certificate data into a file and try using the openssl x509 command on the data to see what it might be. The file command may also gives you a clue.

I’m trying to do similar inspection of headers in a similar callback.Do you need to end the callback in some particular way as my program seems to be hanging after it gets invoked?

The callback data argument is raw ASN.1. You need an ASN.1 parser like pyasn1 or asn1crypto to decode the data. You also need to figure out the ASN.1 structure based on version, content type, and message type. RFC 8446 will get you started.

I am still using this callback and I don’t end it in a particular way, I never had any issue with it hanging the program. I use it for logging purpose so most times it does nothing but inspect the data and when an issue is detected it is sent to the logging mechanism.