Skip to main content

How to use Python to set up two factor authentication

Updated 24 min readMarkdown

Two-factor authentication adds a second proof of identity to a password or SSH key: possession of a physical security key, such as a FIDO U2F or FIDO2/WebAuthn authenticator, checked by a PAM (Pluggable Authentication Modules) rule on the target machine. pam_u2f is Yubico's PAM module for that job: it validates a challenge–response against a public credential registered to the user, with no shared secret stored on the server.

Reemote is a pure-Python configuration-management library. Instead of a domain-specific language, you write an ordinary Python generator that yields operations, gather typed facts from the target, and await a two-phase run that previews the work before applying it. This article uses Reemote's pam_u2f module to install the package, write its global configuration, synchronize a centralized credential file, and require a key for sudo and SSH logins. Enrollment itself stays manual — a physical touch cannot be automated — but everything around it becomes ordinary, testable Python.

Try the canonical example first

Install Python 3.13 or newer and Docker or Podman. The connector requires you to name the CLI explicitly; there is no default.

uv venv .venv
source .venv/bin/activate
uv pip install reemote

Save this as hello.py. It is the canonical example configured for Podman. The offline pytest suite simulates the connector, and the example was also verified live with Podman. Change both docker_cmd values to "docker" if that is your local CLI.

# hello.py
import asyncio

from reemote import files, format_log, format_plan, op, run

INVENTORY = [
    {
        "host": "demo0",
        "family": "Alpine",
        "connection": {
            "connector": "docker",
            "identifier": "alpine:3.20",
            "docker_cmd": "podman",
        },
    },
    {
        "host": "demo1",
        "family": "Alpine",
        "connection": {
            "connector": "docker",
            "identifier": "alpine:3.20",
            "docker_cmd": "podman",
        },
    },
]


def deploy(host):
    yield op(
        files.install,
        name="Write a greeting",
        content="Hello from reemote!\n",
        dest="/tmp/reemote-hello.txt",
        mode="0644",
    )
    yield op(
        files.install,
        name="Record the host name",
        content=f"written on {host.name}\n",
        dest="/tmp/reemote-host.txt",
        mode="0644",
    )


async def main():
    plans, report, _ = await run(INVENTORY, deploy, dry=True)
    print("== Dry run ==")
    print(format_plan(plans))
    assert report is None

    _, report, _ = await run(INVENTORY, deploy)
    print("\n== Applied ==")
    assert report is not None
    print(format_log(report))


asyncio.run(main())

Run it with python hello.py. The dry run connects to both containers and reads real state, but sends no mutating deploy commands inside them. The connector may still create, commit, and remove its temporary containers. The apply then advances through the two operations in lockstep: both hosts finish writing the greeting before either starts recording its name.

Verified output from Podman is shown below. The dry-run plan is host-major, while the apply log is step-major: both Write a greeting entries appear before either Record the host name entry.

== Dry run ==
demo0: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
demo0: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
demo1: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
demo1: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]

