1
0

waouw-keyfetch 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #!/bin/sh
  2. # /etc/waouw/waouw-keyfetch
  3. #
  4. # LUKS keyscript: fetches the disk encryption key from waouw-admin
  5. # during early boot (initramfs). Called by cryptsetup, must output
  6. # the raw key on stdout.
  7. #
  8. # Environment: minimal initramfs (busybox + binaries added by hook).
  9. # POSIX sh only — no bash, no arrays, no [[ ]].
  10. #
  11. # Network strategy:
  12. # 1. Try Ethernet first (may already have IP via ip=dhcp in cmdline.txt)
  13. # 2. Fall back to WiFi if Ethernet has no link
  14. #
  15. # Auth: HMAC-SHA256(timestamp + serial, SHA256(serial + "waouw-boot-2026"))
  16. # Endpoint: POST https://admin.waouw.eu/api/device_luks_key.php
  17. set -e
  18. # -------------------------------------------------------------------
  19. # Configuration
  20. # -------------------------------------------------------------------
  21. CA_BUNDLE="/etc/ssl/certs/ca-certificates.crt"
  22. WIFI_CONF="/boot/firmware/wifi-initramfs.conf"
  23. DEVICE_ID_FILE="/boot/firmware/waouw-device-id"
  24. LOCAL_KEY_FILE="/boot/firmware/.waouw-luks-localkey"
  25. LOT_ID_FILE="/boot/firmware/.waouw-lot-id"
  26. ADMIN_URL_FILE="/boot/firmware/waouw-admin-url.txt"
  27. BOOT_SALT="waouw-boot-2026"
  28. # Read admin URL from boot partition
  29. ADMIN_URL=""
  30. if [ -f "$ADMIN_URL_FILE" ]; then
  31. ADMIN_URL="$(cat "$ADMIN_URL_FILE" 2>/dev/null | tr -d '\r\n ')"
  32. fi
  33. if [ -z "$ADMIN_URL" ]; then
  34. ADMIN_URL="https://admin.waouw.eu"
  35. fi
  36. ADMIN_URL="${ADMIN_URL}/api/device_luks_key.php"
  37. MAX_ATTEMPTS=30
  38. RETRY_INTERVAL=10
  39. # Interfaces
  40. ETH_IFACE="eth0"
  41. WLAN_IFACE="wlan0"
  42. # PIDs to clean up
  43. WPA_PID=""
  44. UDHCPC_PID=""
  45. # -------------------------------------------------------------------
  46. # Logging (visible on serial console, helps debugging)
  47. # -------------------------------------------------------------------
  48. log() {
  49. echo "waouw-keyfetch: $*" >/dev/console 2>/dev/null || true
  50. }
  51. log_err() {
  52. echo "waouw-keyfetch: ERROR: $*" >/dev/console 2>/dev/null || true
  53. }
  54. # -------------------------------------------------------------------
  55. # Cleanup handler
  56. # -------------------------------------------------------------------
  57. cleanup() {
  58. # Kill wpa_supplicant if we started it
  59. if [ -n "$WPA_PID" ] && kill -0 "$WPA_PID" 2>/dev/null; then
  60. kill "$WPA_PID" 2>/dev/null || true
  61. wait "$WPA_PID" 2>/dev/null || true
  62. log "wpa_supplicant stopped"
  63. fi
  64. # Kill udhcpc if we started it
  65. if [ -n "$UDHCPC_PID" ] && kill -0 "$UDHCPC_PID" 2>/dev/null; then
  66. kill "$UDHCPC_PID" 2>/dev/null || true
  67. wait "$UDHCPC_PID" 2>/dev/null || true
  68. fi
  69. # Remove WiFi config copy from tmpfs (contains password)
  70. rm -f /tmp/wpa-initramfs.conf 2>/dev/null || true
  71. # Clear any key material from environment
  72. unset LUKS_KEY BOOT_SECRET HMAC_SIG TIMESTAMP SERIAL DEVICE_ID
  73. }
  74. trap cleanup EXIT
  75. # -------------------------------------------------------------------
  76. # Check for local key file (first boot after encryption)
  77. # If present, use it directly — no network needed.
  78. # The key will be registered on waouw-admin during install-complete.sh
  79. # and the local file deleted afterwards.
  80. # -------------------------------------------------------------------
  81. if [ -f "$LOCAL_KEY_FILE" ]; then
  82. LOCAL_KEY=$(cat "$LOCAL_KEY_FILE" 2>/dev/null)
  83. if [ -n "$LOCAL_KEY" ] && [ ${#LOCAL_KEY} -ge 32 ]; then
  84. log "Using local key from $LOCAL_KEY_FILE (first boot)"
  85. printf '%s' "$LOCAL_KEY"
  86. unset LOCAL_KEY
  87. exit 0
  88. fi
  89. log "Local key file present but invalid, falling back to network"
  90. fi
  91. # -------------------------------------------------------------------
  92. # Read device serial from /proc/cpuinfo
  93. # -------------------------------------------------------------------
  94. get_serial() {
  95. _serial=""
  96. if [ -f /proc/cpuinfo ]; then
  97. _serial=$(sed -n 's/^Serial[[:space:]]*:[[:space:]]*0*//p' /proc/cpuinfo)
  98. fi
  99. if [ -z "$_serial" ]; then
  100. log_err "cannot read device serial from /proc/cpuinfo"
  101. return 1
  102. fi
  103. echo "$_serial"
  104. }
  105. # -------------------------------------------------------------------
  106. # Read device ID from boot partition
  107. # -------------------------------------------------------------------
  108. get_device_id() {
  109. if [ -f "$DEVICE_ID_FILE" ]; then
  110. _devid=$(cat "$DEVICE_ID_FILE" 2>/dev/null | tr -d '[:space:]')
  111. if [ -n "$_devid" ]; then
  112. echo "$_devid"
  113. return 0
  114. fi
  115. fi
  116. log_err "cannot read device ID from ${DEVICE_ID_FILE}"
  117. return 1
  118. }
  119. # -------------------------------------------------------------------
  120. # Compute HMAC-SHA256 using openssl
  121. # $1 = message
  122. # $2 = key (hex or plaintext)
  123. # Outputs hex-encoded HMAC
  124. # -------------------------------------------------------------------
  125. hmac_sha256() {
  126. _msg="$1"
  127. _key="$2"
  128. # openssl dgst outputs "stdin= <hex>" or "(stdin)= <hex>"
  129. _hmac=$(printf '%s' "$_msg" | openssl dgst -sha256 -hmac "$_key" 2>/dev/null | sed 's/^.*=[[:space:]]*//')
  130. if [ -z "$_hmac" ]; then
  131. log_err "HMAC computation failed"
  132. return 1
  133. fi
  134. echo "$_hmac"
  135. }
  136. # -------------------------------------------------------------------
  137. # Compute SHA256 hash of a string
  138. # -------------------------------------------------------------------
  139. sha256_hash() {
  140. _input="$1"
  141. _hash=$(printf '%s' "$_input" | openssl dgst -sha256 2>/dev/null | sed 's/^.*=[[:space:]]*//')
  142. if [ -z "$_hash" ]; then
  143. log_err "SHA256 computation failed"
  144. return 1
  145. fi
  146. echo "$_hash"
  147. }
  148. # -------------------------------------------------------------------
  149. # Check if an interface has a usable IP address
  150. # -------------------------------------------------------------------
  151. has_ip() {
  152. _iface="$1"
  153. ip addr show "$_iface" 2>/dev/null | grep -q 'inet [0-9]'
  154. }
  155. # -------------------------------------------------------------------
  156. # Check if Ethernet cable is plugged in (carrier detected)
  157. # -------------------------------------------------------------------
  158. eth_has_link() {
  159. _carrier=$(cat "/sys/class/net/${ETH_IFACE}/carrier" 2>/dev/null)
  160. [ "$_carrier" = "1" ]
  161. }
  162. # -------------------------------------------------------------------
  163. # Bring up WiFi
  164. # -------------------------------------------------------------------
  165. start_wifi() {
  166. if [ ! -f "$WIFI_CONF" ]; then
  167. log "no WiFi config found at ${WIFI_CONF}"
  168. return 1
  169. fi
  170. log "starting WiFi..."
  171. # Load WiFi driver
  172. modprobe brcmfmac 2>/dev/null || true
  173. sleep 2
  174. # Check interface appeared
  175. if [ ! -d "/sys/class/net/${WLAN_IFACE}" ]; then
  176. log_err "WiFi interface ${WLAN_IFACE} not found after loading driver"
  177. return 1
  178. fi
  179. # Bring interface up
  180. ip link set "$WLAN_IFACE" up 2>/dev/null || true
  181. sleep 1
  182. # Copy WiFi config to tmpfs (boot partition may be read-only)
  183. cp "$WIFI_CONF" /tmp/wpa-initramfs.conf 2>/dev/null || true
  184. chmod 600 /tmp/wpa-initramfs.conf
  185. # Start wpa_supplicant
  186. wpa_supplicant -B -i "$WLAN_IFACE" -c /tmp/wpa-initramfs.conf -P /tmp/wpa_supplicant.pid 2>/dev/null
  187. if [ -f /tmp/wpa_supplicant.pid ]; then
  188. WPA_PID=$(cat /tmp/wpa_supplicant.pid)
  189. fi
  190. # Wait for association (up to 15 seconds)
  191. _wifi_wait=0
  192. while [ "$_wifi_wait" -lt 15 ]; do
  193. if wpa_cli -i "$WLAN_IFACE" status 2>/dev/null | grep -q 'wpa_state=COMPLETED'; then
  194. log "WiFi associated"
  195. break
  196. fi
  197. sleep 1
  198. _wifi_wait=$(( _wifi_wait + 1 ))
  199. done
  200. if [ "$_wifi_wait" -ge 15 ]; then
  201. log_err "WiFi association timeout"
  202. return 1
  203. fi
  204. # Get IP via DHCP
  205. if command -v udhcpc >/dev/null 2>&1; then
  206. udhcpc -i "$WLAN_IFACE" -t 5 -T 3 -n -q 2>/dev/null
  207. elif command -v dhclient >/dev/null 2>&1; then
  208. dhclient -1 -timeout 15 "$WLAN_IFACE" 2>/dev/null
  209. else
  210. log_err "no DHCP client available"
  211. return 1
  212. fi
  213. sleep 1
  214. if has_ip "$WLAN_IFACE"; then
  215. log "WiFi IP acquired on ${WLAN_IFACE}"
  216. return 0
  217. else
  218. log_err "WiFi DHCP failed — no IP on ${WLAN_IFACE}"
  219. return 1
  220. fi
  221. }
  222. # -------------------------------------------------------------------
  223. # Ensure we have network connectivity on some interface
  224. # -------------------------------------------------------------------
  225. ensure_network() {
  226. # Check Ethernet first
  227. if has_ip "$ETH_IFACE"; then
  228. log "Ethernet already has IP"
  229. return 0
  230. fi
  231. # If Ethernet has link but no IP, try DHCP on it
  232. if eth_has_link; then
  233. log "Ethernet link detected, requesting DHCP..."
  234. ip link set "$ETH_IFACE" up 2>/dev/null || true
  235. if command -v udhcpc >/dev/null 2>&1; then
  236. udhcpc -i "$ETH_IFACE" -t 5 -T 3 -n -q 2>/dev/null
  237. elif command -v dhclient >/dev/null 2>&1; then
  238. dhclient -1 -timeout 15 "$ETH_IFACE" 2>/dev/null
  239. fi
  240. sleep 1
  241. if has_ip "$ETH_IFACE"; then
  242. log "Ethernet IP acquired"
  243. return 0
  244. fi
  245. fi
  246. # Fall back to WiFi
  247. log "no Ethernet connectivity, trying WiFi..."
  248. if start_wifi; then
  249. return 0
  250. fi
  251. log_err "no network connectivity available"
  252. return 1
  253. }
  254. # -------------------------------------------------------------------
  255. # Fetch LUKS key from waouw-admin (lot mode or device mode)
  256. # -------------------------------------------------------------------
  257. fetch_key_lot() {
  258. # Lot mode: use lot_id as identifier
  259. _lot_id="$1"
  260. TIMESTAMP=$(date +%s)
  261. BOOT_SECRET=$(sha256_hash "${_lot_id}${BOOT_SALT}") || return 1
  262. HMAC_SIG=$(hmac_sha256 "${TIMESTAMP}${_lot_id}" "$BOOT_SECRET") || return 1
  263. _payload="{\"action\":\"retrieve_lot\",\"lot_id\":\"${_lot_id}\"}"
  264. _response=$(curl \
  265. --silent --show-error --max-time 15 \
  266. --cacert "$CA_BUNDLE" \
  267. --header "Content-Type: application/json" \
  268. --header "X-Waouw-Boot-Hmac: ${HMAC_SIG}" \
  269. --header "X-Waouw-Timestamp: ${TIMESTAMP}" \
  270. --data "$_payload" \
  271. "$ADMIN_URL" 2>/dev/null)
  272. _curl_rc=$?
  273. if [ "$_curl_rc" -ne 0 ]; then
  274. log_err "curl failed (exit code ${_curl_rc})"
  275. return 1
  276. fi
  277. if echo "$_response" | grep -q '"error"'; then
  278. _errmsg=$(echo "$_response" | sed -n 's/.*"error"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
  279. log_err "server error (lot): ${_errmsg:-unknown}"
  280. return 1
  281. fi
  282. LUKS_KEY=$(echo "$_response" | sed -n 's/.*"luks_key"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
  283. [ -n "$LUKS_KEY" ] && [ ${#LUKS_KEY} -ge 32 ] && return 0
  284. log_err "no valid key in lot response"
  285. return 1
  286. }
  287. fetch_key_device() {
  288. # Device mode: use serial as identifier
  289. SERIAL=$(get_serial) || return 1
  290. DEVICE_ID=$(get_device_id) || return 1
  291. TIMESTAMP=$(date +%s)
  292. BOOT_SECRET=$(sha256_hash "${SERIAL}${BOOT_SALT}") || return 1
  293. HMAC_SIG=$(hmac_sha256 "${TIMESTAMP}${SERIAL}" "$BOOT_SECRET") || return 1
  294. _payload="{\"serial\":\"${SERIAL}\",\"device_id\":\"${DEVICE_ID}\"}"
  295. _response=$(curl \
  296. --silent --show-error --max-time 15 \
  297. --cacert "$CA_BUNDLE" \
  298. --header "Content-Type: application/json" \
  299. --header "X-Waouw-Boot-Hmac: ${HMAC_SIG}" \
  300. --header "X-Waouw-Timestamp: ${TIMESTAMP}" \
  301. --data "$_payload" \
  302. "$ADMIN_URL" 2>/dev/null)
  303. _curl_rc=$?
  304. if [ "$_curl_rc" -ne 0 ]; then
  305. log_err "curl failed (exit code ${_curl_rc})"
  306. return 1
  307. fi
  308. if echo "$_response" | grep -q '"error"'; then
  309. _errmsg=$(echo "$_response" | sed -n 's/.*"error"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
  310. log_err "server error (device): ${_errmsg:-unknown}"
  311. return 1
  312. fi
  313. LUKS_KEY=$(echo "$_response" | sed -n 's/.*"luks_key"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
  314. [ -n "$LUKS_KEY" ] && [ ${#LUKS_KEY} -ge 32 ] && return 0
  315. log_err "no valid key in device response"
  316. return 1
  317. }
  318. fetch_key() {
  319. # Try lot mode first (if lot ID file exists)
  320. LOT_ID=""
  321. if [ -f "$LOT_ID_FILE" ]; then
  322. LOT_ID=$(cat "$LOT_ID_FILE" 2>/dev/null | tr -d '\r\n ')
  323. fi
  324. if [ -n "$LOT_ID" ]; then
  325. log "lot mode: $LOT_ID"
  326. if fetch_key_lot "$LOT_ID"; then
  327. return 0
  328. fi
  329. log "lot fetch failed, trying device mode..."
  330. fi
  331. # Device mode
  332. fetch_key_device
  333. }
  334. # ===================================================================
  335. # Main
  336. # ===================================================================
  337. log "starting LUKS key fetch..."
  338. _attempt=0
  339. _success=0
  340. while [ "$_attempt" -lt "$MAX_ATTEMPTS" ]; do
  341. _attempt=$(( _attempt + 1 ))
  342. log "attempt ${_attempt}/${MAX_ATTEMPTS}"
  343. # Ensure network is up
  344. if ! ensure_network; then
  345. log "waiting ${RETRY_INTERVAL}s before retry..."
  346. sleep "$RETRY_INTERVAL"
  347. continue
  348. fi
  349. # Try to fetch the key
  350. if fetch_key; then
  351. _success=1
  352. break
  353. fi
  354. log "key fetch failed, waiting ${RETRY_INTERVAL}s before retry..."
  355. sleep "$RETRY_INTERVAL"
  356. done
  357. if [ "$_success" -eq 1 ]; then
  358. log "LUKS key obtained successfully"
  359. # Output the key on stdout for cryptsetup
  360. printf '%s' "$LUKS_KEY"
  361. # Clear from memory immediately
  362. unset LUKS_KEY
  363. exit 0
  364. else
  365. log_err "FAILED to obtain LUKS key after ${MAX_ATTEMPTS} attempts ($(( MAX_ATTEMPTS * RETRY_INTERVAL ))s)"
  366. log_err "device will not boot — check network and admin server"
  367. exit 1
  368. fi