Yubikey – Switch between primary authentication and secondary

descriptionStandard

Intended for use under Linux; this bash script lets you change how your Yubikey is used to authenticate on your device. It can be use used as the primary authentication method or changed to a 2nd factor authentication step for increased security.

Table of Contents

    a2fa.sh usage examples

    This script will changes the active primary authentication method between requiring the Yubikey as the primary authentication or as a 2nd factor.

    Cloning the repository

    git clone git@gitlab.com:oddineers-public/linux-helper-scripts.git
    cd linux-helper-scripts/yubikey

    Supported arguments

    cd <path-to-scripts>
    
    # Authenticate with Yuibkey
    sudo a2fa.sh auth
    
    # Use Yubikey as 2nd factor authentication
    sudo a2fa.sh 2fa
    
    # OR
    
    # Authenticate with Yuibkey
    sudo <path-to-scripts>/a2fa.sh auth
    
    # Use Yubikey as 2nd factor authentication
    sudo <path-to-scripts>/a2fa.sh 2fa

    If installed run from local bin:

    # Authenticate with Yuibkey
    sudo a2fa auth
    
    # Use Yubikey as 2nd factor authentication
    sudo a2fa 2fa

    Installation

    sudo mv a2fa.sh /usr/local/bin/a2fa

    Uninstallation

    sudo rm -f /usr/local/bin/a2fa

    Source Reference

    #!/bin/bash
    
    # Ensure pamu2fcfg is installed
    if ! command -v pamu2fcfg --version &> /dev/null; then
        echo "pamu2fcfg could not be found. Please ensure these packages are installed: pam-u2f pamu2fcfg yubikey-manager"
        exit 1
    fi
    
    # Function to perform authselect operation
    perform_authselect() {
        local mode=$1
        local message=$2
        # If not already elevated try
        sudo authselect select sssd "$mode" without-nullok > /dev/null 2>&1
    
        if [ $? -eq 0 ]; then
            echo "$message"
        else
            echo "Failed to update authentication settings to $mode."
            exit 1
        fi
    }
    
    case "$1" in
        auth)
            perform_authselect "with-pam-u2f" "Authentication settings updated to use Yubikey as auth successfully."
            ;;
        2fa)
            perform_authselect "with-pam-u2f-2fa" "Authentication settings updated to use Yubikey as 2FA successfully."
            ;;
        *)
            echo "Invalid argument: $1"
            echo "Usage: $0 {auth|2fa}"
            exit 1
            ;;
    esac