== Applied ==
demo0: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo1: Write a greeting         [changed: content /tmp/reemote-hello.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo0: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
demo1: Record the host name     [changed: content /tmp/reemote-host.txt is absent, will install]
    $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
    $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'

An image identifier creates a throwaway container for each host. On close, Reemote commits it to a new image and removes the container. That makes every run start fresh; idempotence is demonstrated later against an existing container instead.

Unlike the throwaway-container quickstart, the migration examples below reuse the same Ubuntu hosts, so repeated runs demonstrate convergence against persistent host state.

pam-u2f in brief

U2F and FIDO2 authentication differs from time-based one-time passwords (TOTP). There is no shared secret to seed into a phone app and no code to transcribe: the private key never leaves the authenticator, and the server only stores the corresponding public credential. A login sends a challenge, the key signs it after a physical touch, and pam_u2f verifies the signature.

Three files carry that model on a Linux host:

  • /etc/security/pam_u2f.conf — global defaults such as which authfile to read and whether to prompt (cue) before asking for a touch.
  • The credential file — either a per-user ~/.config/Yubico/u2f_keys or, for authentication that happens before an encrypted home directory is unlocked, a single centralized file such as /etc/u2f_mappings.
  • A PAM service file under /etc/pam.d/ — a line such as auth required pam_u2f.so authfile=/etc/u2f_mappings cue that places the check into the stack for a given service.

Enrollment is the one step that cannot be automated: pamu2fcfg needs the authenticator physically connected and touched. Everything before and after it — installing the package, writing the config, publishing enrolled credentials, adding and removing PAM rules — is what Reemote's pam_u2f module turns into ordinary, idempotent Python operations.

Changing a live PAM stack is riskier than editing most configuration files. Keep an independent root shell or console session open, test every change from a second session, and never replace an entire PAM file with content you have not reviewed; the module's enable_pam_u2f_service deliberately appends a single reviewed rule rather than rewriting a stack.

The pam_u2f module

The pam_u2f module reference is the complete API. It provides facts that inspect live state — whether the shared library is installed, the parsed active settings in pam_u2f.conf, the credential file grouped by username, and whether a given PAM service already has an active pam_u2f.so rule — and operations that reconcile the three protected files described above. Package installation picks apt-get, dnf or apk on the target, so a single request works across the supported families. Every file operation compares content and metadata separately, spools the new bytes with an unprivileged transfer, and installs them as root:root through an elevated shell; it never rewrites a file that already matches, and never puts credential contents in a plan or a log.

This article uses those operations one at a time, then composes them into a single deploy.

What the module owns

A second factor has to be installed, configured, enrolled, inserted into a PAM stack, and undone again — and, unlike a TOTP secret, a U2F credential is public authentication material that can be filed centrally. pam_u2f covers those steps as five operations:

  • install_pam_u2f installs the package, picking apt-get, dnf or apk from target facts.
  • configure_pam_u2f writes /etc/security/pam_u2f.conf from hashable (name, value) pairs, with no template file involved.
  • sync_u2f_mappings publishes manually enrolled credentials to a centralized authfile.
  • enable_pam_u2f_service appends one validated rule to a service file such as /etc/pam.d/sshd.
  • Removal is a files.transform that filters the named lines back out; changed_hosts on the first report drives a systemd.service restart only where something changed.

Appending a rule to a live PAM stack is where a naive implementation goes wrong: a blind line insert duplicates the rule on every run and happily writes into a stack it never read. Reemote's operation reads the file first, does nothing when an active pam_u2f.so rule is already present, and rejects a service file that does not exist rather than creating a broken stack.

Inventory for the two-factor hosts

The examples use the repository's real Ubuntu SSH host. Save an equivalent inventory as inventory.json:

[
  {
    "host": "ubuntu",
    "family": "Ubuntu",
    "connection": {
      "connector": "ssh",
      "address": "192.168.0.251",
      "port": 22,
      "username": "supervisor",
      "key_path": "~/.ssh/id_ed25519"
    },
    "group": "ubuntu",
    "tags": ["ubuntu_host", "apt_package_manager"]
  }
]

Replace the address, user, and key path with your own. Verify the host key and populate ~/.ssh/known_hosts rather than disabling host-key checking. The supervisor login needs passwordless sudo for every request below, since each one reads or writes a root-owned PAM or configuration file. See the SSH connector reference for connection options.

Runnable examples for the inventory Ubuntu host

Clone the repository and edit its inventory.json, or replace that file with the inventory above:

git clone https://github.com/kimjarvis/reemote.git
cd reemote

The scripts under examples/articles/pam_u2f/ load that inventory and select only entries whose family is Ubuntu. Mutating scripts preview by default and require --apply.

Example Article concept
install_u2f.py Install the PAM module and registration utility
configure_global.py Write /etc/security/pam_u2f.conf from hashable settings
sync_mappings.py Publish manually enrolled credentials to a centralized authfile
enable_sudo.py Require a key for sudo
enable_sshd.py Require a key for SSH, and match sshd's own prompt
exempt_accounts.py Exempt a service-account group from the second factor
restart_sshd.py Restart sshd only on hosts whose requests changed
inspect_u2f.py Gather structured pam-u2f facts from real hosts
rollback.py Remove the article's rules and restore the sshd options
deploy_2fa.py Compose every request above into one ordered deploy

Install the module first

The package install is idempotent on its own fact: absent, it issues one command; already installed, it issues none and says so.

# install_u2f.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Install the pam-u2f package with ``pam_u2f.install_pam_u2f``."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, op, pam_u2f

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["INVENTORY", "deploy", "main"]


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        pam_u2f.install_pam_u2f,
        name="Install pam-u2f",
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

Run python examples/articles/pam_u2f/install_u2f.py, review the plan, then repeat with --apply. On a host that already has pam_u2f.so somewhere under a standard library directory, the preview reports no change.

Configure the global module options

configure_pam_u2f replaces the whole configuration file with the active settings it is given, rendered deterministically from hashable (name, value) pairs. Duplicate names, a conf setting inside the file itself, malformed names, and content over upstream's 4 KiB limit all raise before a command is built.

# configure_global.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Manage /etc/security/pam_u2f.conf with ``pam_u2f.configure_pam_u2f``."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, op, pam_u2f

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["INVENTORY", "SETTINGS", "deploy", "main"]

SETTINGS = (
    ("authfile", "/etc/u2f_mappings"),
    ("cue", ""),
    ("origin", "pam://reemote-u2f-demo"),
)


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        pam_u2f.configure_pam_u2f,
        name="Configure pam-u2f globally",
        settings=SETTINGS,
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

authfile points the module at the centralized credential file the next section writes. cue asks the module to prompt before waiting for a touch. origin is the WebAuthn relying-party identifier; keep it stable across hosts that share credentials. Because the operation owns the whole file, do not hand-edit settings into it and expect them to survive.

Publish enrolled credentials

Enroll a key by running pamu2fcfg -u <name> on a machine with the authenticator attached, then touch the key. The output line's credential fields — without the username: prefix — go into the hashable tuple below. These are public authentication material, never private keys, and the operation keeps them out of plans and logs.

# sync_mappings.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Synchronize manually enrolled credentials with ``pam_u2f.sync_u2f_mappings``."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, op, pam_u2f

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["AUTHFILE", "INVENTORY", "MAPPINGS", "deploy", "main"]

AUTHFILE = "/etc/u2f_mappings"
# Replace with the ``keyhandle,userkey,cosetype,options`` output of running
# ``pamu2fcfg -u <name>`` beside a physical authenticator. Never a private key.
MAPPINGS = (
    ("alice", ("8a2f...c41d,04b3...7f9e,1,",)),
    ("bob", ("51c7...9ab0,048f...22d1,1,", "77e0...14c2,0441...b908,1,")),
)


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        pam_u2f.sync_u2f_mappings,
        name="Install enrolled U2F credentials",
        user_mappings=MAPPINGS,
        authfile=AUTHFILE,
        mode="0600",
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

A user may list more than one credential, as bob does. The default mode 0600 is the safe choice; 0440 is also accepted when a dedicated group needs read access, while any execute bit or other-user permission is rejected outright. An empty user_mappings tuple clears the file.

Require a key for sudo

enable_pam_u2f_service appends a rule only when the named service file has no active pam_u2f.so rule yet. Existing controls and options are never rewritten.

# enable_sudo.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Require a registered key for sudo with ``pam_u2f.enable_pam_u2f_service``."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, op, pam_u2f

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from sync_mappings import AUTHFILE

__all__ = ["INVENTORY", "SUDO_RULE", "deploy", "main"]

SUDO_RULE = f"auth required pam_u2f.so authfile={AUTHFILE} cue"


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        pam_u2f.enable_pam_u2f_service,
        name="Require U2F for sudo",
        service="sudo",
        rule=SUDO_RULE,
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

Keep an independent root session open for the whole --apply step, and test sudo from a second session before closing it. If the target's /etc/pam.d/sudo does not exist, the operation raises rather than creating one.

Protect SSH logins

SSH needs two things: the PAM rule, and an sshd_config that actually asks the client for a second factor. AuthenticationMethods publickey,keyboard-interactive makes a key mandatory and still prompts through PAM; KbdInteractiveAuthentication yes lets that prompt reach pam_u2f's cue message.

# enable_sshd.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Require a registered key for SSH logins, and match sshd's own prompt."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, files, op, pam_u2f

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from sync_mappings import AUTHFILE

__all__ = [
    "INVENTORY",
    "SSHD_CONFIG_PATH",
    "SSHD_RULE",
    "deploy",
    "main",
    "require_key_and_second_factor",
    "set_ssh_option",
]

SSHD_CONFIG_PATH = "/etc/ssh/sshd_config"
SSHD_RULE = f"auth required pam_u2f.so authfile={AUTHFILE} cue"


def set_ssh_option(current: str | None, option: str, value: str) -> str:
    lines = (current or "").splitlines()
    prefix = option.lower() + " "
    for index, line in enumerate(lines):
        stripped = line.strip()
        if stripped.startswith("#"):
            commented = stripped[1:].lstrip()
            if commented.lower().startswith(prefix) or commented.lower() == option.lower():
                lines[index] = f"{option} {value}"
                break
        elif stripped.lower().startswith(prefix):
            lines[index] = f"{option} {value}"
            break
    else:
        lines.append(f"{option} {value}")
    return "\n".join(lines) + "\n"


def require_key_and_second_factor(current: str | None) -> str:
    text = set_ssh_option(current, "AuthenticationMethods", "publickey,keyboard-interactive")
    return set_ssh_option(text, "KbdInteractiveAuthentication", "yes")


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        pam_u2f.enable_pam_u2f_service,
        name="Require U2F for sshd",
        service="sshd",
        rule=SSHD_RULE,
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        files.transform,
        name="Require key plus second factor in sshd",
        path=SSHD_CONFIG_PATH,
        transform=require_key_and_second_factor,
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

set_ssh_option replaces an active directive or uncomments a matching default; require_key_and_second_factor applies two such edits. Both are module-level, pure functions — required so the plan and apply phases produce identical, hashable requests, and so a second run finds the file already in its desired state. This is a container-lab-safe pattern, not a licence to lock yourself out: apply it from a console or a second, already-authenticated session, and keep the old session open until the new one proves the change did not break the way you log in.

Exempt service accounts

Automated accounts cannot touch a physical key, so they must skip the second factor rather than fail on it. Reemote has no dedicated exemption operation; this example composes server.group, server.user, and a files.transform that inserts a pam_succeed_if skip line directly above the rule added by enable_sshd.py. Run enable_sshd.py --apply first, since the transform is a deliberate no-op when that rule is not yet present.

# exempt_accounts.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Exempt a service-account group from the second factor without a custom module."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, files, op, server

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from enable_sshd import SSHD_RULE
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["EXEMPT_GROUP", "INVENTORY", "PAM_SSHD_PATH", "deploy", "main", "skip_exempt_group"]

EXEMPT_GROUP = "nou2f"
PAM_SSHD_PATH = "/etc/pam.d/sshd"
EXEMPT_SERVICE_ACCOUNT = "monitoring"
SKIP_LINE = (
    f"auth [success=1 default=ignore] pam_succeed_if.so user ingroup {EXEMPT_GROUP}"
)


def skip_exempt_group(current: str | None) -> str:
    """Insert the exemption rule immediately before the article's pam_u2f.so rule."""
    lines = (current or "").splitlines()
    if SKIP_LINE in lines:
        return "\n".join(lines) + "\n"
    for index, line in enumerate(lines):
        stripped = line.strip()
        if stripped and not stripped.startswith("#") and stripped == SSHD_RULE:
            lines.insert(index, SKIP_LINE)
            break
    else:
        return "\n".join(lines) + ("\n" if lines else "")
    return "\n".join(lines) + "\n"


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        server.group,
        name="Ensure the U2F exempt group",
        group=EXEMPT_GROUP,
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        server.user,
        name=f"Add {EXEMPT_SERVICE_ACCOUNT} to {EXEMPT_GROUP}",
        user=EXEMPT_SERVICE_ACCOUNT,
        groups=(EXEMPT_GROUP,),
        append=True,
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        files.transform,
        name="Skip the second factor for exempt accounts",
        path=PAM_SSHD_PATH,
        transform=skip_exempt_group,
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

append=True adds the account to nou2f without dropping its other group memberships. The [success=1 default=ignore] control means "when the user is in this group, skip the one rule that follows" — which is exactly the pam_u2f.so line the previous example inserted. If that line moves or is removed, the skip silently stops matching anything, which is why the transform keys on the rule's exact text rather than a line number.

Restart sshd only when something changed

A notification-style restart becomes two runs connected by the first run's report. changed_hosts freezes the names of hosts whose named request actually changed; the restart deploy then closes over that immutable set and issues nothing at all for a host that converged.

# restart_sshd.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Restart sshd only on the hosts whose second-factor requests actually changed."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import (
    Host,
    OperationRequest,
    changed_hosts,
    format_log,
    format_plan,
    op,
    run,
    systemd,
)

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from enable_sshd import INVENTORY
from enable_sshd import deploy as enable_sshd_deploy
from pam_u2f_article_common import parse_apply_flag

