summaryrefslogtreecommitdiff
path: root/etc/rc.d/random_seed
blob: 29759bbdd6117bdb79a79404184df75eadd9c860 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/bin/sh
#
# $NetBSD: random_seed,v 1.15 2020/09/08 12:52:18 martin Exp $
#

# PROVIDE: random_seed
# REQUIRE: CRITLOCALMOUNTED
# 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"