repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
enable-keyboard276 lines13.6 KiBraw download
#!/usr/bin/env bash
# enable-keyboard — turn the internal keyboard back on (TongFang GM7RGxM / PCSpecialist Valeon II 17)
#
# Root cause (see README.md): kernel >= 6.0 skips the ACPI IRQ override on AMD Zen; this board is
# missing from the kernel's fix table, so IRQ 1 is programmed edge/ACTIVE-LOW while the EC signals
# active-high -> the keyboard is dead in Linux, fine in BIOS.
#
# Usage:
#   sudo enable-keyboard            do the next right thing (state machine; run again after reboot)
#   sudo enable-keyboard now        no-reboot fix: kernel module flips IRQ1 polarity live (attended!)
#   sudo enable-keyboard now revert undo a 'now' fix in the same boot
#   sudo enable-keyboard persist    run the 'now' fix automatically at every boot (after ONE verified success)
#   sudo enable-keyboard unpersist  remove that boot service
#   sudo enable-keyboard revert     remove the boot-preset drop-in (then reboot)
#   enable-keyboard status          (no root) where things stand
#
# Mechanisms, in the order this program reaches for them:
#   1. pnpacpi=off boot preset — the one stock-kernel cmdline that prevents the wrong-polarity
#      programming at its source (PNP-ACPI never parses the DSDT's IRQ1 descriptor). One reboot.
#   2. irq1fix.ko — flips IRQ1 polarity in the kernel's IOAPIC bookkeeping while i8042 is unbound,
#      then rebinding i8042 makes the kernel program the corrected IOAPIC entry itself. No reboot.
#   Durable fixes (do one eventually): PCSpecialist BIOS/EC update ticket, the one-line upstream
#   kernel patch (0001-acpi-resource-irq1-override-gm7rgxm.patch), or a DSDT override — see README.
#
# NB: no pipefail — several probes are `big-stream | grep -q`, and grep -q's early
# exit SIGPIPEs the producer, which pipefail would misreport as probe failure.
set -u

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
INKBD="$SCRIPT_DIR/inkbd"
MODDIR="$SCRIPT_DIR/irq1fix"
MOD="$MODDIR/irq1fix.ko"
I8042_DRV="/sys/bus/platform/drivers/i8042"
UNIT=/etc/systemd/system/enable-keyboard.service
DROPIN=/etc/limine-entry-tool.d/95-inkbd-i8042.conf   # shared with 'inkbd boot' so both reverts work

if [[ -t 1 ]]; then C0=$'\e[0m'; CB=$'\e[1m'; CG=$'\e[32m'; CY=$'\e[33m'; CR=$'\e[31m'; else C0="" CB="" CG="" CY="" CR=""; fi
say()  { printf '%s\n' "$*"; }
ok()   { say "${CG}[ok]${C0} $*"; }
warn() { say "${CY}[!!]${C0} $*"; }
bad()  { say "${CR}[XX]${C0} $*"; }
need_root() { [[ $EUID -eq 0 ]] || { echo "needs root: sudo $(basename "$0") $*" >&2; exit 1; }; }

# ---------- probes ----------
pnpacpi_live()      { tr ' ' '\n' < /proc/cmdline | grep -qx 'pnpacpi=off'; }
dropin_installed()  { [[ -f $DROPIN ]] && grep -q 'pnpacpi=off' "$DROPIN"; }
kbd_serio()         { # the KBD port moves across rebinds (serio0→serio1→serio5) — find it live
  local d
  for d in /sys/bus/serio/devices/serio*; do
    grep -q 'i8042 KBD port' "$d/description" 2>/dev/null && { echo "$d"; return 0; }
  done
  return 1
}
atkbd_bound()       { local d; d="$(kbd_serio)" || return 1
  [[ "$(basename "$(readlink -f "$d/driver" 2>/dev/null)" 2>/dev/null)" == atkbd ]]; }