__all__ = ["CHANGED_NAMES", "INVENTORY", "main", "restart"]

CHANGED_NAMES = (
    "Require U2F for sshd",
    "Require key plus second factor in sshd",
)


def restart(host: Host, notified: frozenset[str]) -> Generator[OperationRequest]:
    if host.name in notified:
        yield op(
            systemd.service,
            name="Restart sshd",
            service="sshd",
            running=None,
            restarted=True,
            sudo=True,
        )


async def main() -> None:
    apply_changes = parse_apply_flag(__doc__)

    plans, _report, _hosts = await run(INVENTORY, enable_sshd_deploy, dry=True)
    print("== Dry run ==")
    print(format_plan(plans))
    if not apply_changes:
        print("\nPreview only; pass --apply to change the host.")
        return

    _, report, _hosts = await run(INVENTORY, enable_sshd_deploy)
    assert report is not None
    print(format_log(report))

    notified = changed_hosts(report, CHANGED_NAMES)
    if not notified:
        print("SSH second factor unchanged; no restart needed")
        return

    _, restart_report, _ = await run(INVENTORY, lambda host: restart(host, notified))
    assert restart_report is not None
    print(format_log(restart_report))


if __name__ == "__main__":
    asyncio.run(main())

running=None asks for a restart without a start/stop assertion first; restarted=True acts only on a unit the state fact already reports running. A lambda used outside a yielded request, like the one passed to run() above, is fine; a lambda stored inside an operation argument would break the determinism guard.

