Synss / python-mbedtls

Cryptographic library with an mbed TLS back end
MIT License
79 stars 28 forks source link

Implement getpeercert #56

Closed skelsec closed 2 years ago

skelsec commented 2 years ago

NOTE: Please use stackoverflow for support questions. This repository's issues are reserved for feature requests and bug reports.

I am submitting a …

Description

I need to obtain the server's certificate after a successful handshake. In PEP there is a function documented getpeercert but I see in the code this is not implemented (commented out). Would it be possible to obtain the server's certificate in some other way? If not, I'd like to ask you to add this feature.

Current behavior

getpeercert is not implemented

Expected behavior

getpeercert to be implemented

Steps to reproduce

N/A

Minimal demo of the problem

N/A

Other information

I don't need it in parsed form, binary DER is more than enough.

Synss commented 2 years ago

Hi! That seems reasonable, I will see what I can do.

Synss commented 2 years ago

The standard SSLSocket.getpeercert() returns a dict for binary_form=False but I have wrapped the x509 part of mbedTLS so I would rather return an mbedtls.x509.CRT instance. They can be converted to DER with bytes() and PEM with str().

skelsec commented 2 years ago

I have got it working by

def getpeercert(self, binary_form=False):
        crt = _tls.mbedtls_ssl_get_peer_cert(&self._ctx)
        if binary_form is False:
            raise Exception('Not supported!')
        return crt.raw.p[0:crt.raw.len]

This is what is expected by PEP when binary_form=True. I'm just not sure what to do with the pointer. Should it be freed?

skelsec commented 2 years ago

sorry I haven't noticed you already pushed, it's okay for me

Synss commented 2 years ago

sorry I haven't noticed you already pushed, it's okay for me

sure, no problem.

I'm just not sure what to do with the pointer. Should it be freed?

I don't think so. I think it is a view on the peer certificate. At least, that is how I interpret the documentation and the fact that it is returned as a const *. So copying and returning looks good to me.