Search code examples
pythonazure-functionsclient-certificatespyopenssl

How to determine client certificate type using Python?


I have an HTTP-triggered Python Azure Function. The App Service which hosts this Function is set to Require Client Certs and only use HTTPS.

Azure automagically passes the client cert from each HTTP request to the Function code via the X-ARR-ClientCert header.

How do I determine the type (.der, .crt, .pem, .cer) of the incoming certificate using Python?

Example:

  • When testing using Postman, I upload a cert in .crt format via Settings/Certificates
  • Postman encodes this as a .der (binary) file and passes it to the Function endpoint
  • Azure (load balancer?) receives the request and forwards the cert to my Python Function code via the X-ARR-ClientCert header
    • Azure will not alter the cert from its original form(?)
    • If client was using say, Python instead of Postman to generate the request and they sent a .pem file across the wire (rather than a .der file), the Function would receive a .pem file.

How can I determine the cert file type so I can programmatically parse out the properties (Issuer, Common Name, not_valid_before/after, etc.) from the file?


Solution

  • I'm afraid you can't determine the cert automatically with python, but you can do it manually and view the encoded certification directly.

    Firstly, open the certificate file with txt format, if there is a start line like ----BEGIN CERTIFICATE----, it is in PEM format, otherwise it is in DER format.

    Then, here is some common OpenSSL certificate manipulations:

    View PEM encoded certificate Use the command that has the extension of your certificate replacing cert.xxx with the name of your certificate

    openssl x509 -in cert.pem -text -noout
    openssl x509 -in cert.cer -text -noout
    openssl x509 -in cert.crt -text -noout
    

    If you get the folowing error it means that you are trying to view a DER encoded certifciate and need to use the commands in the “View DER encoded certificate below”

    unable to load certificate 12626:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:647:Expecting: TRUSTED CERTIFICATE View DER encoded Certificate

    openssl x509 -in certificate.der -inform der -text -noout