def parse_csr(data, encoding): """Loads the user provided CSR into the backend X509 library. :param data: CSR as provided by the API user :param encoding: encoding for the CSR (must be PEM today) :return: CSR object from backend X509 library or aborts """ # validate untrusted input if str(encoding).lower() not in VALID_ENCODINGS: logger.error("parse_csr failed: bad encoding ({})".format(encoding)) pecan.abort(400, "invalid CSR") if data is None: logger.error("parse_csr failed: missing CSR") pecan.abort(400, "invalid CSR") # get DER version der = util.extract_pem(data.encode('ascii')) if der is None: logger.error("perse_csr failed: PEM contentents not found") pecan.abort(400, "PEM contents not found") # try to unpack the certificate from CMC wrappers try: csr = cmc.parse_request(der) return signing_request.X509Csr(csr) except cmc.CMCParsingError: # it's not CMC data, that's fine, it's likely the CSR itself try: return signing_request.X509Csr.from_buffer(der, 'der') except Exception as e: logger.exception("Exception while parsing the CSR: %s", e) pecan.abort(400, "CSR cannot be parsed")
def from_open_file(f, encoding='pem'): if encoding == 'pem': try: der_content = util.extract_pem(f.read()) except Exception: raise X509CsrError("Data not in PEM format") elif encoding == 'der': der_content = f.read() else: raise X509CsrError("Unknown encoding") try: csr = decoder.decode(der_content, asn1Spec=rfc6402.CertificationRequest())[0] return X509Csr(csr) except Exception: raise X509CsrError("Could not read X509 certificate from data.")