Exemple #1
0
def test_get_certificate_primitives(certificate):
    from lemur.certificates.service import get_certificate_primitives

    names = [x509.DNSName(x.name) for x in certificate.domains]

    data = {
        'common_name': certificate.cn,
        'owner': certificate.owner,
        'authority': certificate.authority,
        'description': certificate.description,
        'extensions': {
            'sub_alt_names': x509.SubjectAlternativeName(names)
        },
        'destinations': [],
        'roles': [],
        'validity_end': arrow.get(2021, 5, 7),
        'validity_start': arrow.get(2016, 10, 30),
        'country': 'US',
        'location': 'A place',
        'organization': 'Example',
        'organizational_unit': 'Operations',
        'state': 'CA'
    }

    with freeze_time(datetime.date(year=2016, month=10, day=30)):
        primitives = get_certificate_primitives(certificate)
        assert len(primitives) == 23
Exemple #2
0
def test_get_certificate_primitives(certificate):
    from lemur.certificates.service import get_certificate_primitives

    names = [x509.DNSName(x.name) for x in certificate.domains]

    data = {
        'common_name': certificate.cn,
        'owner': certificate.owner,
        'authority': certificate.authority,
        'description': certificate.description,
        'extensions': {
            'sub_alt_names': x509.SubjectAlternativeName(names)
        },
        'destinations': [],
        'roles': [],
        'validity_end': arrow.get(2021, 5, 7),
        'validity_start': arrow.get(2016, 10, 30),
        'country': 'US',
        'location': 'A place',
        'organization': 'Example',
        'organizational_unit': 'Operations',
        'state': 'CA'
    }

    with freeze_time(datetime.date(year=2016, month=10, day=30)):
        primitives = get_certificate_primitives(certificate)
        assert len(primitives) == 23
