NetBSD/etc/rc.d/random_seed
riastradh c4e3864f67 If no random seed file exists on boot, create one.
rndctl -S triggers entropy consolidation, so whatever we gathered
during kernel startup -- interrupt timings, autoconf timings, &c. --
will be incorporated into the seed and into subsequent data read from
/dev/urandom, just like if rndctl -L had run at this boot, and the
seed will carry them into the next boot too.

But it still avoids frequently consolidating entropy on any regular
schedule, in order to continue to mitigate iterative-guessing
attacks.
2020-05-07 20:01:04 +00:00

104 lines
1.8 KiB
Bash
Executable File

#!/bin/sh
#
# $NetBSD: random_seed,v 1.13 2020/05/07 20:01:04 riastradh Exp $
#
# PROVIDE: random_seed
# REQUIRE: mountcritlocal
# BEFORE: securelevel
# BEFORE: bootconf
# KEYWORD: shutdown
#
# The "BEFORE: securelevel" is a real dependency, in that
# this script won't work if run after the securelevel is changed.
#
# The "BEFORE: bootconf" is intended to cause this to
# be the first script that runs after mountcritlocal.
$_rc_subr_loaded . /etc/rc.subr
name="random_seed"
rcvar=$name
start_cmd="random_load"
stop_cmd="random_save"
random_file="${random_file:-/var/db/entropy-file}"
message()
{
echo "${name}: ${random_file}: $@" 1>&2
}
fs_safe()
{
# Consider the root file system safe always.
df -P "$1" | (while read dev total used avail cap mountpoint; do
case $mountpoint in
'Mounted on') continue;;
/) exit 0;;
*) exit 1;;
esac
done) && return 0
# Otherwise, consider local file systems safe and non-local
# file systems unsafe.
case $(df -l "$1") in
*Warning:*)
return 1
;;
*)
return 0
;;
esac
}
random_load()
{
local flags=
if [ ! -f "${random_file}" ]; then
message "Not present; creating"
random_save
return
fi
if ! fs_safe "${random_file}"; then
message "Unsafe file system"
flags=-i
fi
set -- $(ls -ldn "${random_file}")
st_mode="$1" # should be "-rw-------"
st_uid="$3" # should be "0" for root
# The file must be owned by root,
if [ "$st_uid" != "0" ]; then
message "Bad owner ${st_uid}"
flags=-i
fi
# and root read/write only.
if [ "$st_mode" != "-rw-------" ]; then
message "Bad mode ${st_mode}"
flags=-i
fi
if rndctl $flags -L "${random_file}"; then
echo "Loaded entropy from ${random_file}."
fi
}
random_save()
{
oum="$(umask)"
umask 077
if rndctl -S "${random_file}"; then
echo "Saved entropy to ${random_file}."
fi
umask "${oum}"
}
load_rc_config "${name}"
run_rc_command "$1"