kmsg() { { [[ $EUID -eq 0 ]] && dmesg || journalctl -k -b 0 --no-pager -q; } 2>/dev/null; }
init_failed_this_boot() { # the LAST atkbd probe this boot did not register cleanly -> keyboard NOT working
  kmsg | grep -E 'serio: i8042 KBD port|atkbd serio[0-9]+: Failed to (deactivate|enable) keyboard|input: AT Translated Set 2 keyboard' \
    | awk '/serio: i8042 KBD port/ { fail = 0; reg = 0 }
           /Failed to (deactivate|enable) keyboard/ { fail = 1 }
           /input: AT Translated Set 2 keyboard/ { reg = 1 }
           END { exit (reg && !fail) ? 1 : 0 }'
}
noctrl_this_boot()  { kmsg | grep -q 'No PS/2 controller found'; }
healthy() { atkbd_bound && ! init_failed_this_boot; }
irq1_owner_is_i8042() { grep -E '^\s*1:' /proc/interrupts | grep -q 'i8042'; }
fadt_8042_flag() { # 0=flag clear (i8042 direct probe may refuse), 1=set, 2=unreadable
  python3 - <<'PY' 2>/dev/null || echo 2
try:
    d = open('/sys/firmware/acpi/tables/FACP','rb').read()
    print((int.from_bytes(d[109:111],'little') >> 1) & 1)
except Exception:
    print(2)
PY
}

# ---------- module ----------
build_module() {
  [[ -d "/usr/lib/modules/$(uname -r)/build" ]] || { bad "linux-headers for $(uname -r) not installed"; return 1; }
  if [[ -f "$MOD" ]] && modinfo -F vermagic "$MOD" 2>/dev/null | grep -q "^$(uname -r) "; then return 0; fi
  say "building irq1fix.ko for $(uname -r)…"
  make -C "$MODDIR" >/dev/null 2>&1 || make -C "$MODDIR" || { bad "module build failed"; return 1; }
  modinfo -F vermagic "$MOD" 2>/dev/null | grep -q "^$(uname -r) " || { bad "built module vermagic does not match running kernel"; return 1; }
}
apply_module() { # $1 = "" | "revert=1" ; flips IRQ1 polarity with i8042 safely unbound. Rebind is guaranteed.
  local arg="${1:-}" rc=1
  irq1_owner_is_i8042 || { bad "IRQ 1 is not owned solely by i8042 (see /proc/interrupts) — refusing"; return 1; }
  [[ -e $I8042_DRV/unbind ]] || { bad "i8042 platform driver not present"; return 1; }
  lsmod | grep -q '^irq1fix' && rmmod irq1fix 2>/dev/null
  trap 'printf i8042 > "$I8042_DRV/bind" 2>/dev/null' EXIT INT TERM
  printf 'i8042' > "$I8042_DRV/unbind" 2>/dev/null || { bad "could not unbind i8042"; trap - EXIT INT TERM; return 1; }
  say "i8042 unbound (IRQ 1 released, nothing can race the change)"
  if insmod "$MOD" $arg 2>/dev/null; then
    ok "irq1fix: polarity flipped in the kernel's IRQ bookkeeping"
    rc=0
  else
    bad "irq1fix refused (see: dmesg | grep irq1fix) — nothing was changed"
  fi
  printf 'i8042' > "$I8042_DRV/bind" 2>/dev/null
  trap - EXIT INT TERM
  if [[ -e $I8042_DRV/i8042 ]]; then
    ok "i8042 re-bound — the kernel just re-programmed the IOAPIC entry from the (fixed) IRQ data"
  else
    bad "i8042 did NOT re-bind — check 'dmesg | tail'; a reboot restores it"
    rc=1
  fi
  rmmod irq1fix 2>/dev/null || true
  return $rc
}
verify_fix() {
  sleep 2
  say ""
  say "${CB}Verification 1/2 — EC echo (no touching any keyboard):${C0}"
  local out; out="$("$INKBD" ledecho 2 2>&1)"; printf '%s\n' "$out"
  local inwin; inwin="$(grep -oE 'on-window \+[0-9]+' <<<"$out" | grep -oE '[0-9]+' | awk '{s+=$1} END {print s+0}')"
  if (( inwin >= 2 )); then
    ok "EC replies now arrive IN the same window (before: one window late) — IRQ delivery is fixed"
  else
    warn "EC replies still not landing in-window (in-window total: ${inwin:-0})"
  fi
  say ""
  say "${CB}Verification 2/2 — type on the INTERNAL keyboard for 8 s:${C0}"
  "$INKBD" watch 8
}