Exemple #3
0
def request_reissue(certificate, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param commit:
    :return:
    """
    status = FAILURE_METRIC_STATUS
    try:
        print("[+] {0} is eligible for re-issuance".format(certificate.name))

        # set the lemur identity for all cli commands
        identity_changed.send(current_app._get_current_object(), identity=Identity(1))

        details = get_certificate_primitives(certificate)
        print_certificate_details(details)

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

        status = SUCCESS_METRIC_STATUS

    except Exception as e:
        sentry.captureException()
        print(
            "[!] Failed to reissue certificates. Reason: {}".format(
                e
            )
        )

    metrics.send('certificate_reissue', 'counter', 1, metric_tags={'status': status})
Exemple #4
0
def request_reissue(certificate, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param commit:
    :return:
    """
    status = FAILURE_METRIC_STATUS
    try:
        print("[+] {0} is eligible for re-issuance".format(certificate.name))

        # set the lemur identity for all cli commands
        identity_changed.send(current_app._get_current_object(), identity=Identity(1))

        details = get_certificate_primitives(certificate)
        print_certificate_details(details)

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

        status = SUCCESS_METRIC_STATUS

    except Exception as e:
        sentry.captureException()
        current_app.logger.exception("Error reissuing certificate.", exc_info=True)
        print(
            "[!] Failed to reissue certificates. Reason: {}".format(
                e
            )
        )

    metrics.send('certificate_reissue', 'counter', 1, metric_tags={'status': status})
Exemple #5
0
def certificate_reissue():
    """
    This celery task reissues certificates which are pending reissue
    :return:
    """
    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    task_id = None
    if celery.current_task:
        task_id = celery.current_task.request.id

    log_data = {
        "function": function,
        "message": "reissuing certificates",
        "task_id": task_id,
    }

    if task_id and is_task_active(function, task_id, None):
        log_data["message"] = "Skipping task: Task is already active"
        current_app.logger.debug(log_data)
        return

    current_app.logger.debug(log_data)

    # set the lemur identity
    identity_changed.send(current_app._get_current_object(),
                          identity=Identity(1))

    for certificate in certificate_service.get_all_pending_reissue():
        log_data["message"] = f"{certificate.name} is eligible for re-issuance"
        current_app.logger.info(log_data)

        details = certificate_service.get_certificate_primitives(certificate)
        details, errors = CertificateOutputSchema().dump(details)
        current_app.logger.info(
            "Re-issuing certificate",
            extra=dict(
                certificate={
                    "common_name":
                    details["commonName"],
                    "sans":
                    ",".join(x["value"] for x in details["extensions"]
                             ["subAltNames"]["names"]),
                    "authority_name":
                    details["authority"]["name"],
                    "validity_start":
                    details["validityStart"],
                    "validity_end":
                    details["validityEnd"],
                }),
        )

        new_cert = certificate_service.reissue_certificate(certificate,
                                                           replace=True)
        log_data["message"] = f"New certificate named:{new_cert.name}"
        current_app.logger.info(log_data)

    log_data["message"] = "reissuance completed"
    current_app.logger.info(log_data)
    metrics.send(f"{function}.success", "counter", 1)
    return log_data
Exemple #6
0
def test_get_certificate_primitives(certificate):
    from lemur.certificates.service import get_certificate_primitives

    names = [{
        'name_type': 'DNSName',
        'value': x.name
    } for x in certificate.domains]

    data = {
        'common_name': certificate.cn,
        'owner': certificate.owner,
        'authority': certificate.authority,
        'description': certificate.description,
        'extensions': {
            'sub_alt_names': {
                'names': names
            }
        },
        'destinations': [],
        'roles': [],
        'validity_end': datetime.date(year=2021, month=5, day=7),
        'validity_start': datetime.date(year=2016, month=10, day=30)
    }

    with freeze_time(datetime.date(year=2016, month=10, day=30)):
        primitives = get_certificate_primitives(certificate)
        assert data == primitives
Exemple #7
0
def test_get_certificate_primitives(certificate):
    from lemur.certificates.service import get_certificate_primitives

    names = [x509.DNSName(x.name) for x in certificate.domains]

    with freeze_time(datetime.date(year=2016, month=10, day=30)):
        primitives = get_certificate_primitives(certificate)
        assert len(primitives) == 26
Exemple #8
0
def test_get_certificate_primitives(certificate):
    from lemur.certificates.service import get_certificate_primitives

    names = [x509.DNSName(x.name) for x in certificate.domains]

    with freeze_time(datetime.date(year=2016, month=10, day=30)):
        primitives = get_certificate_primitives(certificate)
        assert len(primitives) == 26
Exemple #9
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"
        )
Exemple #10
0
def reissue_and_rotate(old_certificate,
                       new_certificate=None,
                       commit=False,
                       message=False):
    if not new_certificate:
        # we don't want to re-issue if it's already been replaced
        if not old_certificate.replaced:
            details = get_certificate_primitives(old_certificate)
            print_certificate_details(details)

            if commit:
                new_certificate = reissue_certificate(old_certificate,
                                                      replace=True)
                print("[+] Issued new certificate named: {0}".format(
                    new_certificate.name))
                time.sleep(10)
                print(
                    "[!] Sleeping to ensure that certificate propagates before rotating."
                )
            else:
                new_certificate = old_certificate

            print("[+] Done!")

        else:
            if len(old_certificate.replaced) > 1:
                raise Exception(
                    "Unable to rotate certificate based on replacement, found more than one!"
                )
            else:
                new_certificate = old_certificate.replaced[0]
                print("[!] Certificate has been replaced by: {0}".format(
                    old_certificate.replaced[0].name))

    if len(old_certificate.endpoints) > 0:
        for endpoint in old_certificate.endpoints:
            print(
                "[+] Certificate deployed on endpoint: name:{name} dnsname:{dnsname} port:{port} type:{type}"
                .format(name=endpoint.name,
                        dnsname=endpoint.dnsname,
                        port=endpoint.port,
                        type=endpoint.type))
            print("[+] Rotating certificate from: {0} to: {1}".format(
                old_certificate.name, new_certificate.name))

            if commit:
                rotate_certificate(endpoint, new_certificate)

            print("[+] Done!")

    if message:
        send_rotation_notification(old_certificate)
