1#!/bin/sh 2# SPDX-License-Identifier: GPL-2.0 3# 4# Measure kernel stack entropy by sampling via LKDTM's REPORT_STACK test. 5set -e 6samples="${1:-1000}" 7 8# Capture dmesg continuously since it may fill up depending on sample size. 9log=$(mktemp -t stack-entropy-XXXXXX) 10dmesg --follow >"$log" & pid=$! 11report=-1 12for i in $(seq 1 $samples); do 13 echo "REPORT_STACK" >/sys/kernel/debug/provoke-crash/DIRECT 14 if [ -t 1 ]; then 15 percent=$(( 100 * $i / $samples )) 16 if [ "$percent" -ne "$report" ]; then 17 /bin/echo -en "$percent%\r" 18 report="$percent" 19 fi 20 fi 21done 22kill "$pid" 23 24# Count unique offsets since last run. 25seen=$(tac "$log" | grep -m1 -B"$samples"0 'Starting stack offset' | \ 26 grep 'Stack offset' | awk '{print $NF}' | sort | uniq -c | wc -l) 27bits=$(echo "obase=2; $seen" | bc | wc -L) 28echo "Bits of stack entropy: $bits" 29rm -f "$log" 30 31# We would expect any functional stack randomization to be at least 5 bits. 32if [ "$bits" -lt 5 ]; then 33 exit 1 34else 35 exit 0 36fi 37