1#!/bin/sh
2#
3# $NetBSD: random_seed,v 1.15 2020/09/08 12:52:18 martin Exp $
4#
5
6# PROVIDE: random_seed
7# REQUIRE: CRITLOCALMOUNTED
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; creating"
61                    random_save
62                    return
63          fi
64
65          if ! fs_safe "${random_file}"; then
66                    message "Unsafe file system"
67                    flags=-i
68          fi
69
70          set -- $(ls -ldn "${random_file}")
71          st_mode="$1" # should be "-rw-------"
72          st_uid="$3"  # should be "0" for root
73
74          # The file must be owned by root,
75          if [ "$st_uid" != "0" ]; then
76                    message "Bad owner ${st_uid}"
77                    flags=-i
78          fi
79          # and root read/write only.
80          if [ "$st_mode" != "-rw-------" ]; then
81                    message "Bad mode ${st_mode}"
82                    flags=-i
83          fi
84
85          if rndctl $flags -L "${random_file}"; then
86                    echo "Loaded entropy from ${random_file}."
87          fi
88}
89
90random_save()
91{
92          oum="$(umask)"
93          umask 077
94
95          if rndctl -S "${random_file}"; then
96                    echo "Saved entropy to ${random_file}."
97          fi
98          umask "${oum}"
99}
100
101
102load_rc_config "${name}"
103run_rc_command "$1"
104