2019-03-15 09:18:33 +01:00
|
|
|
"""
|
|
|
|
Utils to parse certificate data.
|
|
|
|
|
|
|
|
.. module: lemur.certificates.hooks
|
|
|
|
:platform: Unix
|
|
|
|
:copyright: (c) 2019 by Javier Ramos, see AUTHORS for more
|
|
|
|
:license: Apache, see LICENSE for more details.
|
|
|
|
|
|
|
|
.. moduleauthor:: Javier Ramos <javier.ramos@booking.com>
|
|
|
|
"""
|
|
|
|
|
|
|
|
from cryptography import x509
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from marshmallow.exceptions import ValidationError
|
|
|
|
|
|
|
|
|
2019-03-26 15:09:08 +01:00
|
|
|
def get_sans_from_csr(data):
|
2019-03-15 09:18:33 +01:00
|
|
|
"""
|
2019-03-26 15:09:08 +01:00
|
|
|
Fetches SubjectAlternativeNames from CSR.
|
|
|
|
Works with any kind of SubjectAlternativeName
|
2019-03-15 09:18:33 +01:00
|
|
|
:param data: PEM-encoded string with CSR
|
2019-03-26 15:09:08 +01:00
|
|
|
:return: List of LemurAPI-compatible subAltNames
|
2019-03-15 09:18:33 +01:00
|
|
|
"""
|
2019-03-26 15:09:08 +01:00
|
|
|
sub_alt_names = []
|
2019-03-15 09:18:33 +01:00
|
|
|
try:
|
2019-05-16 16:57:02 +02:00
|
|
|
request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend())
|
2019-03-15 09:18:33 +01:00
|
|
|
except Exception:
|
2019-05-16 16:57:02 +02:00
|
|
|
raise ValidationError("CSR presented is not valid.")
|
2019-03-15 09:18:33 +01:00
|
|
|
|
|
|
|
try:
|
2019-05-16 16:57:02 +02:00
|
|
|
alt_names = request.extensions.get_extension_for_class(
|
|
|
|
x509.SubjectAlternativeName
|
|
|
|
)
|
2019-03-26 15:09:08 +01:00
|
|
|
for alt_name in alt_names.value:
|
2019-05-16 16:57:02 +02:00
|
|
|
sub_alt_names.append(
|
|
|
|
{"nameType": type(alt_name).__name__, "value": alt_name.value}
|
|
|
|
)
|
2019-03-15 09:18:33 +01:00
|
|
|
except x509.ExtensionNotFound:
|
|
|
|
pass
|
|
|
|
|
2019-03-26 15:09:08 +01:00
|
|
|
return sub_alt_names
|