Beispiel #1
0
def rotate(new_certificate_name=False,
           old_certificate_name=False,
           message=False,
           commit=False):
    new_cert = old_cert = None

    if commit:
        print("[!] Running in COMMIT mode.")

    if old_certificate_name:
        old_cert = get_by_name(old_certificate_name)

        if not old_cert:
            print("[-] No certificate found with name: {0}".format(
                old_certificate_name))
            sys.exit(1)

    if new_certificate_name:
        new_cert = get_by_name(new_certificate_name)

        if not new_cert:
            print("[-] No certificate found with name: {0}".format(
                old_certificate_name))
            sys.exit(1)

    if old_cert and new_cert:
        reissue_and_rotate(old_cert,
                           new_certificate=new_cert,
                           commit=commit,
                           message=message)
    else:
        for certificate in get_all_pending_rotation():
            reissue_and_rotate(certificate, commit=commit, message=message)
Beispiel #2
0
def rotate(new_certificate_name, old_certificate_name, commit=False):
    from lemur.certificates.service import get_by_name, reissue_certificate, get_certificate_primitives
    from lemur.endpoints.service import rotate_certificate

    old_cert = get_by_name(old_certificate_name)

    if not old_cert:
        sys.stdout.write("[-] No certificate found with name: {0}\n".format(
            old_certificate_name))
        sys.exit(1)

    if new_certificate_name:
        new_cert = get_by_name(new_certificate_name)

        if not new_cert:
            sys.stdout.write(
                "[-] No certificate found with name: {0}\n".format(
                    old_certificate_name))
            sys.exit(1)

    if commit:
        sys.stdout.write("[!] Running in COMMIT mode.\n")

    if not new_certificate_name:
        sys.stdout.write(
            "[!] No new certificate provided. Attempting to re-issue old certificate: {0}.\n"
            .format(old_certificate_name))

        details = get_certificate_primitives(old_cert)
        print_certificate_details(details)

        if commit:
            new_cert = reissue_certificate(old_cert, replace=True)
            sys.stdout.write("[+] Issued new certificate named: {0}\n".format(
                new_cert.name))

        sys.stdout.write("[+] Done! \n")

    if len(old_cert.endpoints) > 0:
        for endpoint in old_cert.endpoints:
            sys.stdout.write(
                "[+] Certificate deployed on endpoint: name:{name} dnsname:{dnsname} port:{port} type:{type}\n"
                .format(name=endpoint.name,
                        dnsname=endpoint.dnsname,
                        port=endpoint.port,
                        type=endpoint.type))
            sys.stdout.write(
                "[+] Rotating certificate from: {0} to: {1}\n".format(
                    old_certificate_name, new_cert.name))

            if commit:
                rotate_certificate(endpoint, new_cert)

            sys.stdout.write("[+] Done! \n")
    else:
        sys.stdout.write(
            "[!] Certificate not found on any existing endpoints. Nothing to rotate.\n"
        )
Beispiel #3
0
def rotate(new_certificate_name, old_certificate_name, message, commit):
    """
    Rotates a certificate and reissues it if it has not already been replaced. If it has
    been replaced, will use the replacement certificate for the rotation.
    """
    new_cert = old_cert = None

    if commit:
        print("[!] Running in COMMIT mode.")

    if old_certificate_name:
        old_cert = get_by_name(old_certificate_name)

        if not old_cert:
            print("[-] No certificate found with name: {0}".format(
                old_certificate_name))
            sys.exit(1)

    if new_certificate_name:
        new_cert = get_by_name(new_certificate_name)

        if not new_cert:
            print("[-] No certificate found with name: {0}".format(
                old_certificate_name))
            sys.exit(1)

    if old_cert and new_cert:
        try:
            reissue_and_rotate(old_cert,
                               new_certificate=new_cert,
                               commit=commit,
                               message=message)

            if commit:
                metrics.send('certificate_rotation_success', 'counter', 1)

        except Exception as e:
            current_app.logger.exception(e)

            if commit:
                metrics.send('certificate_rotation_failure', 'counter', 1)
    else:
        for certificate in get_all_pending_rotation():
            try:
                reissue_and_rotate(certificate, commit=commit, message=message)

                if commit:
                    metrics.send('certificate_rotation_success', 'counter', 1)

            except Exception as e:
                current_app.logger.exception(e)

                if commit:
                    metrics.send('certificate_rotation_failure', 'counter', 1)
