diff --git a/sort_certificate.py b/sort_certificate.py index 97ff0b8..5e3c05e 100755 --- a/sort_certificate.py +++ b/sort_certificate.py @@ -116,6 +116,14 @@ def match_cert_privkey(cert, priv): return get_pub_modulus(cert) == get_priv_modulus(priv) +def find_root(x509_objects, root_issuers): + ''' + Find a suitable anchor by finding the intermediate that was signed by root + ''' + root_cert = root_issuers[str(x509_objects[-1].get_issuer())] + logging.debug('Retrieved root certificate %s', root_cert.get_subject()) + return root_cert + def find_intermediate_root(x509_objects, root_issuers): ''' Find a suitable anchor by finding the intermediate that was signed by root @@ -146,7 +154,7 @@ def order_x509(x509_objects, root_issuers): root_crt = [x for x in x509_objects if x.get_subject() == x.get_issuer()] if root_crt: root_crt = x509_objects.pop(x509_objects.index(root_crt[0])) - logging.warning('Found root certificate %s in input', + logging.warning('Found self signed (root) certificate %s in input', str(root_crt.get_subject())) # Double check if our self signed root certificate is not also present # as an intermediate: @@ -226,8 +234,8 @@ def load_root_issuers(): logging.debug(onlyrsa_exception) continue - root_issuers = [str(root_cert.get_subject()) - for root_cert in root_certs] + root_issuers = {str(root_cert.get_subject()): root_cert + for root_cert in root_certs} return root_issuers @@ -264,6 +272,8 @@ def main(): action='store_true', help='Just print chain') outputgrp.add_argument('--no-chain', dest='print_chain', action='store_false', help='Omit chain from output') + outputgrp.add_argument('--include-root', dest='include_root', + action='store_true', help='Also include the root certificate') outputgrp.set_defaults(print_chain=True) outputgrp.add_argument('--key', dest='print_key', @@ -347,6 +357,10 @@ def main(): logging.info('OK: Modulus of provided certificate' ' and private key match') + if args.include_root: + logging.debug('root certificate in output requested') + x509_objects.append(find_root(x509_objects, root_issuers)) + logging.debug("Print certificates in order") # Need to do b'CN' to have this python3 compatible logging.info('Writing bundle for Subject: %s', @@ -355,7 +369,8 @@ def main(): if x[0] == b'CN'][0]) for x509_object in [x for x in x509_objects - if x.get_subject() != x.get_issuer()]: + if x.get_subject() != x.get_issuer() + or args.include_root]: # Stringify subject like openssl x509 -subject x509_subject = \