Beispiel #1
0
def test_send_expiring_deployed_certificate_notifications():
    from lemur.domains.models import Domain
    from lemur.notifications.messaging import send_expiring_deployed_certificate_notifications
    verify_sender_email()

    # three certs with ports, one cert with no ports
    cert_1 = create_cert_that_expires_in_days(
        10,
        domains=[Domain(name='domain1.com')],
        owner='*****@*****.**')
    cert_1.certificate_associations[0].ports = [1234]
    cert_2 = create_cert_that_expires_in_days(
        10,
        domains=[Domain(name='domain1.com')],
        owner='*****@*****.**')
    cert_2.certificate_associations[0].ports = [1234, 12345]
    cert_3 = create_cert_that_expires_in_days(
        10,
        domains=[Domain(name='domain1.com')],
        owner='*****@*****.**')
    cert_3.certificate_associations[0].ports = [1234, 12345, 12456]
    cert_4 = create_cert_that_expires_in_days(
        10,
        domains=[Domain(name='domain1.com')],
        owner='*****@*****.**')
    cert_4.certificate_associations[0].ports = []

    certificates = get_expiring_deployed_certificates([]).items()
    assert send_expiring_deployed_certificate_notifications(certificates) == (
        3, 0)  # 3 certs with ports
Beispiel #2
0
def test_create_name(client):
    from lemur.common.defaults import certificate_name
    from datetime import datetime
    from lemur.domains.models import Domain

    assert (certificate_name(
        "example.com",
        "Example Inc,",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2015, 5, 12, 0, 0, 0),
        False,
    ) == "example.com-ExampleInc-20150507-20150512")
    assert (certificate_name(
        "example.com",
        "Example Inc,",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2015, 5, 12, 0, 0, 0),
        True,
    ) == "SAN-example.com-ExampleInc-20150507-20150512")
    assert (certificate_name(
        "xn--mnchen-3ya.de",
        "Vertrauenswürdig Autorität",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2015, 5, 12, 0, 0, 0),
        False,
    ) == "xn--mnchen-3ya.de-VertrauenswurdigAutoritat-20150507-20150512")
    assert (certificate_name(
        "selfie.example.org",
        "<selfsigned>",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2025, 5, 12, 13, 37, 0),
        False,
    ) == "selfie.example.org-selfsigned-20150507-20250512")
    assert (certificate_name(
        "selfie.example.org",
        "<selfsigned>",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2025, 5, 12, 13, 37, 0),
        False,
        domains=[Domain(name='san-example')],
    ) == "selfie.example.org-selfsigned-20150507-20250512")
    assert (certificate_name(
        "",
        "<selfsigned>",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2025, 5, 12, 13, 37, 0),
        False,
        domains=[Domain(name='san-example')],
    ) == "san-example-selfsigned-20150507-20250512")
    assert (certificate_name(
        "",
        "<selfsigned>",
        datetime(2015, 5, 7, 0, 0, 0),
        datetime(2025, 5, 12, 13, 37, 0),
        True,
        domains=[Domain(name='san1'), Domain(name='san2')],
    ) == "SAN-san1-selfsigned-20150507-20250512")
Beispiel #3
0
def test_identify_and_persist_expiring_deployed_certificates():
    from lemur.domains.models import Domain
    """
    This test spins up three local servers, each serving the same default test cert with a non-matching CN/SANs.
    The logic to check if a cert is still deployed ignores certificate validity; all it needs to know is whether
    the certificate currently deployed at the cert's associated domain has the same serial number as the one in
    Lemur's DB. The expiration check is done using the date in Lemur's DB, and is not parsed from the actual deployed
    certificate - so we can get away with using a totally unrelated cert, as long as the serial number matches.
    In this test, the serial number is always the same, since it's parsed from the hardcoded test cert.
    """

    # one non-expiring cert, two expiring certs, and one cert that doesn't match a running server
    cert_1 = create_cert_that_expires_in_days(
        180,
        domains=[Domain(name='localhost')],
        owner='*****@*****.**')
    cert_2 = create_cert_that_expires_in_days(
        10, domains=[Domain(name='localhost')], owner='*****@*****.**')
    cert_3 = create_cert_that_expires_in_days(
        10, domains=[Domain(name='localhost')], owner='*****@*****.**')
    cert_4 = create_cert_that_expires_in_days(
        10,
        domains=[Domain(name='not-localhost')],
        owner='*****@*****.**')

    # test certs are all hardcoded with the same body/chain so we don't need to use the created cert here
    cert_file_data = SAN_CERT_STR + INTERMEDIATE_CERT_STR + ROOTCA_CERT_STR + SAN_CERT_KEY
    f = NamedTemporaryFile(suffix='.pem', delete=True)
    try:
        f.write(cert_file_data.encode('utf-8'))
        server_1 = run_server(65521, f.name)
        server_2 = run_server(65522, f.name)
        server_3 = run_server(65523, f.name)
        if not (server_1.is_alive() and server_2.is_alive()
                and server_3.is_alive()):
            fail('Servers not alive, test cannot proceed')

        for c in [cert_1, cert_2, cert_3, cert_4]:
            assert len(c.certificate_associations) == 1
            for ca in c.certificate_associations:
                assert ca.ports is None
        identify_and_persist_expiring_deployed_certificates()
        for c in [cert_1, cert_4]:
            assert len(c.certificate_associations) == 1
            for ca in c.certificate_associations:
                assert ca.ports is None
        for c in [cert_2, cert_3]:
            assert len(c.certificate_associations) == 1
            for ca in c.certificate_associations:
                assert ca.ports == [65521, 65522, 65523]
    finally:
        f.close()  # close file (which also deletes it)
