environment/bin/admin/single-user

80 lines
2.5 KiB
Bash
Executable file

#!/bin/bash
## This script make autologin. If user has phisical access
## to the device we can trust him, otherwiese we require password
## for remote access
#!/bin/bash
set -euo pipefail
# Settings
USERNAME="user"
if [ "$(id -u)" -ne 0 ]; then
echo "Please run this script as root." >&2
exit 1
fi
id "$USERNAME" &>/dev/null || { echo "User '$USERNAME' does not exist." >&2; exit 1; }
echo "Configuring passwordless sudo ONLY on local TTYs for $USERNAME"
echo
SUDOERS_FILE="/etc/sudoers.d/90-$USERNAME-sudo"
if [ ! -f "$SUDOERS_FILE" ]; then
echo "$USERNAME ALL=(ALL:ALL) ALL" > "$SUDOERS_FILE"
chmod 0440 "$SUDOERS_FILE"
visudo -cf "$SUDOERS_FILE" >/dev/null || { echo "sudoers validation failed"; exit 1; }
fi
# PAM: allow passwordless sudo on physical ttys, require password otherwise.
PAM_FILE="/etc/pam.d/sudo"
BACKUP_FILE="/etc/pam.d/sudo.bak"
if ! grep -q "BEGIN local TTY passwordless" "$PAM_FILE"; then
echo "Backing up $PAM_FILE to $BACKUP_FILE"
cp "$PAM_FILE" "$BACKUP_FILE"
# Insert at the top of the file:
# - If TTY matches /dev/ttyN (real VT), immediately permit auth (no password).
# - Otherwise fall through to the normal rules (which will ask for a password).
#
# Notes:
# - pam_succeed_if.so is in the libpam-modules package on Debian/Ubuntu (ensure installed).
# - The 'success=done' short-circuits the auth stack on real TTYs.
tmp="$(mktemp)"
cat > "$tmp" <<'PAMHEAD'
# --- BEGIN local TTY passwordless ---
# Passwordless sudo on real virtual consoles only:
# /dev/tty1, /dev/tty2, ... (NOT /dev/pts/* used by SSH)
auth [success=done default=ignore] pam_succeed_if.so tty =~ ^/dev/tty[0-9]+$
# --- END local TTY passwordless ---
PAMHEAD
cat "$PAM_FILE" >> "$tmp"
mv "$tmp" "$PAM_FILE"
echo "PAM updated. On SSH (/dev/pts/*) a password will be required."
else
echo "PAM sudo already has local TTY rule."
fi
# 3) Autologin on tty1 (physical console)
echo "Configuring systemd autologin on tty1 for $USERNAME..."
mkdir -p /etc/systemd/system/getty@tty1.service.d
AUTOLOGIN_CONF="/etc/systemd/system/getty@tty1.service.d/override.conf"
AGETTY_BIN="$(command -v agetty || true)"
: "${AGETTY_BIN:=/sbin/agetty}"
cat > "$AUTOLOGIN_CONF" <<EOF
[Service]
ExecStart=
ExecStart=-$AGETTY_BIN --autologin $USERNAME --noclear %I \$TERM
EOF
systemctl daemon-reload
systemctl restart getty@tty1
echo
echo "$USERNAME will auto-login on tty1."
echo "• On real TTYs (/dev/ttyN), sudo won't prompt for a password."
echo "• Over SSH (/dev/pts/*), sudo will require the user's password."