Inspect the result

The module's four facts are readable on their own, without a deploy. PamU2fInstalled answers a plain boolean; PamU2fConfig and PamU2fMappings parse active, non-comment lines into a dict and a grouped dict respectively; PamServiceU2fRule reports only whether an active auth line names pam_u2f.so. The example gathers all four across the inventory and closes its connections explicitly.

# inspect_u2f.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Read pam-u2f facts from real hosts without changing anything."""

import asyncio
import json
import sys
from pathlib import Path

from reemote import (
    Host,
    PamServiceU2fRule,
    PamU2fConfig,
    PamU2fInstalled,
    PamU2fMappings,
    gather_fact,
)

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from pam_u2f_article_common import INVENTORY
from sync_mappings import AUTHFILE

__all__ = ["AUTHFILE", "INVENTORY", "SERVICES", "main"]

SERVICES = ("sshd", "sudo")


async def main() -> None:
    hosts = [Host.from_inventory(entry) for entry in INVENTORY]
    try:
        installed = await gather_fact(hosts, PamU2fInstalled)
        configs = await gather_fact(hosts, PamU2fConfig, sudo=True)
        mappings = await gather_fact(hosts, PamU2fMappings, AUTHFILE, sudo=True)
        rules = {
            service: await gather_fact(
                hosts, PamServiceU2fRule, service, sudo=True
            )
            for service in SERVICES
        }
        for host in hosts:
            print(f"== {host.name} ==")
            print("installed:", installed[host.name])
            print("config:", json.dumps(configs[host.name], indent=2))
            print("mappings:", json.dumps(mappings[host.name], indent=2))
            for service in SERVICES:
                print(f"rule {service}:", rules[service][host.name])
    finally:
        await asyncio.gather(*(host.aclose() for host in hosts))