Beispiel #4
0
def create_cert(name, dst_dir, export_type, dst_user, dst_priv, dst_priv_key,
                dst_host, dst_host_port):

    lem_cert = service.get_by_name(name)
    dst_dir = dst_dir + '/' + lem_cert.cn
    dst_file = 'cert.pem'
    if export_type == 'NGINX':
        dst_data = lem_cert.body + '\n' + lem_cert.chain
        chain_req = False
    elif export_type == '3File':
        dst_data = lem_cert.body
        chain_req = True
    else:
        dst_data = lem_cert.body
    copy_cert(dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port,
              dst_dir, dst_file, dst_data)
    if chain_req is True:
        dst_file = 'chain.pem'
        dst_data = lem_cert.chain_req
        copy_cert(dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port,
                  dst_dir, dst_file, dst_data)
    dst_file = 'priv.key'
    dst_data = lem_cert.private_key
    copy_cert(dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port,
              dst_dir, dst_file, dst_data)
Beispiel #5
0
def create_cert(name, dst_dir, export_type, dst_user, dst_priv, dst_priv_key,
                dst_host, dst_host_port):
    lem_cert = service.get_by_name(name)
    dst_file = 'cert.pem'
    chain_req = False

    if export_type == 'NGINX':
        # This process will result in a cert.pem file with the body and chain in a single file
        if lem_cert.chain is None:
            dst_data = lem_cert.body
        else:
            dst_data = lem_cert.body + '\n' + lem_cert.chain
        chain_req = False

    elif export_type == '3File':
        # This process will results in three files. cert.pem, priv.key, chain.pem
        dst_data = lem_cert.body
        chain_req = True

    else:
        dst_data = lem_cert.body

    copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host,
              dst_host_port, dst_dir, dst_file, dst_data)

    if chain_req is True:
        dst_file = 'chain.pem'
        dst_data = lem_cert.chain_req
        copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host,
                  dst_host_port, dst_dir, dst_file, dst_data)

    dst_file = 'priv.key'
    dst_data = lem_cert.private_key
    copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host,
              dst_host_port, dst_dir, dst_file, dst_data)
Beispiel #6
0
def sync_certificates(source, user):
    new, updated = 0, 0

    current_app.logger.debug("Retrieving certificates from {0}".format(source.label))
    s = plugins.get(source.plugin_name)
    certificates = s.get_certificates(source.options)

    for certificate in certificates:
        exists = certificate_service.get_by_name(certificate['name'])

        if not certificate.get('owner'):
            certificate['owner'] = user.email

        certificate['creator'] = user

        if not exists:
            current_app.logger.debug("Creating Certificate. Name: {name}".format(name=certificate['name']))
            certificate_create(certificate, source)
            new += 1

        else:
            current_app.logger.debug("Updating Certificate. Name: {name}".format(name=certificate['name']))
            certificate_update(exists, source)
            updated += 1

    assert len(certificates) == new + updated

    return new, updated
Beispiel #7
0
def create_cert(name, dst_dir, export_type, dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port):
    lem_cert = service.get_by_name(name)
    dst_file = 'cert.pem'
    chain_req = False

    if export_type == 'NGINX':
        # This process will result in a cert.pem file with the body and chain in a single file
        if lem_cert.chain is None:
            dst_data = lem_cert.body
        else:
            dst_data = lem_cert.body + '\n' + lem_cert.chain
        chain_req = False

    elif export_type == '3File':
        # This process will results in three files. cert.pem, priv.key, chain.pem
        dst_data = lem_cert.body
        chain_req = True

    else:
        dst_data = lem_cert.body

    copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port, dst_dir, dst_file, dst_data)

    if chain_req is True:
        dst_file = 'chain.pem'
        dst_data = lem_cert.chain_req
        copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port, dst_dir, dst_file, dst_data)

    dst_file = 'priv.key'
    dst_data = lem_cert.private_key
    copy_cert(lem_cert.cn, dst_user, dst_priv, dst_priv_key, dst_host, dst_host_port, dst_dir, dst_file, dst_data)