Beispiel #4
0
    def __init__(self, **kwargs):
        cert = defaults.parse_certificate(kwargs['body'])

        self.issuer = defaults.issuer(cert)
        self.cn = defaults.common_name(cert)
        self.san = defaults.san(cert)
        self.not_before = defaults.not_before(cert)
        self.not_after = defaults.not_after(cert)

        # when destinations are appended they require a valid name.
        if kwargs.get('name'):
            self.name = kwargs['name']
        else:
            self.name = get_or_increase_name(
                defaults.certificate_name(self.cn, self.issuer,
                                          self.not_before, self.not_after,
                                          self.san))

        self.owner = kwargs['owner']
        self.body = kwargs['body']
        self.private_key = kwargs.get('private_key')
        self.chain = kwargs.get('chain')
        self.destinations = kwargs.get('destinations', [])
        self.notifications = kwargs.get('notifications', [])
        self.description = kwargs.get('description')
        self.roles = list(set(kwargs.get('roles', [])))
        self.replaces = kwargs.get('replacements', [])
        self.signing_algorithm = defaults.signing_algorithm(cert)
        self.bits = defaults.bitstrength(cert)
        self.serial = defaults.serial(cert)

        for domain in defaults.domains(cert):
            self.domains.append(Domain(name=domain))
Beispiel #5
0
    def __init__(self, **kwargs):
        self.body = kwargs["body"].strip()
        cert = self.parsed_cert

        self.issuer = defaults.issuer(cert)
        self.cn = defaults.common_name(cert)
        self.san = defaults.san(cert)
        self.not_before = defaults.not_before(cert)
        self.not_after = defaults.not_after(cert)
        self.serial = defaults.serial(cert)

        self.owner = kwargs["owner"]

        if kwargs.get("private_key"):
            self.private_key = kwargs["private_key"].strip()

        if kwargs.get("chain"):
            self.chain = kwargs["chain"].strip()

        if kwargs.get("csr"):
            self.csr = kwargs["csr"].strip()

        self.notify = kwargs.get("notify", True)
        self.notifications = kwargs.get("notifications", [])
        self.description = kwargs.get("description")
        self.roles = list(set(kwargs.get("roles", [])))
        self.replaces = kwargs.get("replaces", [])
        self.rotation = kwargs.get("rotation")
        self.rotation_policy = kwargs.get("rotation_policy")
        self.key_type = kwargs.get("key_type")
        self.signing_algorithm = defaults.signing_algorithm(cert)
        self.bits = defaults.bitstrength(cert)
        self.external_id = kwargs.get("external_id")
        self.authority_id = kwargs.get("authority_id")
        self.dns_provider_id = kwargs.get("dns_provider_id")

        for domain in defaults.domains(cert):
            self.domains.append(Domain(name=domain))

        # when destinations are appended they require a valid name
        # do not attempt to modify self.destinations before this step
        if kwargs.get("name"):
            self.name = get_or_increase_name(
                defaults.text_to_slug(kwargs["name"]), self.serial)
        else:
            self.name = get_or_increase_name(
                defaults.certificate_name(self.cn, self.issuer,
                                          self.not_before, self.not_after,
                                          self.san, self.domains),
                self.serial,
            )

        self.destinations = kwargs.get("destinations", [])

        # Check integrity before saving anything into the database.
        # For user-facing API calls, validation should also be done in schema validators.
        self.check_integrity()
Beispiel #6
0
def create(name, sensitive):
    """
    Create a new domain

    :param name:
    :param sensitive:
    :return:
    """
    domain = Domain(name=name, sensitive=sensitive)
    return database.create(domain)
