Blog | G5 Cyber Security

Manage SSH Keys with Automation

TL;DR

Automate adding, removing, and monitoring SSH keys in your authorized_keys file to improve security and reduce admin overhead. Tools like Ansible, Puppet, Chef, or even simple scripts can help.

1. Why Automate?

Manually managing SSH keys is error-prone and time-consuming, especially with many servers. Automation offers:

2. Choosing an Automation Tool

Several tools can help, depending on your existing infrastructure:

3. Automating Key Addition (Ansible Example)

This example shows how to add an SSH key using Ansible.

  1. Create an Inventory File: List your servers in a file (e.g., inventory.ini).[servers]
    server1 ansible_host=192.168.1.10
    server2 ansible_host=192.168.1.11
  2. Create an Ansible Playbook: Define the tasks to perform (e.g., add_ssh_key.yml).---
    - hosts: servers
    become: yes # Required for writing to authorized_keys
    tasks:
    - name: Add SSH key
    authorized_key:
    user: your_username
    state: present
    key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABA... your_public_key ... your_username@your_host"
  3. Run the Playbook: Execute the playbook to add the key.ansible-playbook -i inventory.ini add_ssh_key.yml

4. Automating Key Removal

Similar to addition, use the authorized_key module with state: absent.

--- 
- hosts: servers
  become: yes
  tasks:
    - name: Remove SSH key
      authorized_key:
        user: your_username
        state: absent
        key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABA... your_public_key ... your_username@your_host"

5. Monitoring Authorized Keys

Regularly check for unauthorized keys or outdated configurations.

Example script snippet (Bash):

#!/bin/bash
for key in $(cat /home/your_username/.ssh/authorized_keys);
do
  fingerprint=$(ssh-keygen -l -f <<< "$key" | awk '{print $2}')
  echo "Key fingerprint: $fingerprint"
done

6. Security Considerations

Exit mobile version