Beispiel #8
0
def sync_certificates(source, user):
    new, updated = 0, 0

    current_app.logger.debug("Retrieving certificates from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)
    certificates = s.get_certificates(source.options)

    for certificate in certificates:
        exists = certificate_service.get_by_name(certificate['name'])

        certificate['owner'] = user.email
        certificate['creator'] = user

        if not exists:
            current_app.logger.debug(
                "Creating Certificate. Name: {name}".format(
                    name=certificate['name']))
            certificate_create(certificate, source)
            new += 1

        else:
            current_app.logger.debug(
                "Updating Certificate. Name: {name}".format(
                    name=certificate['name']))
            certificate_update(exists, source)
            updated += 1

    assert len(certificates) == new + updated

    return new, updated
Beispiel #9
0
def test_sync_certificates_same_cert_same_name(user, source,
                                               sync_source_plugin):
    from lemur.sources.service import sync_certificates, certificate_create
    from lemur.certificates import service as cert_service
    from lemur.plugins.base import plugins

    # create an existing cert with same body
    data = {
        "name": "WildcardCert2",
        "body": WILDCARD_CERT_STR,
        "private_key": WILDCARD_CERT_KEY,
        "owner": "*****@*****.**",
        "creator": user["user"],
    }
    certificate_create(data, source)

    # sync a certificate with same body
    s = plugins.get(source.plugin_name)
    s.certificates = [
        {
            "name": "WildcardCert2",
            "body": WILDCARD_CERT_STR,
        },
    ]

    res = sync_certificates(source, user["user"])

    assert res == (0, 1, 1)
    assert cert_service.get_by_name("WildcardCert2") is not None
Beispiel #10
0
def sync_endpoints(source):
    new, updated = 0, 0
    current_app.logger.debug("Retrieving endpoints from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)

    try:
        endpoints = s.get_endpoints(source.options)
    except NotImplementedError:
        current_app.logger.warning(
            "Unable to sync endpoints for source {0} plugin has not implemented 'get_endpoints'"
            .format(source.label))
        return

    for endpoint in endpoints:
        exists = endpoint_service.get_by_dnsname(endpoint['dnsname'])

        certificate_name = endpoint.pop('certificate_name', None)
        certificate = endpoint.pop('certificate', None)

        if certificate_name:
            current_app.logger.debug(certificate_name)
            cert = cert_service.get_by_name(certificate_name)

        elif certificate:
            cert = cert_service.get_by_body(certificate['body'])
            if not cert:
                cert = cert_service.import_certificate(**certificate)

        if not cert:
            current_app.logger.error(
                "Unable to find associated certificate, be sure that certificates are sync'ed before endpoints"
            )
            continue

        endpoint['certificate'] = cert

        policy = endpoint.pop('policy')

        policy_ciphers = []
        for nc in policy['ciphers']:
            policy_ciphers.append(
                endpoint_service.get_or_create_cipher(name=nc))

        policy['ciphers'] = policy_ciphers
        endpoint['policy'] = endpoint_service.get_or_create_policy(**policy)
        endpoint['source'] = source

        if not exists:
            endpoint_service.create(**endpoint)
            new += 1

        else:
            endpoint_service.update(exists.id, **endpoint)
            updated += 1

    _disassociate_endpoints_from_source(endpoints, source)
Beispiel #11
0
    def run(self, elb_list, chain_path, cert_name, cert_prefix, description):

        for e in open(elb_list, 'r').readlines():
            elb_name, account_id, region, from_port, to_port, protocol = e.strip().split(',')

            if cert_name:
                arn = "arn:aws:iam::{0}:server-certificate/{1}".format(account_id, cert_name)

            else:
                # if no cert name is provided we need to discover it
                listeners = elb.get_listeners(account_id, region, elb_name)

                # get the listener we care about
                for listener in listeners:
                    if listener[0] == int(from_port) and listener[1] == int(to_port):
                        arn = listener[4]
                        name = get_name_from_arn(arn)
                        certificate = cert_service.get_by_name(name)
                        break
                else:
                    sys.stdout.write("[-] Could not find ELB {0}".format(elb_name))
                    continue

                if not certificate:
                    sys.stdout.write("[-] Could not find certificate {0} in Lemur".format(name))
                    continue

                dests = []
                for d in certificate.destinations:
                    dests.append({'id': d.id})

                nots = []
                for n in certificate.notifications:
                    nots.append({'id': n.id})

                new_certificate = database.clone(certificate)

                if cert_prefix:
                    new_certificate.name = "{0}-{1}".format(cert_prefix, new_certificate.name)

                new_certificate.chain = open(chain_path, 'r').read()
                new_certificate.description = "{0} - {1}".format(new_certificate.description, description)

                new_certificate = database.create(new_certificate)
                database.update_list(new_certificate, 'destinations', Destination, dests)
                database.update_list(new_certificate, 'notifications', Notification, nots)
                database.update(new_certificate)

                arn = new_certificate.get_arn(account_id)

            elb.update_listeners(account_id, region, elb_name, [(from_port, to_port, protocol, arn)], [from_port])

            sys.stdout.write("[+] Updated {0} to use {1}\n".format(elb_name, new_certificate.name))
Beispiel #12
0
    def run(self, elb_list, chain_path, cert_name, cert_prefix, description):

        for e in open(elb_list, 'r').readlines():
            elb_name, account_id, region, from_port, to_port, protocol = e.strip().split(',')

            if cert_name:
                arn = "arn:aws:iam::{0}:server-certificate/{1}".format(account_id, cert_name)

            else:
                # if no cert name is provided we need to discover it
                listeners = elb.get_listeners(account_id, region, elb_name)

                # get the listener we care about
                for listener in listeners:
                    if listener[0] == int(from_port) and listener[1] == int(to_port):
                        arn = listener[4]
                        name = get_name_from_arn(arn)
                        certificate = cert_service.get_by_name(name)
                        break
                else:
                    sys.stdout.write("[-] Could not find ELB {0}".format(elb_name))
                    continue

                if not certificate:
                    sys.stdout.write("[-] Could not find certificate {0} in Lemur".format(name))
                    continue

                dests = []
                for d in certificate.destinations:
                    dests.append({'id': d.id})

                nots = []
                for n in certificate.notifications:
                    nots.append({'id': n.id})

                new_certificate = database.clone(certificate)

                if cert_prefix:
                    new_certificate.name = "{0}-{1}".format(cert_prefix, new_certificate.name)

                new_certificate.chain = open(chain_path, 'r').read()
                new_certificate.description = "{0} - {1}".format(new_certificate.description, description)

                new_certificate = database.create(new_certificate)
                database.update_list(new_certificate, 'destinations', Destination, dests)
                database.update_list(new_certificate, 'notifications', Notification, nots)
                database.update(new_certificate)

                arn = new_certificate.get_arn(account_id)

            elb.update_listeners(account_id, region, elb_name, [(from_port, to_port, protocol, arn)], [from_port])

            sys.stdout.write("[+] Updated {0} to use {1}\n".format(elb_name, new_certificate.name))
Beispiel #13
0
def sync_endpoints(source):
    new, updated = 0, 0
    current_app.logger.debug("Retrieving endpoints from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)

    try:
        endpoints = s.get_endpoints(source.options)
    except NotImplementedError:
        current_app.logger.warning(
            "Unable to sync endpoints for source {0} plugin has not implemented 'get_endpoints'"
            .format(source.label))
        return new, updated

    for endpoint in endpoints:
        exists = endpoint_service.get_by_dnsname_and_port(
            endpoint["dnsname"], endpoint["port"])

        certificate_name = endpoint.pop("certificate_name")

        endpoint["certificate"] = certificate_service.get_by_name(
            certificate_name)

        if not endpoint["certificate"]:
            current_app.logger.error(
                "Certificate Not Found. Name: {0} Endpoint: {1}".format(
                    certificate_name, endpoint["name"]))
            continue

        policy = endpoint.pop("policy")

        policy_ciphers = []
        for nc in policy["ciphers"]:
            policy_ciphers.append(
                endpoint_service.get_or_create_cipher(name=nc))

        policy["ciphers"] = policy_ciphers
        endpoint["policy"] = endpoint_service.get_or_create_policy(**policy)
        endpoint["source"] = source

        if not exists:
            current_app.logger.debug(
                "Endpoint Created: Name: {name}".format(name=endpoint["name"]))
            endpoint_service.create(**endpoint)
            new += 1

        else:
            current_app.logger.debug("Endpoint Updated: {}".format(endpoint))
            endpoint_service.update(exists.id, **endpoint)
            updated += 1

    return new, updated
Beispiel #14
0
def sync_endpoints(source):
    new, updated = 0, 0
    current_app.logger.debug("Retrieving endpoints from {0}".format(source.label))
    s = plugins.get(source.plugin_name)

    try:
        endpoints = s.get_endpoints(source.options)
    except NotImplementedError:
        current_app.logger.warning("Unable to sync endpoints for source {0} plugin has not implemented 'get_endpoints'".format(source.label))
        return

    for endpoint in endpoints:
        exists = endpoint_service.get_by_dnsname(endpoint['dnsname'])

        certificate_name = endpoint.pop('certificate_name', None)
        certificate = endpoint.pop('certificate', None)

        if certificate_name:
            current_app.logger.debug(certificate_name)
            cert = cert_service.get_by_name(certificate_name)

        elif certificate:
            cert = cert_service.get_by_body(certificate['body'])
            if not cert:
                cert = cert_service.import_certificate(**certificate)

        if not cert:
            current_app.logger.error(
                "Unable to find associated certificate, be sure that certificates are sync'ed before endpoints")
            continue

        endpoint['certificate'] = cert

        policy = endpoint.pop('policy')

        policy_ciphers = []
        for nc in policy['ciphers']:
            policy_ciphers.append(endpoint_service.get_or_create_cipher(name=nc))

        policy['ciphers'] = policy_ciphers
        endpoint['policy'] = endpoint_service.get_or_create_policy(**policy)

        if not exists:
            endpoint_service.create(**endpoint)
            new += 1

        else:
            endpoint_service.update(exists.id, **endpoint)
            updated += 1

    _disassociate_endpoints_from_source(endpoints, source)
Beispiel #15
0
def validate_certificate(certificate_name):
    """
    Ensuring that the specified certificate exists.
    :param certificate_name:
    :return:
    """
    if certificate_name:
        cert = get_by_name(certificate_name)

        if not cert:
            print("[-] No certificate found with name: {0}".format(certificate_name))
            sys.exit(1)

        return cert
Beispiel #16
0
def validate_certificate(certificate_name):
    """
    Ensuring that the specified certificate exists.
    :param certificate_name:
    :return:
    """
    if certificate_name:
        cert = get_by_name(certificate_name)

        if not cert:
            print("[-] No certificate found with name: {0}".format(certificate_name))
            sys.exit(1)

        return cert
Beispiel #17
0
def sync_certificates(source, user):
    new, updated = 0, 0

    current_app.logger.debug("Retrieving certificates from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)
    certificates = s.get_certificates(source.options)

    for certificate in certificates:
        exists = False

        if certificate.get("search", None):
            conditions = certificate.pop("search")
            exists = certificate_service.get_by_attributes(conditions)

        if not exists and certificate.get("name"):
            result = certificate_service.get_by_name(certificate["name"])
            if result:
                exists = [result]

        if not exists and certificate.get("serial"):
            exists = certificate_service.get_by_serial(certificate["serial"])

        if not exists:
            cert = parse_certificate(certificate["body"])
            matching_serials = certificate_service.get_by_serial(serial(cert))
            exists = find_matching_certificates_by_hash(cert, matching_serials)

        if not certificate.get("owner"):
            certificate["owner"] = user.email

        certificate["creator"] = user
        exists = [x for x in exists if x]

        if not exists:
            certificate_create(certificate, source)
            new += 1

        else:
            for e in exists:
                if certificate.get("external_id"):
                    e.external_id = certificate["external_id"]
                if certificate.get("authority_id"):
                    e.authority_id = certificate["authority_id"]
                certificate_update(e, source)
                updated += 1

    return new, updated
Beispiel #18
0
def sync_certificates(source, user):
    new, updated = 0, 0

    current_app.logger.debug("Retrieving certificates from {0}".format(source.label))
    s = plugins.get(source.plugin_name)
    certificates = s.get_certificates(source.options)

    for certificate in certificates:
        exists = False

        if certificate.get('search', None):
            conditions = certificate.pop('search')
            exists = certificate_service.get_by_attributes(conditions)

        if not exists and certificate.get('name'):
            result = certificate_service.get_by_name(certificate['name'])
            if result:
                exists = [result]

        if not exists and certificate.get('serial'):
            exists = certificate_service.get_by_serial(certificate['serial'])

        if not exists:
            cert = parse_certificate(certificate['body'])
            matching_serials = certificate_service.get_by_serial(serial(cert))
            exists = find_matching_certificates_by_hash(cert, matching_serials)

        if not certificate.get('owner'):
            certificate['owner'] = user.email

        certificate['creator'] = user
        exists = [x for x in exists if x]

        if not exists:
            certificate_create(certificate, source)
            new += 1

        else:
            for e in exists:
                if certificate.get('external_id'):
                    e.external_id = certificate['external_id']
                if certificate.get('authority_id'):
                    e.authority_id = certificate['authority_id']
                certificate_update(e, source)
                updated += 1

    return new, updated
Beispiel #19
0
def sync_endpoints(source):
    new, updated = 0, 0
    current_app.logger.debug("Retrieving endpoints from {0}".format(source.label))
    s = plugins.get(source.plugin_name)

    try:
        endpoints = s.get_endpoints(source.options)
    except NotImplementedError:
        current_app.logger.warning("Unable to sync endpoints for source {0} plugin has not implemented 'get_endpoints'".format(source.label))
        return new, updated

    for endpoint in endpoints:
        exists = endpoint_service.get_by_dnsname_and_port(endpoint['dnsname'], endpoint['port'])

        certificate_name = endpoint.pop('certificate_name')

        endpoint['certificate'] = certificate_service.get_by_name(certificate_name)

        if not endpoint['certificate']:
            current_app.logger.error(
                "Certificate Not Found. Name: {0} Endpoint: {1}".format(certificate_name, endpoint['name']))
            continue

        policy = endpoint.pop('policy')

        policy_ciphers = []
        for nc in policy['ciphers']:
            policy_ciphers.append(endpoint_service.get_or_create_cipher(name=nc))

        policy['ciphers'] = policy_ciphers
        endpoint['policy'] = endpoint_service.get_or_create_policy(**policy)
        endpoint['source'] = source

        if not exists:
            current_app.logger.debug("Endpoint Created: Name: {name}".format(name=endpoint['name']))
            endpoint_service.create(**endpoint)
            new += 1

        else:
            current_app.logger.debug("Endpoint Updated: {}".format(endpoint))
            endpoint_service.update(exists.id, **endpoint)
            updated += 1

    return new, updated
Beispiel #20
0
def reissue(old_certificate_name, commit=False):
    old_cert = get_by_name(old_certificate_name)

    if not old_cert:
        print("[-] No certificate found with name: {0}".format(
            old_certificate_name))
        sys.exit(1)

    if commit:
        print("[!] Running in COMMIT mode.")

    details = get_certificate_primitives(old_cert)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(old_cert, replace=True)
        print("[+] Issued new certificate named: {0}".format(new_cert.name))

    print("[+] Done!")
Beispiel #21
0
def clean(source):
    s = plugins.get(source.plugin_name)

    try:
        certificates = s.clean(source.options)
    except NotImplementedError:
        current_app.logger.warning(
            "Cannot clean source: {0}, source plugin does not implement 'clean()'"
            .format(source.label))
        return

    for certificate in certificates:
        cert = cert_service.get_by_name(certificate)

        if cert:
            current_app.logger.warning(
                "Removed {0} from source {1} during cleaning".format(
                    cert.name, source.label))
            cert.sources.remove(source)
Beispiel #22
0
def find_cert(certificate):
    if not certificate.get("name"):
        # certificate must have a name
        return False, 0

    matched_cert = certificate_service.get_by_name(certificate["name"])
    if not matched_cert:
        # no cert with the same name found
        return False, 0

    # check hash of matched cert
    cert = parse_certificate(certificate["body"])
    exists = find_matching_certificates_by_hash(cert, [matched_cert])
    if not exists:
        raise Exception(
            f"A certificate with the same name {certificate['name']} already exists with a different hash"
        )

    return exists, len(exists)
Beispiel #23
0
def sync_certificates(source, user):
    new, updated = 0, 0

    current_app.logger.debug("Retrieving certificates from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)
    certificates = s.get_certificates(source.options)

    for certificate in certificates:
        exists = False
        if certificate.get('name'):
            result = certificate_service.get_by_name(certificate['name'])
            if result:
                exists = [result]

        if not exists and certificate.get('serial'):
            exists = certificate_service.get_by_serial(certificate['serial'])

        if not exists:
            cert = parse_certificate(certificate['body'])
            exists = certificate_service.get_by_serial(serial(cert))

        if not certificate.get('owner'):
            certificate['owner'] = user.email

        certificate['creator'] = user
        exists = [x for x in exists if x]

        if not exists:
            certificate_create(certificate, source)
            new += 1

        else:
            for e in exists:
                if certificate.get('external_id'):
                    e.external_id = certificate['external_id']
                if certificate.get('authority_id'):
                    e.authority_id = certificate['authority_id']
                certificate_update(e, source)
                updated += 1

    return new, updated
Beispiel #24
0
def clean(source):
    s = plugins.get(source.plugin_name)

    try:
        certificates = s.clean(source.options)
    except NotImplemented:
        current_app.logger.warning("Cannot clean source: {0}, source plugin does not implement 'clean()'".format(
            source.label
        ))
        return

    for certificate in certificates:
        current_app.logger.debug(certificate)
        cert = cert_service.get_by_name(certificate)

        if cert:
            current_app.logger.warning("Removed {0} from source {1} during cleaning".format(
                cert.name,
                source.label
            ))
            cert.sources.remove(source)
Beispiel #25
0
def reissue(old_certificate_name, commit=False):
    from lemur.certificates.service import get_by_name, reissue_certificate, get_certificate_primitives

    old_cert = get_by_name(old_certificate_name)

    if not old_cert:
        sys.stdout.write("[-] No certificate found with name: {0}\n".format(
            old_certificate_name))
        sys.exit(1)

    if commit:
        sys.stdout.write("[!] Running in COMMIT mode.\n")

    details = get_certificate_primitives(old_cert)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(old_cert, replace=True)
        sys.stdout.write("[+] Issued new certificate named: {0}\n".format(
            new_cert.name))

    sys.stdout.write("[+] Done! \n")
Beispiel #26
0
def find_cert(certificate):
    updated_by_hash = 0
    exists = False

    if certificate.get("search", None):
        conditions = certificate.pop("search")
        exists = certificate_service.get_by_attributes(conditions)

    if not exists and certificate.get("name"):
        result = certificate_service.get_by_name(certificate["name"])
        if result:
            exists = [result]

    if not exists and certificate.get("serial"):
        exists = certificate_service.get_by_serial(certificate["serial"])

    if not exists:
        cert = parse_certificate(certificate["body"])
        matching_serials = certificate_service.get_by_serial(serial(cert))
        exists = find_matching_certificates_by_hash(cert, matching_serials)
        updated_by_hash += 1

    exists = [x for x in exists if x]
    return exists, updated_by_hash
Beispiel #27
0
def reissue(old_certificate_name, validity_start, validity_end, commit):
    """
    Reissues certificate with the same parameters as it was originally issued with.
    If not time period is provided, reissues certificate as valid from today to
    today + length of original.
    """
    old_cert = get_by_name(old_certificate_name)

    if not old_cert:
        print("[-] No certificate found with name: {0}".format(
            old_certificate_name))
        sys.exit(1)

    if commit:
        print("[!] Running in COMMIT mode.")

    details = get_certificate_primitives(old_cert)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(old_cert, replace=True)
        print("[+] Issued new certificate named: {0}".format(new_cert.name))

    print("[+] Done!")
Beispiel #28
0
def sync_endpoints(source):
    new, updated, updated_by_hash = 0, 0, 0
    current_app.logger.debug("Retrieving endpoints from {0}".format(
        source.label))
    s = plugins.get(source.plugin_name)

    try:
        endpoints = s.get_endpoints(source.options)
    except NotImplementedError:
        current_app.logger.warning(
            "Unable to sync endpoints for source {0} plugin has not implemented 'get_endpoints'"
            .format(source.label))
        return new, updated, updated_by_hash

    for endpoint in endpoints:
        exists = endpoint_service.get_by_dnsname_and_port(
            endpoint["dnsname"], endpoint["port"])

        certificate_name = endpoint.pop("certificate_name")

        endpoint["certificate"] = certificate_service.get_by_name(
            certificate_name)

        # if get cert by name failed, we attempt a search via serial number and hash comparison
        # and link the endpoint certificate to Lemur certificate
        if not endpoint["certificate"]:
            certificate_attached_to_endpoint = None
            try:
                certificate_attached_to_endpoint = s.get_certificate_by_name(
                    certificate_name, source.options)
            except NotImplementedError:
                current_app.logger.warning(
                    "Unable to describe server certificate for endpoints in source {0}:"
                    " plugin has not implemented 'get_certificate_by_name'".
                    format(source.label))
                sentry.captureException()

            if certificate_attached_to_endpoint:
                lemur_matching_cert, updated_by_hash_tmp = find_cert(
                    certificate_attached_to_endpoint)
                updated_by_hash += updated_by_hash_tmp

                if lemur_matching_cert:
                    endpoint["certificate"] = lemur_matching_cert[0]

                if len(lemur_matching_cert) > 1:
                    current_app.logger.error(
                        "Too Many Certificates Found{0}. Name: {1} Endpoint: {2}"
                        .format(len(lemur_matching_cert), certificate_name,
                                endpoint["name"]))
                    metrics.send("endpoint.certificate.conflict",
                                 "gauge",
                                 len(lemur_matching_cert),
                                 metric_tags={
                                     "cert":
                                     certificate_name,
                                     "endpoint":
                                     endpoint["name"],
                                     "acct":
                                     s.get_option("accountNumber",
                                                  source.options)
                                 })

        if not endpoint["certificate"]:
            current_app.logger.error({
                "message":
                "Certificate Not Found",
                "certificate_name":
                certificate_name,
                "endpoint_name":
                endpoint["name"],
                "dns_name":
                endpoint.get("dnsname"),
                "account":
                s.get_option("accountNumber", source.options),
            })

            metrics.send("endpoint.certificate.not.found",
                         "counter",
                         1,
                         metric_tags={
                             "cert": certificate_name,
                             "endpoint": endpoint["name"],
                             "acct": s.get_option("accountNumber",
                                                  source.options),
                             "dnsname": endpoint.get("dnsname")
                         })
            continue

        policy = endpoint.pop("policy")

        policy_ciphers = []
        for nc in policy["ciphers"]:
            policy_ciphers.append(
                endpoint_service.get_or_create_cipher(name=nc))

        policy["ciphers"] = policy_ciphers
        endpoint["policy"] = endpoint_service.get_or_create_policy(**policy)
        endpoint["source"] = source

        if not exists:
            current_app.logger.debug(
                "Endpoint Created: Name: {name}".format(name=endpoint["name"]))
            endpoint_service.create(**endpoint)
            new += 1

        else:
            current_app.logger.debug("Endpoint Updated: {}".format(endpoint))
            endpoint_service.update(exists.id, **endpoint)
            updated += 1

    return new, updated, updated_by_hash
Beispiel #29
0
def test_get_by_name(session, certificate):
    from lemur.certificates.service import get_by_name

    found = get_by_name(certificate.name)

    assert found
Beispiel #30
0
def test_get_by_name(session, certificate):
    from lemur.certificates.service import get_by_name

    found = get_by_name(certificate.name)

    assert found