Beispiel #7
0
    def __init__(self, **kwargs):
        self.body = kwargs['body'].strip()
        cert = self.parsed_cert

        self.issuer = defaults.issuer(cert)
        self.cn = defaults.common_name(cert)
        self.san = defaults.san(cert)
        self.not_before = defaults.not_before(cert)
        self.not_after = defaults.not_after(cert)
        self.serial = defaults.serial(cert)

        # when destinations are appended they require a valid name.
        if kwargs.get('name'):
            self.name = get_or_increase_name(
                defaults.text_to_slug(kwargs['name']), self.serial)
        else:
            self.name = get_or_increase_name(
                defaults.certificate_name(self.cn, self.issuer,
                                          self.not_before, self.not_after,
                                          self.san), self.serial)

        self.owner = kwargs['owner']

        if kwargs.get('private_key'):
            self.private_key = kwargs['private_key'].strip()

        if kwargs.get('chain'):
            self.chain = kwargs['chain'].strip()

        if kwargs.get('csr'):
            self.csr = kwargs['csr'].strip()

        self.notify = kwargs.get('notify', True)
        self.destinations = kwargs.get('destinations', [])
        self.notifications = kwargs.get('notifications', [])
        self.description = kwargs.get('description')
        self.roles = list(set(kwargs.get('roles', [])))
        self.replaces = kwargs.get('replaces', [])
        self.rotation = kwargs.get('rotation')
        self.rotation_policy = kwargs.get('rotation_policy')
        self.signing_algorithm = defaults.signing_algorithm(cert)
        self.bits = defaults.bitstrength(cert)
        self.external_id = kwargs.get('external_id')
        self.authority_id = kwargs.get('authority_id')
        self.dns_provider_id = kwargs.get('dns_provider_id')

        for domain in defaults.domains(cert):
            self.domains.append(Domain(name=domain))

        # Check integrity before saving anything into the database.
        # For user-facing API calls, validation should also be done in schema validators.
        self.check_integrity()
Beispiel #8
0
def test_certificate_sensitive_name(client, authority, session, logged_in_user):
    """The CN is disallowed by 'sensitive' flag on Domain model."""
    from lemur.certificates.schemas import CertificateInputSchema
    input_data = {
        'commonName': 'sensitive.example.com',
        'owner': '*****@*****.**',
        'authority': {'id': authority.id},
        'description': 'testtestest',
        'validityStart': '2020-01-01T00:00:00',
        'validityEnd': '2020-01-01T00:00:01',
    }
    session.add(Domain(name='sensitive.example.com', sensitive=True))

    data, errors = CertificateInputSchema().load(input_data)
    assert errors['common_name'][0].startswith("Domain sensitive.example.com has been marked as sensitive")
Beispiel #9
0
    def __init__(self, **kwargs):
        cert = lemur.common.utils.parse_certificate(kwargs['body'])

        self.issuer = defaults.issuer(cert)
        self.cn = defaults.common_name(cert)
        self.san = defaults.san(cert)
        self.not_before = defaults.not_before(cert)
        self.not_after = defaults.not_after(cert)
        self.serial = defaults.serial(cert)

        # when destinations are appended they require a valid name.
        if kwargs.get('name'):
            self.name = get_or_increase_name(
                defaults.text_to_slug(kwargs['name']), self.serial)
        else:
            self.name = get_or_increase_name(
                defaults.certificate_name(self.cn, self.issuer,
                                          self.not_before, self.not_after,
                                          self.san), self.serial)

        self.owner = kwargs['owner']
        self.body = kwargs['body'].strip()

        if kwargs.get('private_key'):
            self.private_key = kwargs['private_key'].strip()

        if kwargs.get('chain'):
            self.chain = kwargs['chain'].strip()

        self.notify = kwargs.get('notify', True)
        self.destinations = kwargs.get('destinations', [])
        self.notifications = kwargs.get('notifications', [])
        self.description = kwargs.get('description')
        self.roles = list(set(kwargs.get('roles', [])))
        self.replaces = kwargs.get('replaces', [])
        self.rotation = kwargs.get('rotation')
        self.rotation_policy = kwargs.get('rotation_policy')
        self.signing_algorithm = defaults.signing_algorithm(cert)
        self.bits = defaults.bitstrength(cert)
        self.external_id = kwargs.get('external_id')
        self.authority_id = kwargs.get('authority_id')
        self.dns_provider_id = kwargs.get('dns_provider_id')

        for domain in defaults.domains(cert):
            self.domains.append(Domain(name=domain))
Beispiel #10
0
def test_certificate_sensitive_name(client, authority, session, logged_in_user):
    """The CN is disallowed by 'sensitive' flag on Domain model."""
    from lemur.certificates.schemas import CertificateInputSchema

    input_data = {
        "commonName": "sensitive.example.com",
        "owner": "*****@*****.**",
        "authority": {"id": authority.id},
        "description": "testtestest",
        "validityStart": "2020-01-01T00:00:00",
        "validityEnd": "2020-01-01T00:00:01",
        "dnsProvider": None,
    }
    session.add(Domain(name="sensitive.example.com", sensitive=True))

    data, errors = CertificateInputSchema().load(input_data)
    assert errors["common_name"][0].startswith(
        "Domain sensitive.example.com has been marked as sensitive"
    )