Cisco Meraki

Rotate your Cisco Meraki Network Credentials

Overview

In this guide, you will learn how to set up password rotation to rotate Cisco Meraki network credentials.

Prerequisites

  • KSM Application: Ensure that the Keeper Secrets Manager (KSM) application is set up.

  • Shared Folder: A shared folder should be set up where all the records will be stored.

  • PAM Configuration: Ensure that the PAM Configuration is set up and that the Gateway is running and attached to this configuration.

  • Requests Library: Ensure that the requests library is installed in your Python environment. This library is necessary for making HTTP requests to Cisco devices.

  • Setting up AnyConnect Cisco VPN: In order to connect to cisco devices, ensure that the machine hosting Keeper Gateway has Cisco AnyConnect VPN installed and properly configured

  • Test Cisco Device Connectivity

Requests library installation

The Requests library allows you to send HTTP requests easily. Activate a Python virtual environment in your Keeper Gateway environment and install the library using the following command:

pip install requests

Setting up AnyConnect Cisco VPN

Ensure that the machine hosting Keeper Gateway has Cisco AnyConnect VPN installed and properly configured inorder to connect to cisco device. This setup is necessary for establishing secure connections to Cisco devices.

Steps to Test Cisco Device

Following these steps will allow you to test the Cisco device and create a new user in the Cisco sandbox environment.

Note: If you want to use a virtual environment, add a shebang line at the top of the script as documented here in the Python Environment Setup.

Login to Cisco Sandbox

  • Log in with your Cisco account credentials.

  • Select and launch the sandbox.

2. Select and Launch the Device

  • Navigate to the sandbox catalog.

  • Select the appropriate sandbox for your Cisco device (e.g., Cisco IOS XE, etc.).

  • Launch the sandbox.

3. Receive Details via Email or DevNet Environment

After launching the sandbox, you will receive an email with the connection details or find them in the DevNet Environment under Quick Access.

4. Download Cisco AnyConnect VPN

  • Download and install the Cisco AnyConnect Secure Mobility Client.

  • Get detailed connection instructions here.

5. Connect to the VPN

  • Open the Cisco AnyConnect Secure Mobility Client.

  • Enter the VPN connection details provided in the email or from the DevNet Environment.

  • Connect using the provided username and password.

6. Store Developer Credentials

At this point, you will see Developer Credentials—a host, username, and password. Store these values in a Keeper Security record of type Login named as Cisco Authentication Record. You will need this Keeper Security record name in order to run the post-rotation script.

7. Add Custom Field to Cisco Authentication Record

Add a custom field named network_id to the Cisco Authentication Record and set its value to the host address (e.g., 13.0.0.1).

8. Create a User

  • Open your terminal or SSH client.

  • Connect to the Cisco device using the provided IP address and credentials.

9. Follow These Steps to Create a User

  1. Login with Admin User (developer):

    ssh developer@<device-ip>
  2. Enable privileged commands:

    enable
  3. Enter configuration mode:

    configure terminal
  4. Create a new user with a password:

    username <user> password <pass>

10. Test the New User

Login with the new user:

ssh <user>@<device-ip>

Note: Replace <user> with the username you created and <device-ip> with the IP address of the Cisco device.

Setting up Rotation in your Vault

Once you have your prerequisites ready, make sure you cover the following:

  1. Make sure you satisfy all the prerequisites

  2. Ensure that the post-rotation script references the Keeper Security record containing your Cisco admin credentials.

  3. Attach the post-rotation script to a Keeper Security PAM user record using the Keeper Security documentation. When this record has its secrets rotated, the post-rotation script will execute and update the password for the specified Cisco device user.

Step 1: Set Up Rotation Record

Create a new PAM User record to store Cisco User details whose password will be rotated.

  • Set the username to match the Cisco device admin credentials

  • Set the password to the current password set for the user.

  • Add a custom field named network_id to the Cisco Authentication Record and set its value to the host address (e.g., 13.0.0.1).

Step 2: Add PAM Script

  • Attach the below Python script that will perform the password rotation. The script has additional comments inside that describe each line.

Step 3: Add NOOP Custom Field

  • Enable No-Operation (NOOP) atomic execution:

    • In the current PAM User record where user's details are stored, create a new custom text field labeled NOOP and set its value to True.

Step 4: Configure Password Rotation Settings

  1. Rotation Type: Set it to "On-Demand" for this example.

  2. Password Complexity: Leave it as default unless you have specific requirements.

  3. Rotation Settings: Point to the PAM Configuration set up earlier.

  4. Administrative Credentials Record: Can should be left empty

Python Script

PAM script to rotate Cisco Meraki user credentials:

'''
Password rotation script for Cisco meraki user accounts.

This script is designed to rotate the password for a given Cisco Meraki User.
It facilitates the automated updating of user password in your Cisco meraki environment.

NOTE: If spaces are present in the path to the python interpreter, the script will fail to execute.
    This is a known limitation of the shebang line in Linux and you will need to create a symlink
    to the python interpreter in a path that does not contain spaces.
    For example: sudo ln -s "/usr/local/bin/my python3.7" /usr/local/bin/pam_rotation_venv_python3
'''

import sys
import base64
import json
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
'''
Optionally display installed packages for debugging. Uncomment if needed.
import pkg_resources
print("# \n# Installed packages for debugging:")
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages])
for m in installed_packages_list:
    print(f"  {m}")
'''