if __name__ == "__main__":
    asyncio.run(main())

gather_fact reads every host concurrently for one fact at a time and returns a dictionary keyed by host name. Unlike run(), it does not own or close the hosts passed to it, which is why the finally block closes them. Missing or unreadable protected files produce an empty dict or False rather than an error, so this is safe to run before anything has been installed.

Roll back

enable_pam_u2f_service deliberately has no inverse: it only ever appends, so it cannot rewrite a stack it did not write. Removing the article's rules is a plain, reviewable files.transform that filters the exact lines back out and restores the sshd options to a key-only default.

# rollback.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Remove the article's second-factor rules and restore the sshd options."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, files, op

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from enable_sshd import SSHD_CONFIG_PATH, SSHD_RULE, set_ssh_option
from enable_sudo import SUDO_RULE
from exempt_accounts import SKIP_LINE
from pam_u2f_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["INVENTORY", "PAM_SSHD_PATH", "PAM_SUDO_PATH", "deploy", "main", "strip_u2f_rules"]

PAM_SSHD_PATH = "/etc/pam.d/sshd"
PAM_SUDO_PATH = "/etc/pam.d/sudo"


def strip_u2f_rules(current: str | None) -> str:
    """Drop the article's pam_u2f.so and exemption lines, keep everything else."""
    removed = {SSHD_RULE, SUDO_RULE, SKIP_LINE}
    lines = [line for line in (current or "").splitlines() if line.strip() not in removed]
    return "\n".join(lines) + ("\n" if lines else "")


