예제 #1
0
def __authenticate_vault_client(client: hvac.Client, tenant: str,
                                priv_jwt_token: str) -> hvac.Client:

    trace_enter(inspect.currentframe())

    vault_auth_jwt_path = config.get_vault_auth_jwt_path(tenant)

    if not vault_auth_jwt_path:
        logger.error('Failed to load auth jwt path for tenant "%s"', tenant)
        return None

    if config.get_config_by_keypath('DEV_MODE'):
        logger.debug('Attempting to authenticate against Vault using JWT: %s',
                     priv_jwt_token)

    cache_id = utils.get_vault_token_cache_id(tenant, priv_jwt_token)

    if cache_id in __VAULT_TOKEN_CACHE:
        logger.debug('Cache hit: Found token for "%s".', cache_id)
        client.token = __VAULT_TOKEN_CACHE[cache_id]
    else:
        logger.debug('Cache miss: Token for "%s" not found.', cache_id)

        token = __get_vault_token(client, tenant, priv_jwt_token,
                                  vault_auth_jwt_path)

        if not token:
            ret = None
            logger.error('Failed to get Vault token.')
            trace_exit(inspect.currentframe(), ret)
            return ret

        client.token = token
        __VAULT_TOKEN_CACHE[cache_id] = token

    if not client.is_authenticated():
        # token might be invalid/has expired
        del __VAULT_TOKEN_CACHE[cache_id]

        ret = None

        logger.error('Failed to validate Vault client. '
                     'Review configuration (config/config.json). '
                     'Retry as token might have expired.')

        trace_exit(inspect.currentframe(), ret)
        return ret

    logger.debug('Successfully authenticated Vault client '
                 'for tenant "%s"', tenant)

    trace_exit(inspect.currentframe(), client)
    return client
예제 #2
0
def get_client(obj):
    client = Client(
        **{k: v
           for k, v in obj.VAULT_FOR_DYNACONF.items() if v is not None})
    if obj.VAULT_ROLE_ID_FOR_DYNACONF is not None:
        client.auth_approle(
            role_id=obj.VAULT_ROLE_ID_FOR_DYNACONF,
            secret_id=obj.get("VAULT_SECRET_ID_FOR_DYNACONF"),
        )
    elif obj.VAULT_ROOT_TOKEN_FOR_DYNACONF is not None:
        client.token = obj.VAULT_ROOT_TOKEN_FOR_DYNACONF
    elif obj.VAULT_AUTH_WITH_IAM_FOR_DYNACONF:
        if boto3 is None:
            raise ImportError(
                "boto3 package is not installed in your environment. "
                "`pip install boto3` or disable the VAULT_AUTH_WITH_IAM")

        session = boto3.Session()
        credentials = session.get_credentials()
        client.auth.aws.iam_login(
            credentials.access_key,
            credentials.secret_key,
            credentials.token,
            role=obj.VAULT_AUTH_ROLE_FOR_DYNACONF,
        )
    assert client.is_authenticated(), (
        "Vault authentication error: is VAULT_TOKEN_FOR_DYNACONF or "
        "VAULT_ROLE_ID_FOR_DYNACONF defined?")
    client.kv.default_kv_version = obj.VAULT_KV_VERSION_FOR_DYNACONF
    return client
예제 #3
0
    def login(self) -> Client:
        """
        create a client and log it in with the correct method
        :return: a logged in client
        """
        client = Client(self.url)
        log.info("client created with url %s", client.url)

        if not client.is_authenticated():
            log.info("client is not authenticated")

            if self.method == Method.LDAP:
                log.info("trying to login with LDAP")
                try:
                    client.auth.ldap.login(self.username, self.password)
                except (InvalidPath, ValueError) as err:
                    log.error("LDAP Login failed: %s", err)
                    exit(2)

            if self.method == Method.Token:
                log.info("trying to login with Token")
                try:
                    client.token = self.token
                    client.login(self.url, True)
                except (InvalidPath, ValueError) as err:
                    log.error("Token Login failed: %s", err)
                    exit(2)

        if not client.is_authenticated():
            log.error("login failed.")
            log.error("Aborting...")
            exit(2)

        return client
예제 #4
0
    def _auth(self):
        client = VaultClient(url=self._config['addr'])
        auth = self._config['auth_type']
        token = self._config['token']

        if token and auth == 'token':
            client.token = token
        elif auth == 'aws_iam':
            session = boto3.Session()
            creds = session.get_credentials()
            kwargs = [self._config['header_value'], self._config['role']]

            client.auth_aws_iam(
                creds.access_key, creds.secret_key, creds.token,
                **{k: v
                   for k, v in self._config.items() if v and k in kwargs})

        if client.is_authenticated() is False:
            raise VaultUnauthorized(f'auth_type: {auth}')

        return client.secrets.kv
예제 #5
0
 def _set_token(self, _client: hvac.Client) -> None:
     if self.token_path:
         with open(self.token_path) as f:
             _client.token = f.read().strip()
     else:
         _client.token = self.token
예제 #6
0
#!/usr/bin/env python
import os

from hvac import Client

from tools.vault import *

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
SETTINGS_FILE = os.path.join(CURRENT_DIR, '.vault-init.json')
K8S_CA_CERT_FILE = os.path.join(CURRENT_DIR, '.kube-ca.pem')
vault = Client(url="https://localhost:8200", verify="ssl/certs/ca.pem")

vault_settings = init_vault(vault, SETTINGS_FILE)
unseal_vault(vault, vault_settings)

vault.token = vault_settings["root_token"]
vault.enable_secret_backend(backend_type='pki', mount_point='/pki', config={"max_lease_ttl": 760 * 24 * 60})

bundle = {}
with open(os.path.join(CURRENT_DIR, "ssl", "certs", "ca.pem")) as input:
    bundle['cert'] = input.read()
with open(os.path.join(CURRENT_DIR, "ssl", "certs", "ca-key.pem")) as input:
    bundle['key'] = input.read()

vault.write(path='/pki/config/ca', pem_bundle="{}\n{}".format(bundle['cert'], bundle['key']))

vault.write('/pki/roles/default', allow_any_name=False, allow_subdomains=True,
            allowed_domains="default.svc.cluster.local",
            ttl='768h')

vault.write('/pki/roles/servicemesh', allow_any_name=False, allow_subdomains=True,