Automating MFA Key Management in Vault with Python
Introduction
Managing Multi-Factor Authentication (MFA) keys in HashiCorp Vault can be challenging, especially when dealing with large-scale enterprise environments. This blog will walk you through automating the process of retrieving, creating, and deleting MFA keys in Vault using Python, with a step-by-step explanation suitable for beginners.
The Complete Script can be found here:
https://github.com/tasmiyam72/Automated-Identity-and-Access-Management-Scripts
What is MFA?
Multi-Factor Authentication (MFA) is a security mechanism that requires users to provide multiple forms of verification before accessing a system. In this case, we will manage MFA secrets stored in Vault and automate their retrieval and deletion.
Prerequisites
Before you start, ensure you have:
- A running instance of HashiCorp Vault
- Python 3.8+ installed
- Required dependencies listed in
requirements.txt - Properly configured environment variables for Vault authentication
Setting Up the Environment
Step 1: Install Dependencies
Run the following command to install required Python packages:
pip install -r requirements.txtStep 2: Configure Environment Variables
Ensure your .env file contains the required Vault credentials:
VAULT_TOKEN=<your_vault_token>
VAULT_ADDR=<your_vault_address>
MOUNT_POINT_SECRETS=<your_secrets_mount_point>
MOUNT_POINT_TOTP=<your_totp_mount_point>
TARGET_FOLDER=<target_folder>
TOTP_ISSUER=<issuer>Listing Vault Secrets
Understanding Secrets Management
Secrets are stored in Vault under a specific path. We need to list these stored secrets before processing them.
Python Function to List Secrets
def list_vault_secrets(vault_client, path: str, mount_point: str):
return vault_client.secrets.kv.v2.list_secrets(path=path, mount_point=mount_point)Purpose: Retrieve a list of stored secrets from HashiCorp Vault.
Details:
- Uses Vault’s KV v2 secrets engine to list stored secrets at a given path.
- Requires
vault_client,path, andmount_pointas parameters. - Returns the list of secrets.
Automating MFA Key Management
The main.py script automates the process of retrieving and storing MFA keys.
Step 1: Authenticate with Vault
def vault_authentication_client() -> hvac.Client:
vault_client = hvac.Client(url=VAULT_URL, token=VAULT_TOKEN, strict_http=True)
if vault_client.is_authenticated():
return vault_client
raise ValueError("Invalid or missing Vault token")Purpose: Establish a connection to Vault using a valid authentication token.
Details:
- Creates an HVAC client with
VAULT_URLandVAULT_TOKEN. - Checks if authentication is successful using
is_authenticated(). - Raises an error if authentication fails.
Step 2: List Tenant Secrets
def list_tenant_folders(vault_client, vault_folder, mount_point):
tenant_list = list_vault_secrets(vault_client, vault_folder, mount_point)
return tenant_list["data"]["keys"]Purpose: Retrieve all tenant folders containing stored secrets.
Get Tasmiya Mansoor’s stories in your inbox
Join Medium for free to get updates from this writer.
Details:
- Calls
list_vault_secretsto fetch tenant folder names. - Extracts the
"keys"from the response to return a list of tenants.
Step 3: Extract and Process MFA Keys
def process_secrets_dictionaries(secrets_dict: dict) -> list:
mfa_secret_match = []
username_match = []
for dictionary in secrets_dict:
if "mfa_secret_key" in dictionary:
mfa_secret_match.append(dictionary["mfa_secret_key"])
username_match.append(dictionary["username"])
return list(zip(mfa_secret_match, username_match))Purpose: Extract MFA secret keys and match them with corresponding usernames.
Details:
- Iterates through a dictionary of stored secrets.
- Extracts values of
"mfa_secret_key"and"username". - Returns a list of tuples containing (MFA Key, Username) pairs.
Step 4: Deleting Old TOTP Keys
Over time, expired or outdated MFA keys must be removed. The delete.py script helps manage this cleanup process.
Python Function to Delete MFA Keys
def delete_vault_totp(vault_client, vault_totp_key, vault_url, mount_point):
request_url = f"{vault_url}/v1/{mount_point}/keys/{vault_totp_key}"
request_header = {"X-Vault-Token": vault_client.token}
response = requests.request("DELETE", request_url, headers=request_header)
return response.status_code in (200, 204)Purpose: Remove expired or unnecessary MFA keys from Vault.
Details:
- Constructs a DELETE request to Vault’s API endpoint.
- Uses the
vault_totp_key(MFA key identifier) to target a specific key. - Includes the Vault authentication token in the request header.
- Returns
Trueif the deletion is successful (200or204response)
Steps 5: Running the Scripts
python main.py # Generate MFA Keys
python delete.py # Delete Old KeysPurpose: Execute the automation process — generate and delete MFA keys.
Details:
python main.py→ Generates and stores MFA keys in Vault.python delete.py→ Removes outdated MFA keys from Vault.
Summary
- Vault Authentication — Establishes a connection using a token.
- Listing Secrets — Retrieves stored secrets and tenant folders.
- Processing MFA Keys — Extracts keys and matches them to users.
- Deleting Old MFA Keys — Sends DELETE requests to remove outdated keys.
- Execution — Automates the entire workflow using Python scripts.
Conclusion
Conclusion
Automating MFA key management in HashiCorp Vault significantly enhances security, efficiency, and time management. Manual handling of MFA keys can be time-consuming and error-prone, but this Python-based automation streamlines the entire workflow, reducing administrative overhead.
By breaking the process into authentication, secret retrieval, key processing, and deletion, this solution ensures a secure, fast, and scalable approach to MFA key management. Automating these tasks minimizes human intervention, eliminates repetitive manual work, and ensures consistency across large-scale environments.
With this script, organizations can improve security compliance, reduce operational delays, and enhance overall efficiency, making Vault MFA key management both effortless and effective.








