def mint(issuer_options): """ Minting is slightly different for each authority. Support for multiple authorities is handled by individual plugins. :param issuer_options: """ authority = issuer_options['authority'] issuer = plugins.get(authority.plugin_name) # allow the CSR to be specified by the user if not issuer_options.get('csr'): csr, private_key = create_csr(issuer_options) else: csr = str(issuer_options.get('csr')) private_key = None issuer_options['creator'] = g.user.email cert_body, cert_chain = issuer.create_certificate(csr, issuer_options) cert = Certificate(cert_body, private_key, cert_chain) cert.user = g.user cert.authority = authority database.update(cert) return cert, private_key, cert_chain,
def create(**kwargs): """ Creates a new certificate. """ kwargs['creator'] = g.user.email cert_body, private_key, cert_chain = mint(**kwargs) kwargs['body'] = cert_body kwargs['private_key'] = private_key kwargs['chain'] = cert_chain roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles cert = Certificate(**kwargs) g.user.certificates.append(cert) cert.authority = kwargs['authority'] database.commit() metrics.send('certificate_issued', 'counter', 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer)) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles if kwargs.get('private_key'): private_key = kwargs['private_key'] if not isinstance(private_key, bytes): kwargs['private_key'] = private_key.encode('utf-8') cert = Certificate(**kwargs) cert.authority = kwargs.get('authority') cert = database.create(cert) kwargs['creator'].certificates.append(cert) cert = database.update(cert) certificate_imported.send(certificate=cert, authority=cert.authority) return cert
def create(**kwargs): """ Creates a new certificate. """ cert_body, private_key, cert_chain, external_id, csr = mint(**kwargs) kwargs['body'] = cert_body kwargs['private_key'] = private_key kwargs['chain'] = cert_chain kwargs['external_id'] = external_id kwargs['csr'] = csr roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles if cert_body: cert = Certificate(**kwargs) kwargs['creator'].certificates.append(cert) else: cert = PendingCertificate(**kwargs) kwargs['creator'].pending_certificates.append(cert) cert.authority = kwargs['authority'] database.commit() if isinstance(cert, Certificate): certificate_issued.send(certificate=cert, authority=cert.authority) metrics.send('certificate_issued', 'counter', 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer)) return cert
def create(**kwargs): """ Creates a new certificate. """ try: cert_body, private_key, cert_chain, external_id, csr = mint(**kwargs) except Exception: log_data = { "message": "Exception minting certificate", "issuer": kwargs["authority"].name, "cn": kwargs["common_name"], } current_app.logger.error(log_data, exc_info=True) capture_exception() raise kwargs["body"] = cert_body kwargs["private_key"] = private_key kwargs["chain"] = cert_chain kwargs["external_id"] = external_id kwargs["csr"] = csr roles = create_certificate_roles(**kwargs) if kwargs.get("roles"): kwargs["roles"] += roles else: kwargs["roles"] = roles if cert_body: cert = Certificate(**kwargs) kwargs["creator"].certificates.append(cert) else: # ACME path cert = PendingCertificate(**kwargs) kwargs["creator"].pending_certificates.append(cert) cert.authority = kwargs["authority"] database.commit() if isinstance(cert, Certificate): certificate_issued.send(certificate=cert, authority=cert.authority) metrics.send( "certificate_issued", "counter", 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer), ) if isinstance(cert, PendingCertificate): # We need to refresh the pending certificate to avoid "Instance is not bound to a Session; " # "attribute refresh operation cannot proceed" pending_cert = database.session_query(PendingCertificate).get(cert.id) from lemur.common.celery import fetch_acme_cert if not current_app.config.get("ACME_DISABLE_AUTORESOLVE", False): fetch_acme_cert.apply_async((pending_cert.id,), countdown=5) return cert
def create(kwargs): """ Create a new authority. :rtype : Authority :return: """ issuer = plugins.get(kwargs.get('pluginName')) kwargs['creator'] = g.current_user.email cert_body, intermediate, issuer_roles = issuer.create_authority(kwargs) cert = Certificate(cert_body, chain=intermediate) cert.owner = kwargs['ownerEmail'] cert.description = "This is the ROOT certificate for the {0} certificate authority".format(kwargs.get('caName')) cert.user = g.current_user cert.notifications = notification_service.create_default_expiration_notifications( 'DEFAULT_SECURITY', current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL') ) # we create and attach any roles that the issuer gives us role_objs = [] for r in issuer_roles: role = role_service.create( r['name'], password=r['password'], description="{0} auto generated role".format(kwargs.get('pluginName')), username=r['username']) # the user creating the authority should be able to administer it if role.username == 'admin': g.current_user.roles.append(role) role_objs.append(role) authority = Authority( kwargs.get('caName'), kwargs['ownerEmail'], kwargs['pluginName'], cert_body, description=kwargs['caDescription'], chain=intermediate, roles=role_objs ) database.update(cert) authority = database.create(authority) g.current_user.authorities.append(authority) return authority
def create(**kwargs): """ Creates a new certificate. """ try: cert_body, private_key, cert_chain, external_id, csr = mint(**kwargs) except Exception: current_app.logger.error("Exception minting certificate", exc_info=True) sentry.captureException() raise kwargs['body'] = cert_body kwargs['private_key'] = private_key kwargs['chain'] = cert_chain kwargs['external_id'] = external_id kwargs['csr'] = csr roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles if cert_body: cert = Certificate(**kwargs) kwargs['creator'].certificates.append(cert) else: cert = PendingCertificate(**kwargs) kwargs['creator'].pending_certificates.append(cert) cert.authority = kwargs['authority'] database.commit() if isinstance(cert, Certificate): certificate_issued.send(certificate=cert, authority=cert.authority) metrics.send('certificate_issued', 'counter', 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer)) if isinstance(cert, PendingCertificate): # We need to refresh the pending certificate to avoid "Instance is not bound to a Session; " # "attribute refresh operation cannot proceed" pending_cert = database.session_query(PendingCertificate).get(cert.id) from lemur.common.celery import fetch_acme_cert if not current_app.config.get("ACME_DISABLE_AUTORESOLVE", False): fetch_acme_cert.apply_async((pending_cert.id, ), countdown=5) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles if kwargs.get('private_key'): private_key = kwargs['private_key'] if not isinstance(private_key, bytes): kwargs['private_key'] = private_key.encode('utf-8') cert = Certificate(**kwargs) cert = database.create(cert) try: g.user.certificates.append(cert) except AttributeError: current_app.logger.debug( "No user to associate uploaded certificate to.") return database.update(cert)
def upload(self, name, body, private_key, cert_chain, options, **kwargs): k8_bearer = self.get_option('kubernetesAuthToken', options) k8_cert = self.get_option('kubernetesServerCertificate', options) k8_namespace = self.get_option('kubernetesNamespace', options) k8_base_uri = self.get_option('kubernetesURL', options) k8s_api = K8sSession(k8_bearer, k8_cert) cert = Certificate(body=body) # in the future once runtime properties can be passed-in - use passed-in secret name secret_name = 'certs-' + urllib.quote_plus(cert.name) err = ensure_resource(k8s_api, k8s_base_uri=k8_base_uri, namespace=k8_namespace, kind="secret", name=secret_name, data={ 'apiVersion': 'v1', 'kind': 'Secret', 'metadata': { 'name': secret_name, }, 'data': { 'combined.pem': base64.b64encode(body + private_key), 'ca.crt': base64.b64encode(cert_chain), 'service.key': base64.b64encode(private_key), 'service.crt': base64.b64encode(body), } }) if err is not None: raise Exception("Error uploading secret: " + err)
def create(**kwargs): """ Creates a new certificate. """ try: cert_body, private_key, cert_chain, external_id, csr = mint(**kwargs) except Exception: current_app.logger.error("Exception minting certificate", exc_info=True) sentry.captureException() raise kwargs['body'] = cert_body kwargs['private_key'] = private_key kwargs['chain'] = cert_chain kwargs['external_id'] = external_id kwargs['csr'] = csr roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles if cert_body: cert = Certificate(**kwargs) kwargs['creator'].certificates.append(cert) else: cert = PendingCertificate(**kwargs) kwargs['creator'].pending_certificates.append(cert) cert.authority = kwargs['authority'] database.commit() if isinstance(cert, Certificate): certificate_issued.send(certificate=cert, authority=cert.authority) metrics.send('certificate_issued', 'counter', 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer)) if isinstance(cert, PendingCertificate): # We need to refresh the pending certificate to avoid "Instance is not bound to a Session; " # "attribute refresh operation cannot proceed" pending_cert = database.session_query(PendingCertificate).get(cert.id) from lemur.common.celery import fetch_acme_cert if not current_app.config.get("ACME_DISABLE_AUTORESOLVE", False): fetch_acme_cert.apply_async((pending_cert.id,), countdown=5) return cert
def test_get_cert_from_arn(app): from lemur.plugins.lemur_aws.iam import upload_cert, get_cert_from_arn cert = Certificate(EXTERNAL_VALID_STR) upload_cert('123456789012', cert, PRIVATE_KEY_STR) body, chain = get_cert_from_arn( 'arn:aws:iam::123456789012:server-certificate/tttt2.netflixtest.net-NetflixInc-20150624-20150625' ) assert body.replace('\n', '') == EXTERNAL_VALID_STR.replace('\n', '')
def create(kwargs): """ Create a new authority. :return: """ issuer = plugins.get(kwargs.get('pluginName')) kwargs['creator'] = g.current_user.email cert_body, intermediate, issuer_roles = issuer.create_authority(kwargs) cert = Certificate(cert_body, chain=intermediate) cert.owner = kwargs['ownerEmail'] if kwargs['caType'] == 'subca': cert.description = "This is the ROOT certificate for the {0} sub certificate authority the parent \ authority is {1}.".format( kwargs.get('caName'), kwargs.get('caParent')) else: cert.description = "This is the ROOT certificate for the {0} certificate authority.".format( kwargs.get('caName')) cert.user = g.current_user cert.notifications = notification_service.create_default_expiration_notifications( 'DEFAULT_SECURITY', current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')) # we create and attach any roles that the issuer gives us role_objs = [] for r in issuer_roles: role = role_service.create( r['name'], password=r['password'], description="{0} auto generated role".format( kwargs.get('pluginName')), username=r['username']) # the user creating the authority should be able to administer it if role.username == 'admin': g.current_user.roles.append(role) role_objs.append(role) authority = Authority(kwargs.get('caName'), kwargs['ownerEmail'], kwargs['pluginName'], cert_body, description=kwargs['caDescription'], chain=intermediate, roles=role_objs) database.update(cert) authority = database.create(authority) g.current_user.authorities.append(authority) return authority
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if not kwargs.get("roles"): kwargs["roles"] = [] kwargs["roles"] += [role for role in roles if role not in kwargs["roles"]] cert = Certificate(**kwargs) cert.authority = kwargs.get("authority") cert = database.create(cert) kwargs["creator"].certificates.append(cert) cert = database.update(cert) certificate_imported.send(certificate=cert, authority=cert.authority) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles cert = Certificate(**kwargs) cert.authority = kwargs.get('authority') cert = database.create(cert) kwargs['creator'].certificates.append(cert) cert = database.update(cert) certificate_imported.send(certificate=cert, authority=cert.authority) return cert
def import_certificate(**kwargs): """ Uploads already minted certificates and pulls the required information into Lemur. This is to be used for certificates that are created outside of Lemur but should still be tracked. Internally this is used to bootstrap Lemur with external certificates, and used when certificates are 'discovered' through various discovery techniques. was still in aws. :param kwargs: """ from lemur.users import service as user_service from lemur.notifications import service as notification_service cert = Certificate(kwargs['public_certificate'], chain=kwargs['intermediate_certificate']) # TODO future source plugins might have a better understanding of who the 'owner' is we should support this cert.owner = kwargs.get('owner', current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')[0]) cert.creator = kwargs.get('creator', user_service.get_by_email('lemur@nobody')) # NOTE existing certs may not follow our naming standard we will # overwrite the generated name with the actual cert name if kwargs.get('name'): cert.name = kwargs.get('name') if kwargs.get('user'): cert.user = kwargs.get('user') notification_name = 'DEFAULT_SECURITY' notifications = notification_service.create_default_expiration_notifications(notification_name, current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')) cert.notifications = notifications cert = database.create(cert) return cert
def mint(issuer_options): """ Minting is slightly different for each authority. Support for multiple authorities is handled by individual plugins. :param issuer_options: """ authority = issuer_options["authority"] issuer = plugins.get(authority.plugin_name) csr, private_key = create_csr(issuer_options) issuer_options["creator"] = g.user.email cert_body, cert_chain = issuer.create_certificate(csr, issuer_options) cert = Certificate(cert_body, private_key, cert_chain) cert.user = g.user cert.authority = authority database.update(cert) return cert, private_key, cert_chain
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ from lemur.notifications import service as notification_service cert = Certificate( kwargs.get('public_cert'), kwargs.get('private_key'), kwargs.get('intermediate_cert'), ) # we override the generated name if one is provided if kwargs.get('name'): cert.name = kwargs['name'] cert.description = kwargs.get('description') cert.owner = kwargs['owner'] cert = database.create(cert) g.user.certificates.append(cert) database.update_list(cert, 'destinations', Destination, kwargs['destinations']) database.update_list(cert, 'notifications', Notification, kwargs['notifications']) database.update_list(cert, 'replaces', Certificate, kwargs['replacements']) # create default notifications for this certificate if none are provided notifications = [] if not kwargs.get('notifications'): notification_name = "DEFAULT_{0}".format(cert.owner.split('@')[0].upper()) notifications += notification_service.create_default_expiration_notifications(notification_name, [cert.owner]) notification_name = 'DEFAULT_SECURITY' notifications += notification_service.create_default_expiration_notifications(notification_name, current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')) cert.notifications = notifications database.update(cert) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ from lemur.notifications import service as notification_service cert = Certificate(kwargs.get("public_cert"), kwargs.get("private_key"), kwargs.get("intermediate_cert")) # we override the generated name if one is provided if kwargs.get("name"): cert.name = kwargs["name"] cert.description = kwargs.get("description") cert.owner = kwargs["owner"] cert = database.create(cert) g.user.certificates.append(cert) database.update_list(cert, "destinations", Destination, kwargs.get("destinations")) database.update_list(cert, "notifications", Notification, kwargs.get("notifications")) # create default notifications for this certificate if none are provided notifications = [] if not kwargs.get("notifications"): notification_name = "DEFAULT_{0}".format(cert.owner.split("@")[0].upper()) notifications += notification_service.create_default_expiration_notifications(notification_name, [cert.owner]) notification_name = "DEFAULT_SECURITY" notifications += notification_service.create_default_expiration_notifications( notification_name, current_app.config.get("LEMUR_SECURITY_TEAM_EMAIL") ) cert.notifications = notifications database.update(cert) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles cert = Certificate(**kwargs) cert = database.create(cert) g.user.certificates.append(cert) database.update(cert) return cert
def import_certificate(**kwargs): """ Uploads already minted certificates and pulls the required information into Lemur. This is to be used for certificates that are created outside of Lemur but should still be tracked. Internally this is used to bootstrap Lemur with external certificates, and used when certificates are 'discovered' through various discovery techniques. was still in aws. :param kwargs: """ from lemur.users import service as user_service from lemur.notifications import service as notification_service cert = Certificate(kwargs['public_certificate'], chain=kwargs['intermediate_certificate']) # TODO future source plugins might have a better understanding of who the 'owner' is we should support this cert.owner = kwargs.get( 'owner', current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')[0]) cert.creator = kwargs.get('creator', user_service.get_by_email('lemur@nobody')) # NOTE existing certs may not follow our naming standard we will # overwrite the generated name with the actual cert name if kwargs.get('name'): cert.name = kwargs.get('name') if kwargs.get('user'): cert.user = kwargs.get('user') notification_name = 'DEFAULT_SECURITY' notifications = notification_service.create_default_expiration_notifications( notification_name, current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')) if kwargs.get('replacements'): database.update_list(cert, 'replaces', Certificate, kwargs['replacements']) cert.notifications = notifications cert = database.create(cert) return cert
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ roles = create_certificate_roles(**kwargs) if kwargs.get('roles'): kwargs['roles'] += roles else: kwargs['roles'] = roles cert = Certificate(**kwargs) cert = database.create(cert) try: g.user.certificates.append(cert) except AttributeError: current_app.logger.debug("No user to associate uploaded certificate to.") return database.update(cert)
def upload(**kwargs): """ Allows for pre-made certificates to be imported into Lemur. """ from lemur.notifications import service as notification_service cert = Certificate( kwargs.get('public_cert'), kwargs.get('private_key'), kwargs.get('intermediate_cert'), ) # we override the generated name if one is provided if kwargs.get('name'): cert.name = kwargs['name'] cert.description = kwargs.get('description') cert.owner = kwargs['owner'] cert = database.create(cert) g.user.certificates.append(cert) database.update_list(cert, 'destinations', Destination, kwargs.get('destinations')) database.update_list(cert, 'notifications', Notification, kwargs.get('notifications')) database.update_list(cert, 'replaces', Certificate, kwargs['replacements']) # create default notifications for this certificate if none are provided notifications = [] if not kwargs.get('notifications'): notification_name = "DEFAULT_{0}".format( cert.owner.split('@')[0].upper()) notifications += notification_service.create_default_expiration_notifications( notification_name, [cert.owner]) notification_name = 'DEFAULT_SECURITY' notifications += notification_service.create_default_expiration_notifications( notification_name, current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL')) cert.notifications = notifications database.update(cert) return cert
def test_get_all_server_certs(app): from lemur.plugins.lemur_aws.iam import upload_cert, get_all_server_certs cert = Certificate(EXTERNAL_VALID_STR) upload_cert('123456789012', cert, PRIVATE_KEY_STR) certs = get_all_server_certs('123456789012') assert len(certs) == 1
def create(kwargs): """ Create a new authority. :return: """ issuer = kwargs['plugin']['plugin_object'] kwargs['creator'] = g.current_user.email cert_body, intermediate, issuer_roles = issuer.create_authority(kwargs) cert = Certificate(cert_body, chain=intermediate) cert.owner = kwargs['owner'] if kwargs['type'] == 'subca': cert.description = "This is the ROOT certificate for the {0} sub certificate authority the parent \ authority is {1}.".format(kwargs.get('name'), kwargs.get('parent')) else: cert.description = "This is the ROOT certificate for the {0} certificate authority.".format( kwargs.get('name') ) cert.user = g.current_user cert.notifications = notification_service.create_default_expiration_notifications( 'DEFAULT_SECURITY', current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL') ) # we create and attach any roles that the issuer gives us role_objs = [] for r in issuer_roles: role = role_service.create( r['name'], password=r['password'], description="{0} auto generated role".format(issuer.title), username=r['username']) # the user creating the authority should be able to administer it if role.username == 'admin': g.current_user.roles.append(role) role_objs.append(role) authority = Authority( kwargs.get('name'), kwargs['owner'], issuer.slug, cert_body, description=kwargs['description'], chain=intermediate, roles=role_objs ) database.update(cert) authority = database.create(authority) # the owning dl or role should have this authority associated with it owner_role = role_service.get_by_name(kwargs['owner']) if not owner_role: owner_role = role_service.create(kwargs['owner']) owner_role.authority = authority g.current_user.authorities.append(authority) return authority
def create(**kwargs): """ Creates a new certificate. """ # Validate destinations do not overlap accounts if "destinations" in kwargs: dest_accounts = {} for dest in kwargs["destinations"]: account = get_plugin_option("accountNumber", dest.options) if account in dest_accounts: raise Exception(f"Only one destination allowed per account: {account}") dest_accounts[account] = True try: cert_body, private_key, cert_chain, external_id, csr = mint(**kwargs) except Exception: log_data = { "message": "Exception minting certificate", "issuer": kwargs["authority"].name, "cn": kwargs.get("common_name"), } current_app.logger.error(log_data, exc_info=True) capture_exception() raise kwargs["body"] = cert_body kwargs["private_key"] = private_key kwargs["chain"] = cert_chain kwargs["external_id"] = external_id kwargs["csr"] = csr roles = create_certificate_roles(**kwargs) if kwargs.get("roles"): kwargs["roles"] += roles else: kwargs["roles"] = roles if cert_body: cert = Certificate(**kwargs) kwargs["creator"].certificates.append(cert) else: # ACME path cert = PendingCertificate(**kwargs) kwargs["creator"].pending_certificates.append(cert) cert.authority = kwargs["authority"] database.commit() if isinstance(cert, Certificate): certificate_issued.send(certificate=cert, authority=cert.authority) metrics.send( "certificate_issued", "counter", 1, metric_tags=dict(owner=cert.owner, issuer=cert.issuer), ) log_data = { "function": "lemur.certificates.service.create", "owner": cert.owner, "name": cert.name, "serial": cert.serial, "issuer": cert.issuer, "not_after": cert.not_after.format('YYYY-MM-DD HH:mm:ss'), "not_before": cert.not_before.format('YYYY-MM-DD HH:mm:ss'), "sans": str(', '.join([domain.name for domain in cert.domains])), } current_app.logger.info(log_data) if isinstance(cert, PendingCertificate): # We need to refresh the pending certificate to avoid "Instance is not bound to a Session; " # "attribute refresh operation cannot proceed" pending_cert = database.session_query(PendingCertificate).get(cert.id) from lemur.common.celery import fetch_acme_cert if not current_app.config.get("ACME_DISABLE_AUTORESOLVE", False): fetch_acme_cert.apply_async((pending_cert.id, kwargs.get("async_reissue_notification_cert_id", None)), countdown=5) return cert