Exemple #11
0
def request_reissue(certificate, notify, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param notify:
    :param commit:
    :return:
    """
    status = FAILURE_METRIC_STATUS
    notify = notify and certificate.notify
    try:
        print("[+] {0} is eligible for re-issuance".format(certificate.name))

        # set the lemur identity for all cli commands
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(1))

        details = get_certificate_primitives(certificate)
        print_certificate_details(details)

        if commit:
            new_cert = reissue_certificate(certificate,
                                           notify=notify,
                                           replace=True)
            print("[+] New certificate named: {0}".format(new_cert.name))
            if notify and isinstance(
                    new_cert,
                    Certificate):  # let celery handle PendingCertificates
                send_reissue_no_endpoints_notification(certificate, new_cert)

        status = SUCCESS_METRIC_STATUS

    except Exception as e:
        capture_exception(extra={"certificate_name": str(certificate.name)})
        current_app.logger.exception(
            f"Error reissuing certificate: {certificate.name}", exc_info=True)
        print(
            f"[!] Failed to reissue certificate: {certificate.name}. Reason: {e}"
        )
        if notify:
            send_reissue_failed_notification(certificate)

    metrics.send(
        "certificate_reissue",
        "counter",
        1,
        metric_tags={
            "status": status,
            "certificate": certificate.name
        },
    )
Exemple #12
0
def request_reissue(certificate, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param commit:
    :return:
    """
    details = get_certificate_primitives(certificate)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(certificate, replace=True)
        metrics.send('certificate_reissue_success', 'counter', 1)
        print("[+] New certificate named: {0}".format(new_cert.name))
Exemple #13
0
def request_reissue(certificate, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param commit:
    :return:
    """
    details = get_certificate_primitives(certificate)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(certificate, replace=True)
        metrics.send('certificate_reissue_success', 'counter', 1)
        print("[+] New certificate named: {0}".format(new_cert.name))
Exemple #14
0
def request_reissue(certificate, commit):
    """
    Reissuing certificate and handles any exceptions.
    :param certificate:
    :param commit:
    :return:
    """
    # set the lemur identity for all cli commands
    identity_changed.send(current_app._get_current_object(), identity=Identity(1))

    details = get_certificate_primitives(certificate)
    print_certificate_details(details)

    if commit:
        new_cert = reissue_certificate(certificate, replace=True)
        metrics.send('certificate_reissue_success', 'counter', 1)
        print("[+] New certificate named: {0}".format(new_cert.name))
Exemple #15
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!")
Exemple #16
0
def reissue_and_rotate(old_certificate,
                       new_certificate=None,
                       commit=False,
                       message=False):
    if not new_certificate:
        # we don't want to re-issue if it's already been replaced
        if not old_certificate.replaced:
            details = get_certificate_primitives(old_certificate)
            print_certificate_details(details)

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

            print("[+] Done!")

        else:
            new_certificate = old_certificate.replaced
            print("[!] Certificate has been replaced by: {0}".format(
                old_certificate.replaced.name))

    if len(old_certificate.endpoints) > 0:
        for endpoint in old_certificate.endpoints:
            print(
                "[+] Certificate deployed on endpoint: name:{name} dnsname:{dnsname} port:{port} type:{type}"
                .format(name=endpoint.name,
                        dnsname=endpoint.dnsname,
                        port=endpoint.port,
                        type=endpoint.type))
            print("[+] Rotating certificate from: {0} to: {1}".format(
                old_certificate.name, new_certificate.name))

            if commit:
                rotate_certificate(endpoint, new_certificate)

            print("[+] Done!")

    if message:
        send_rotation_notification(old_certificate)
Exemple #17
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")
Exemple #18
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!")