# Import the requests package
try:
    import requests
except ImportError:
    print("# Error: The 'requests' package is not installed. Run 'pip install requests' to install it.")
    exit(1)

def fetch_meraki_user_by_email(api_key, network_id, email):
    """
    Fetches User details by email.
    
    Args:
    - api_key (str): The Meraki API key.
    - network_id (str): The network ID to search within.
    - email (str): The email of the user to fetch.
    
    Returns:
    - User details if found, otherwise None.
    """
    if not network_id:
        print("Invalid network ID.")
        return None

    # URL to fetch Meraki dashboard users
    users_url = f"https://api.meraki.com/api/v1/networks/{network_id}/merakiAuthUsers"
    headers = {
        'X-Cisco-Meraki-API-Key': api_key,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    try:
        # Make GET request to fetch users
        response = requests.get(users_url, headers=headers)
        response.raise_for_status()
        # Parse response JSON
        users = response.json()

        if users:
            for user in users:
                if user['email'] == email:
                    print("\nUser found for the email-", email)
                    return user
        return None

    except requests.exceptions.RequestException as e:
        print(f"Error fetching Meraki dashboard users: {e}")
        return None

def update_meraki_user_password(api_key, network_id, user_id, new_password):
    """
    Updates the password for a Meraki dashboard user.
    
    Args:
    - api_key (str): The Meraki API key.
    - network_id (str): The network ID the user belongs to.
    - user_id (str): The ID of the user to update.
    - new_password (str): The new password to set.
    
    Returns:
    - bool: True if successful, otherwise False.
    """
    if not network_id:
        print("Invalid network ID.")
        return False

    # URL to update a specific user's password
    user_url = f"https://api.meraki.com/api/v1/networks/{network_id}/merakiAuthUsers/{user_id}"
    headers = {
        'X-Cisco-Meraki-API-Key': api_key,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    payload = {'password': new_password}

    # Make PUT request to update user's password
    response = requests.put(user_url, headers=headers, json=payload)
    
    return response

def rotate(meraki_network_id, meraki_api_key, meraki_user_email, new_password):
    """
    Rotate the password for a given Cisco user.
    Args:
    - meraki_network_id (str): Network ID of the network where the user is located.
    - meraki_api_key (str): API access key for authorization.
    - meraki_user_email (str): Email of the user whose password needs to be rotated.
    - new_password (str): The new password to be set for the Cisco user.
    Returns:
    - None
    """
    
    # Calls the function fetch_meraki_user_by_email to fetch the user details using user email.
    user = fetch_meraki_user_by_email(meraki_api_key, meraki_network_id, meraki_user_email)

    # If the user does not exist, print the message and exit the program
    if not user:
        print(f"No user found with the email: {meraki_user_email}")
        exit(1)
    
    try:
        meraki_user_id = user['id']

        # Updating password for the given user using ID
        response = update_meraki_user_password(meraki_api_key, meraki_network_id, meraki_user_id, new_password)
        if response.status_code == 200:
            print(f"Password updated successfully for user with email {meraki_user_email}")
        else:
            print(f"Failed to update password. Status code: {response.status_code}, Error: {response.text}")

    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred while updating the password for the given user email: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

def main():
    """
    Main function to rotate the password for a Cisco meraki user.

    Reads and decodes input parameters from stdin, including the authentication record details
    and the new password. Then, updates the password of the specified Cisco meraki user.
    """
    record_title = 'Cisco Authentication Record' #This should be same as the title of the record containing meraki api key and network ID details. 
    api_access_token_record = None
    params = None
    
    # Read and decode input parameters from stdin
    for base64_params in sys.stdin:
        params = json.loads(base64.b64decode(base64_params).decode())

        # Decode and load records passed in as JSON strings from the PAM Script section as "Rotation Credential" records
        records = json.loads(base64.b64decode(params.get('records')).decode())
        # Find the record that matches the specified title
        api_access_token_record = next((record for record in records if record['title'].lower() == record_title.lower()), None)
        break

    if api_access_token_record is None:
        print(f"# Error: No Record with the access token found. Title: {record_title}")
        exit(1)
    
    # Extract Details from the record
    
    # Network ID of the network where the user is located
    meraki_network_id = api_access_token_record.get('network_id')
    
    # API Key for Cisco meraki api authentication
    meraki_api_key = api_access_token_record.get('password')

    # Email of the Cisco meraki user whose password needs to be rotated
    meraki_user_email = params.get('user')

    # New password to set for the Cisco meraki user
    new_password = params.get('newPassword')
    
    # Check if all required fields are present
    if not all([meraki_network_id, meraki_api_key, meraki_user_email]):
        print("# Error: One or more required fields are missing in the access token record.")
        exit(1)

    # Rotate the password for the specified Cisco meraki user
    rotate(meraki_network_id, meraki_api_key, meraki_user_email, new_password)

if __name__ == "__main__":
    main()

The above script for the Cisco Post-Rotation Script can be also found here:

Rotating Cisco Meraki Network User Credentials

Note: The user whose password is getting rotated should not be an administrator and must be Authorized for Client VPN [While adding the user via user management portal, the authorized option should be selected as 'Yes'].

After successfully setting up Rotation for your Cisco User Credentials on the PAM User Record, clicking on "Run Scripts Only" will rotate the credential:

Last updated

Was this helpful?