def restore_sshd_options(current: str | None) -> str:
    text = set_ssh_option(current, "AuthenticationMethods", "publickey")
    return set_ssh_option(text, "KbdInteractiveAuthentication", "no")


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        files.transform,
        name="Strip U2F rule from sshd PAM stack",
        path=PAM_SSHD_PATH,
        transform=strip_u2f_rules,
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        files.transform,
        name="Strip U2F rule from sudo PAM stack",
        path=PAM_SUDO_PATH,
        transform=strip_u2f_rules,
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        files.transform,
        name="Restore sshd authentication options",
        path=SSHD_CONFIG_PATH,
        transform=restore_sshd_options,
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

Apply the restart idea from restart_sshd.py again after this — a rollback of an active sshd PAM stack is exactly the case where a restart is warranted. The removal matches on the exact rule text; a rule edited by hand after enable_pam_u2f_service appended it is not matched, and remains in place, which is the safer failure mode.

Put it together

The individual scripts above are the same requests, in dependency order, in one deploy. install must precede the file operations, and sync_mappings should precede any service that will actually consult the authfile.

# deploy_2fa.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Compose the article's individual requests into one two-factor deploy."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from configure_global import deploy as configure_deploy
from enable_sshd import deploy as enable_sshd_deploy
from enable_sudo import deploy as enable_sudo_deploy
from exempt_accounts import deploy as exempt_deploy
from install_u2f import deploy as install_deploy
from pam_u2f_article_common import INVENTORY, execute, parse_apply_flag
from sync_mappings import deploy as sync_deploy

__all__ = ["INVENTORY", "deploy", "main"]


