2fa users mandatory

Is there any way to force home assistant to force all users to use 2FA? or if there is no way to force them at least to create a script to warn me when a user does not have 2FA active?

As I could not find an option to force at least I have considered the option to make a warning script to control that everyone has 2FA active.

  1. create a permanent token from admin user security for the api

  2. in the /homeassistant/configuration.yaml create the shell_command

shell_command: !include shell_command.yaml

and in the shell_command.yaml

usuarios_sin_2fa: "/usr/bin/python3 /config/shell/usuarios_sin_2fa.py"
  1. create the script /homeassistant/shell/users_sin_2fa.py with the token
#!/usr/bin/env python3
import json
import subprocess
import os  # Añadido la importación de os

# Configura estos valores según tu instalación
BASE_URL = "https://localhost:8123"  # Dirección IP local
TOKEN = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Token largo de acceso
INPUT_TEXT_ENTITY = "input_text.usuarios_sin_2fa"  # Entidad del helper

# Rutas de los archivos
auth_file = "/homeassistant/.storage/auth"
totp_file = "/homeassistant/.storage/auth_module.totp"
auth_provider_file = "/homeassistant/.storage/auth_provider.homeassistant"

# Verificar si los archivos existen
for file_path in [auth_file, totp_file, auth_provider_file]:
    if not os.path.exists(file_path):
        print(f"Error: El archivo {file_path} no existe.")
        exit(1)

# Cargar datos de los archivos
try:
    with open(auth_file, "r") as f:
        auth_data = json.load(f)
    with open(totp_file, "r") as f:
        totp_data = json.load(f)
    with open(auth_provider_file, "r") as f:
        auth_provider_data = json.load(f)
except Exception as e:
    print(f"Error al cargar los archivos: {e}")
    exit(1)

# Extraer información de los usuarios
auth_users = auth_data.get("data", {}).get("users", [])
totp_users = totp_data.get("data", {}).get("users", {})
auth_provider_users = auth_provider_data.get("data", {}).get("users", [])

# Crear un conjunto de usuarios con contraseña configurada
users_with_password = {user["username"] for user in auth_provider_users if "password" in user}

# Identificar usuarios sin 2FA, con contraseña configurada y sin exclusión por condiciones adicionales
users_without_2fa = []
for user in auth_users:
    user_id = user.get("id")
    user_name = user.get("name", "Desconocido")
    system_generated = user.get("system_generated", True)
    local_only = user.get("local_only", False)
    group_ids = user.get("group_ids", [])

    # Excluir usuarios si cumplen ambas condiciones:
    # 1. "local_only" es True
    # 2. Pertenecen al grupo "system-users"
    if local_only and "system-users" in group_ids:
        continue

    # Ignorar usuarios del sistema o aquellos sin contraseña configurada
    if system_generated or user_name not in users_with_password:
        continue

    # Verificar si no tienen 2FA
    if user_id not in totp_users:
        users_without_2fa.append(user_name)

# Verificar si hay usuarios sin 2FA y preparar el mensaje a enviar a la API
result = ",".join(users_without_2fa) if users_without_2fa else ""

# Preparar los datos a enviar en el formato adecuado para Home Assistant
url = f"{BASE_URL}/api/states/{INPUT_TEXT_ENTITY}"

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json",
}

payload = {
    "state": result,
}

# Ejecutar la solicitud curl a la API de Home Assistant con la opción -k para ignorar SSL
command = [
    "curl",
    "-k",  # Deshabilitar la verificación SSL
    "-X", "POST",
    url,
    "-H", f"Authorization: Bearer {TOKEN}",
    "-H", "Content-Type: application/json",
    "-d", json.dumps(payload)
]

# Ejecutar el comando curl
try:
    subprocess.run(command, check=True)
    print(f"Resultado enviado a Home Assistant: {result}")
except subprocess.CalledProcessError as e:
    print(f"Error al enviar la solicitud: {e}")
    exit(1)

  1. create a text helper that will pick up users that does not meet 2FA requirements - name users_without_2fa

  2. place the helper in a visible panel

  3. from terminal run

dos2unix /homeassistant/shell/usuarios_sin_2fa.py
/homeassistant/shell/usuarios_sin_2fa.py
  1. we will see how in a card of entity it leaves collected the users that do not fulfill the conditions I can simulate by hand that one is deulve…

  2. execution of the script and warning of results. Automatism every hour that executes the Shell, waits 60 seconds, and checks if the result is not empty warning with a message.

I can’t manage to do step 8, I can’t manage to run the script from HA and make it work as it does from terminal, can anyone help me?

No one can help me with how to run this script automatically? is there any way?

I tried to configure it in the cron and it didn’t work, to put it in the /etc/peridoic/hourly folder and it didn’t work, I don’t know what else to try… how can I run the /homeassistant/shell/users_sin_2fa.py script automatically every hour?

I got it! creating a second script that connects via ssh on localhost and executes the first as sudo solved the issue!