random_seed revision 1.10
1#!/bin/sh
2#
3# $NetBSD: random_seed,v 1.10 2020/05/06 18:49:26 riastradh Exp $
4#
5
6# PROVIDE: random_seed
7# REQUIRE: mountcritlocal
8# BEFORE: securelevel
9# BEFORE: bootconf
10# KEYWORD: shutdown
11#
12# The "BEFORE: securelevel" is a real dependency, in that
13# this script won't work if run after the securelevel is changed.
14#
15# The "BEFORE: bootconf" is intended to cause this to
16# be the first script that runs after mountcritlocal.
17
18$_rc_subr_loaded . /etc/rc.subr
19
20name="random_seed"
21rcvar=$name
22start_cmd="random_load"
23stop_cmd="random_save"
24
25random_file="${random_file:-/var/db/entropy-file}"
26
27message()
28{
29	echo "${name}: ${random_file}: $@" 1>&2
30}
31
32fs_safe()
33{
34	# Consider the root file system safe always.
35	df -P "$1" | (while read dev total used avail cap mountpoint; do
36		case $mountpoint in
37		'Mounted on')	continue;;
38		/)		exit 0;;
39		*)		exit 1;;
40		esac
41	done) && return 0
42
43	# Otherwise, consider local file systems safe and non-local
44	# file systems unsafe.
45	case $(df -l "$1") in
46	*Warning:*)
47		return 1
48		;;
49	*)
50		return 0
51		;;
52	esac
53}
54
55random_load()
56{
57	local flags=
58
59	if [ ! -f "${random_file}" ]; then
60		message "Not present"
61		return
62	fi
63
64	if ! fs_safe "$(dirname "${random_file}")"; then
65		flags=-i
66	fi
67
68	set -- $(ls -ldn "${random_file}")
69	st_mode="$1" # should be "-rw-------"
70	st_uid="$3"  # should be "0" for root
71
72	# The file must be owned by root,
73	if [ "$st_uid" != "0" ]; then
74		message "Bad owner ${st_uid}"
75		flags=-i
76	fi
77	# and root read/write only.
78	if [ "$st_mode" != "-rw-------" ]; then
79		message "Bad mode ${st_mode}"
80		flags=-i
81	fi
82
83	if rndctl $flags -L "${random_file}"; then
84		echo "Loaded entropy from ${random_file}."
85	fi
86}
87
88random_save()
89{
90	oum="$(umask)"
91	umask 077
92
93	if rndctl -S "${random_file}"; then
94		echo "Saved entropy to ${random_file}."
95	fi
96	umask "${oum}"
97}
98
99
100load_rc_config "${name}"
101run_rc_command "$1"
102