def deploy(host: Host) -> Generator[OperationRequest]:
    """Yield the article's requests in dependency order: install, configure,
    enroll, then protect each service."""
    yield from install_deploy(host)
    yield from configure_deploy(host)
    yield from sync_deploy(host)
    yield from enable_sudo_deploy(host)
    yield from enable_sshd_deploy(host)
    yield from exempt_deploy(host)


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())

Each nested deploy already carries its own when=is_ubuntu guard, so composing them with yield from adds no new branching. The requests stay separate and named, which means the plan still shows nine distinct lines rather than one opaque blob, and changed_hosts can still address any of them by name from a handler run.

Test the examples, then check convergence

The focused pytest suite imports every script, validates its inventory and requests, and applies the installing, configuring, mapping, enabling, exempting, rolling-back and combined deploys twice each against one persistent SimulatedHost, asserting the second pass reports no change:

.venv/bin/python -m pytest -q tests/test_pam_u2f_article_examples.py

For the real Ubuntu host, preview every script first, then apply this order; every step should already be converged when it is repeated:

python examples/articles/pam_u2f/install_u2f.py --apply
python examples/articles/pam_u2f/configure_global.py --apply
python examples/articles/pam_u2f/sync_mappings.py --apply
python examples/articles/pam_u2f/enable_sudo.py --apply
python examples/articles/pam_u2f/enable_sshd.py --apply
python examples/articles/pam_u2f/exempt_accounts.py --apply
python examples/articles/pam_u2f/inspect_u2f.py

Rerun the mutating steps above, except sync_mappings.py with placeholder credentials, to confirm each reports no change. deploy_2fa.py --apply reaches the same converged state from a clean host in one pass, and a second deploy_2fa.py --apply reports none. When you are done, remove the article's changes:

python examples/articles/pam_u2f/rollback.py --apply
python examples/articles/pam_u2f/restart_sshd.py --apply
python examples/articles/pam_u2f/rollback.py --apply

The second rollback reports no change, which is the point: removal is as idempotent as installation. The scripts touch only /etc/security/pam_u2f.conf, /etc/u2f_mappings, /etc/pam.d/sshd, /etc/pam.d/sudo and /etc/ssh/sshd_config, always through a spool-and-install that never puts credential contents in a plan or a log. They do not remove the installed package, and they leave the nou2f group and the monitoring account in place for a separate cleanup decision.

Implementation summary

Reemote's pam_u2f module pairs whole-file facts with control-side reconciliation. PamU2fInstalled searches the standard library directories with a portable find -print -quit loop, so an architecture-specific subdirectory is found without assuming x86_64. PamU2fConfig, PamU2fMappings and PamServiceU2fRule each read a protected file through one shared raw-content fact and parse only active, non-comment lines in Python; a missing or unreadable file answers empty rather than raising. Reads that a plain login cannot perform retry automatically with the inventory's supported privilege mechanism.

The four operations follow the spool-and-install family. install_pam_u2f yields a single command that selects apt-get, dnf or apk on the target, so one request is correct on every supported family without importing their package managers. configure_pam_u2f and sync_u2f_mappings render the complete desired file from immutable (name, value) and user-to-credentials tuples — deliberately tuples, because reemote operation requests must be hashable and deterministic — validate the result, and compare it against the live file and its ownership and mode separately. Matching content with wrong metadata repairs permissions without rewriting a byte; differing content spools the new text with an unprivileged transfer and installs it as root:root with the operation's restrictive mode. enable_pam_u2f_service appends exactly one validated rule and never rewrites a stack it did not write. Transfer logs redact file contents, including credentials.

What this leaves out is the part that cannot be automated: enrollment. pamu2fcfg needs a connected authenticator and a physical touch, so the credential values in sync_mappings.py are placeholders you replace by hand. Everything around that step — the package, the config, the authfile, the PAM rule, the sshd options, the exempt group, the restart and the rollback — is ordinary Python you can import, unit-test, preview and await. The module reference contains the complete API, and the examples index describes the shared real-host execution contract.

References

pam-u2f background

Reemote

No comments yet. Be the first to comment.