# ---------- subcommands ----------
cmd_status() {
  say "keyboard        : $(healthy && echo "${CG}WORKING${C0} (atkbd init clean this boot)" || echo "${CR}not working${C0}")"
  say "pnpacpi=off     : live=$(pnpacpi_live && echo yes || echo no) drop-in=$(dropin_installed && echo installed || echo no)"
  pnpacpi_live && noctrl_this_boot \
    && say "                  ${CR}BACKFIRED this boot: i8042 found no controller — revert + reboot${C0}"
  say "irq1fix module  : $([[ -f $MOD ]] && echo "built ($(modinfo -F vermagic "$MOD" 2>/dev/null | awk '{print $1}'))" || echo 'not built')"
  local svc; svc="$(systemctl is-enabled enable-keyboard.service 2>/dev/null)"
  [[ -z "$svc" || "$svc" == not-found ]] && svc="not installed"
  say "boot service    : $svc"
  say "IRQ 1           : $(grep -E '^\s*1:' /proc/interrupts | awk '{for(i=NF-2;i<=NF;i++) printf "%s ", $i; s=0; for(i=2;i<=NF-3;i++) s+=$i; printf "(%d since boot)", s}' | grep . || echo 'not registered this boot (no i8042)')"
}
cmd_auto() {
  need_root
  if healthy; then
    ok "The internal keyboard is WORKING this boot."
    if pnpacpi_live; then
      say "  Working via the pnpacpi=off boot preset — leave it in place. It survives kernel updates."
    elif systemctl is-enabled enable-keyboard.service &>/dev/null; then
      say "  Working via the boot-time irq1fix service."
    fi
    say "  For a durable, side-effect-free fix see README.md: PCSpecialist BIOS/EC ticket,"
    say "  the upstream kernel patch (0001-acpi-resource-irq1-override-gm7rgxm.patch), or the DSDT override."
    return 0
  fi
  if pnpacpi_live; then
    bad "pnpacpi=off is live but the keyboard still failed its init this boot."
    if noctrl_this_boot; then
      warn "i8042 refused to probe directly ('No PS/2 controller found') — the firmware's FADT does not advertise the 8042."
      say  "  -> revert the preset and REBOOT:  sudo $(basename "$0") revert"
      if systemctl is-enabled enable-keyboard.service &>/dev/null; then
        say  "     enable-keyboard.service is enabled — after the reboot it applies the live fix automatically."
      else
        say  "     after the reboot:  sudo $(basename "$0") persist   (live fix at every boot)"
      fi
      say  "     Nothing can fix THIS boot: i8042 is built-in and its probe already failed."
    else
      warn "The polarity hypothesis may be wrong for this board, or something else is going on."
      say  "  -> run: sudo $INKBD diag   and share the log. Durable options in README still apply."
    fi
    return 1
  fi
  if dropin_installed; then
    warn "The pnpacpi=off preset is installed but this boot doesn't have it yet."
    say  "  -> REBOOT, then run: sudo $(basename "$0")   again to verify."
    return 0
  fi
  # nothing installed yet: pick the primary fix for THIS firmware
  case "$(fadt_8042_flag)" in
    1)
      say "${CB}Installing the primary fix: pnpacpi=off boot preset (one reboot needed).${C0}"
      ok "FADT advertises the 8042 — i8042 will probe the legacy ports directly under pnpacpi=off."
      "$INKBD" boot pnpacpi || { bad "preset install failed"; return 1; }
      say ""
      ok "Done. ${CB}REBOOT now${C0}, then run:  sudo $(basename "$0")   to verify (it will say WORKING or advance the plan)."
      say "No reboot possible right now? Use the live fix instead:  sudo $(basename "$0") now"
      ;;
    *)
      warn "FADT does not advertise an 8042 (IAPC_BOOT_ARCH bit clear) — under pnpacpi=off, i8042 finds no controller at all ('No PS/2 controller found'; confirmed on this machine 2026-08-30). NOT installing that preset."
      say "${CB}Primary fix on this firmware: live irq1fix now + re-apply at every boot (enable-keyboard.service).${C0}"
      build_module || return 1
      apply_module "" || return 1
      cmd_persist || return 1
      verify_fix
      ;;
  esac
}
cmd_now() {
  need_root
  local mode="${1:-}"
  if [[ "$mode" == revert ]]; then
    build_module && apply_module "revert=1" && ok "reverted to original (broken) polarity"
    return
  fi
  if pnpacpi_live; then
    if noctrl_this_boot; then
      bad "pnpacpi=off is live and i8042 found NO controller this boot (FADT backfire) — the driver is built-in and its probe already failed; nothing can fix THIS boot."
      say "Revert + reboot:  sudo $(basename "$0") revert    (the boot service, if enabled, then applies the live fix automatically)"
    else
      bad "pnpacpi=off is live — IRQ 1 already has the correct polarity this boot; the module has nothing to fix."
      say "If the keyboard is still dead, run: sudo $INKBD diag"
    fi
    return 1
  fi
  if healthy; then ok "keyboard already working — nothing to do"; return 0; fi
  say "${CB}Live fix: flip IRQ 1 to active-high via irq1fix.ko (no reboot).${C0}"
  say "This briefly unbinds the i8042 driver; the external USB keyboard is unaffected either way."
  build_module || return 1
  apply_module "" || return 1
  verify_fix
  say ""
  say "If it types: make it permanent with ONE of:"
  if [[ "$(fadt_8042_flag)" == 1 ]]; then
    say "  A) sudo $(basename "$0")            (installs the pnpacpi=off boot preset — kernel-native, recommended)"
    say "  B) sudo $(basename "$0") persist    (re-applies this live fix at every boot — zero side effects, needs headers after kernel updates)"
  else
    say "  A) sudo $(basename "$0") persist    (re-applies this live fix at every boot — recommended; needs headers after kernel updates)"
    say "     (the pnpacpi=off preset is NOT offered: this firmware's FADT does not advertise the 8042, so under it i8042 finds no controller at all)"
  fi
  say "Undo this session's change: sudo $(basename "$0") now revert"
}
cmd_persist() {
  need_root
  build_module || return 1
  cat > "$UNIT" <<EOF
[Unit]
Description=enable-keyboard: runtime IRQ1 polarity fix (TongFang GM7RGxM AMD-Zen ACPI IRQ override bug)
ConditionKernelCommandLine=!pnpacpi=off
ConditionPathExists=$SCRIPT_PATH
After=systemd-udevd.service
Before=display-manager.service

[Service]
Type=oneshot
ExecStart=$SCRIPT_PATH boot-apply

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload && systemctl enable enable-keyboard.service \
    && ok "installed enable-keyboard.service (applies the live fix at every boot; skips itself if pnpacpi=off is on the cmdline). Undo: sudo $(basename "$0") unpersist"
}
cmd_unpersist() {
  need_root
  systemctl disable enable-keyboard.service 2>/dev/null; rm -f "$UNIT"; systemctl daemon-reload; ok "removed"
}
cmd_boot_apply() { # systemd entry point: must NEVER fail the boot or leave i8042 unbound
  pnpacpi_live && exit 0
  healthy && exit 0
  build_module || { echo "enable-keyboard: module unavailable for $(uname -r) (headers missing/build failed) — skipping, keyboard stays on fallback"; exit 0; }
  apply_module "" || true
  exit 0
}
cmd_revert() {
  need_root
  "$INKBD" boot revert
  say "reboot to run without the preset"
}

case "${1:-auto}" in
  auto)       cmd_auto ;;
  now)        cmd_now "${2:-}" ;;
  persist)    cmd_persist ;;
  unpersist)  cmd_unpersist ;;
  boot-apply) cmd_boot_apply ;;
  revert)     cmd_revert ;;
  status)     cmd_status ;;
  -h|--help|help) sed -n '2,30p' "$SCRIPT_PATH" | sed 's/^# \{0,1\}//' ;;
  *) echo "unknown subcommand: $1 (see: enable-keyboard help)"; exit 2 ;;
esac