#!/bin/bash
#
# mx-dkms-newkey - the system's own dkms signing key for prebuilt modules
#
# A system installed from the ISO (or a snapshot made for distribution)
# has the dkms modules signed with the ISO's key, without its private key
# (/var/lib/dkms/mok.key). This creates the system's own key pair, limited
# to module signing, and re-signs the dkms modules with it, so prebuilt and
# later built modules use the same key. Nothing is enrolled here.
#
# Does nothing when mok.key is present, mok.pub is missing, a key is set in
# /etc/dkms/framework.conf(.d), or no dkms module is signed. Refused in a
# live session without --root. Asks before changing anything, unless --yes.
#
#   mx-dkms-newkey [--yes] [--root DIR]
#
# Called by the installer: live-to-installed runs it with --yes --root for
# the installed system mounted at DIR.
#
# part of mx-system, fehlix@mxlinux.org November 2026

ME=${0##*/}
R=
YES=

die()  { echo "$ME: $*" >&2; exit 1; }
say()  { echo "$ME: $*" >&2; }      # stderr: the installer logs it

while [ $# -gt 0 ]; do
    case $1 in
        --root) [ -n "${2:-}" ] || die "--root needs a directory"; R=${2%/}; shift 2 ;;
        -y|--yes) YES=1; shift ;;
        -h|--help) sed -n '3,16p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) die "unknown argument: $1" ;;
    esac
done
[ -z "$R" ] && [ "$(id -u)" != 0 ] && die "run as root"
[ -z "$R" ] || [ -d "$R" ] || die "not a directory: $R"
[ -z "$R" ] && [ -d /live/aufs ] && die "live system: this is run by the installer for the installed system"

dir=$R/var/lib/dkms
key=$dir/mok.key pub=$dir/mok.pub

# last assignment of a framework.conf variable (dkms reads these files in this order)
conf_get() {
    local conf v='' l
    for conf in "$R"/etc/dkms/framework.conf "$R"/etc/dkms/framework.conf.d/*.conf; do
        [ -r "$conf" ] || continue
        l=$(sed -nE "s/^[[:space:]]*(export[[:space:]]+)?$1=//p" "$conf" | tail -n 1)
        [ -n "$l" ] || continue
        l=${l%%#*}; l=${l%"${l##*[![:space:]]}"}; l=${l#[\"\']}; v=${l%[\"\']}
    done
    printf '%s' "$v"
}

serial_norm() {     # 0A:1B:... or 0A1B... -> 1B... (upper case, no colons, no leading zeros)
    local s=${1//:/}
    s=${s^^}
    while [ "${s#0}" != "$s" ] && [ ${#s} -gt 1 ]; do s=${s#0}; done
    printf '%s' "$s"
}

# --- nothing to do? ---------------------------------------------------------
[ -f "$key" ] && { say "nothing to do: ${key#"$R"} present"; exit 0; }
[ -f "$pub" ] || { say "nothing to do: no ${pub#"$R"}"; exit 0; }
[ -n "$(conf_get mok_signing_key)$(conf_get mok_certificate)" ] && { say "nothing to do: key set in /etc/dkms/framework.conf"; exit 0; }

for c in openssl modinfo; do
    command -v $c >/dev/null 2>&1 || die "missing command: $c"
done

magic='~Module signature appended~'

unpack() {          # module file -> plain .ko on stdout (by suffix, as dkms names them)
    case $1 in
        *.ko.xz)  xz -dc -- "$1" ;;
        *.ko.zst) zstd -dcq -- "$1" ;;
        *.ko.gz)  gzip -dc -- "$1" ;;
        *.ko)     cat -- "$1" ;;
    esac
}

has_sig() {         # plain .ko ends with the module signature mark? (no /dev/fd needed)
    tail -c 28 "$1" | cmp -s - "$work/magic"
}

need_for() {        # the packer for a suffix must be there
    case $1 in
        *.ko.xz)  command -v xz   >/dev/null 2>&1 || die "missing command: xz" ;;
        *.ko.zst) command -v zstd >/dev/null 2>&1 || die "missing command: zstd" ;;
        *.ko.gz)  command -v gzip >/dev/null 2>&1 || die "missing command: gzip" ;;
    esac
}

work=$(mktemp -d "$dir/.newkey.XXXXXX") || die "cannot create a work directory in $dir"
trap 'rm -rf -- "$work"' EXIT
printf '%s\n' "$magic" > "$work/magic"

# signed dkms modules: the installed ones and dkms's own copies
# (signed = the module signature mark at the end of the unpacked module)
# The forms are the ones dkms 3.x writes (set_module_suffix: .ko, .ko.gz,
# .ko.xz, .ko.zst). A new form needs unpack(), need_for() and the pack step
# below as well; files in other forms are not seen here.
mods=()
shopt -s nullglob
for m in "$R"/lib/modules/*/updates/dkms/*.ko{,.gz,.xz,.zst} \
         "$R"/var/lib/dkms/*/*/*/*/module/*.ko{,.gz,.xz,.zst}; do
    [ -f "$m" ] && [ ! -L "$m" ] || continue
    need_for "$m"
    unpack "$m" > "$work/probe.ko" 2>/dev/null || die "${m#"$R"}: could not unpack"
    has_sig "$work/probe.ko" && mods+=("$m")
done
shopt -u nullglob
rm -f -- "$work/probe.ko"
[ ${#mods[@]} -gt 0 ] || { say "nothing to do: no signed dkms modules"; exit 0; }

# --- confirmation (the installer passes --yes) ----------------------------------
if [ -z "$YES" ]; then
    [ -t 0 ] || die "would create a new key and re-sign ${#mods[@]} dkms module file(s): needs --yes (nothing changed)"
    cat >&2 <<EOT
$ME: this creates a new dkms signing key for this system and re-signs
${#mods[@]} dkms module file(s) (e.g. Wi-Fi drivers) with it.
With Secure Boot on, these drivers do NOT load until the new key is enrolled:
    sudo mokutil --import /var/lib/dkms/mok.pub
    then reboot and choose "Enroll MOK" in the blue MOK Manager screen.
EOT
    printf 'Continue? [y/N] ' >&2
    read -r answer || answer=
    case $answer in
        y|Y|yes|Yes|YES) ;;
        *) say "cancelled, nothing changed"; exit 0 ;;
    esac
fi

# kernel version of a module path
kver_of() {
    case $1 in
        "$R"/lib/modules/*) local p=${1#"$R"/lib/modules/}; printf '%s' "${p%%/*}" ;;
        *) local p=${1%/*/module/*}; printf '%s' "${p##*/}" ;;      # .../KVER/ARCH/module/x.ko
    esac
}

sign_file_for() {   # as dkms: linux-kbuild, else the kernel's build tree
    local kv=$1 f
    for f in "$R/usr/lib/linux-kbuild-${kv%.*}/scripts/sign-file" \
             "$R/lib/modules/$kv/build/scripts/sign-file"; do
        [ -x "$f" ] && { printf '%s' "$f"; return 0; }
    done
    return 1
}

xz_opts=$(conf_get compress_xz_opts);     : "${xz_opts:=--check=crc32 --lzma2=dict=1MiB}"
zstd_opts=$(conf_get compress_zstd_opts); : "${zstd_opts:=-q -T0}"
zstd_opts=${zstd_opts//--rm/}
gzip_opts=$(conf_get compress_gzip_opts)

# --- 1. the new key pair (module signing only), not yet in place --------------
( umask 077
  openssl req -new -x509 -nodes -days 36500 -subj "/CN=DKMS module signing key" \
      -newkey rsa:2048 -keyout "$work/mok.key" \
      -addext "extendedKeyUsage=codeSigning,1.3.6.1.4.1.2312.16.1.2" \
      -outform DER -out "$work/mok.pub" >/dev/null 2>&1 ) || die "could not create the key pair"
serial=$(openssl x509 -inform DER -in "$work/mok.pub" -noout -serial 2>/dev/null) || die "could not read the new certificate"
serial=$(serial_norm "${serial#serial=}")

# --- 2. re-sign every module into the work directory -----------------------------
i=0
for m in "${mods[@]}"; do
    i=$((i + 1))
    kv=$(kver_of "$m")
    hash=$(sed -n 's/^CONFIG_MODULE_SIG_HASH="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' "$R/boot/config-$kv" 2>/dev/null)
    [ -n "$hash" ] || die "${m#"$R"}: no CONFIG_MODULE_SIG_HASH in /boot/config-$kv"
    sf=$(sign_file_for "$kv") || die "${m#"$R"}: sign-file for $kv not found (kernel headers missing?)"

    raw=$work/$i.ko
    unpack "$m" > "$raw" || die "${m#"$R"}: could not unpack"

    # strip the appended signature: ... | 12 byte struct (last 4 = sig length) | magic + \n
    size=$(stat -c %s "$raw")
    has_sig "$raw" || die "${m#"$R"}: no module signature found"
    siglen=$(tail -c 32 "$raw" | head -c 4 | od -An -tu1 | awk '{print $1*16777216 + $2*65536 + $3*256 + $4}')
    new=$((size - 28 - 12 - siglen))
    [ "$new" -gt 0 ] || die "${m#"$R"}: bad signature length"
    truncate -s "$new" "$raw"

    "$sf" "$hash" "$work/mok.key" "$work/mok.pub" "$raw" || die "${m#"$R"}: sign-file failed"
    k=$(serial_norm "$(modinfo -F sig_key "$raw" 2>/dev/null)")
    [ "$k" = "$serial" ] || die "${m#"$R"}: check failed after signing"

    out=$work/out-$i.ko${m##*.ko}          # same suffix as the module
    case $m in
        *.ko.xz)  xz $xz_opts -c -- "$raw"     > "$out" ;;
        *.ko.zst) zstd $zstd_opts -c -- "$raw" > "$out" ;;
        *.ko.gz)  gzip $gzip_opts -c -- "$raw" > "$out" ;;
        *.ko)     cp -- "$raw" "$out" ;;
    esac || die "${m#"$R"}: could not pack"
    unpack "$out" 2>/dev/null | cmp -s - "$raw" || die "${m#"$R"}: check failed after packing"
    rm -f -- "$raw"
done

# --- 3. all done: put modules and key in place --------------------------------------
i=0
for m in "${mods[@]}"; do
    i=$((i + 1))
    out=$work/out-$i.ko${m##*.ko}
    chmod --reference="$m" "$out" 2>/dev/null
    mv -f -- "$out" "$m.newkey" && mv -f -- "$m.newkey" "$m" || die "${m#"$R"}: could not replace"
done
install -m 0644 "$work/mok.pub" "$pub" && install -m 0600 "$work/mok.key" "$key" || die "could not install the new key pair"

say "created the system's own dkms signing key (module signing only): ${pub#"$R"}"
say "re-signed ${#mods[@]} dkms module file(s) with it"
say "with Secure Boot on, enroll it once: sudo mokutil --import /var/lib/dkms/mok.pub"
exit 0
