Home | History | Annotate | Line # | Download | only in rc.d
random_seed revision 1.6
      1 #!/bin/sh
      2 #
      3 # $NetBSD: random_seed,v 1.6 2012/12/29 22:15:07 christos 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 
     20 name="random_seed"
     21 rcvar=$name
     22 start_cmd="random_load"
     23 stop_cmd="random_save"
     24 
     25 random_file="${random_file:-/var/db/entropy-file}"
     26 
     27 message()
     28 {
     29 	echo "${name}: ${random_file}: $@" 1>&2
     30 }
     31 
     32 getfstype() {
     33 	df -G "$1" | while read line; do
     34 		set -- $line
     35 		if [ "$2" = "fstype" ]; then
     36 			echo "$1"
     37 			return
     38 		fi
     39 	done
     40 }
     41 
     42 fs_safe()
     43 {
     44 	#
     45 	# Enforce that the file's on a local filesystem.
     46 	# Include only the types we can actually write.
     47 	#
     48 	fstype="$(getfstype "$1")"
     49 	case "${fstype}" in
     50 	ffs|lfs|ext2fs|msdos|v7fs)
     51 		return 0
     52 		;;
     53 	*)
     54 		message "Bad filesystem type ${fstype}"
     55 		return 1
     56 		;;
     57 	esac
     58 }
     59 
     60 random_load()
     61 {
     62 	if [ ! -f "${random_file}" ]; then
     63 		message "Not present"
     64 		return
     65 	fi
     66 
     67 	if ! fs_safe "$(dirname "${random_file}")"; then
     68 		return 1
     69 	fi
     70 
     71 	set -- $(ls -ldn "${random_file}")
     72 	st_mode="$1" # should be "-rw-------"
     73 	st_uid="$3"  # should be "0" for root
     74 
     75 	# The file must be owned by root,
     76 	if [ "$st_uid" != "0" ]; then
     77 		message "Bad owner ${st_uid}"
     78 		return 1
     79 	fi
     80 	# and root read/write only.
     81 	if [ "$st_mode" != "-rw-------" ]; then
     82 		message "Bad mode ${st_mode}"
     83 		return 1
     84 	fi
     85 
     86 	if rndctl -L "${random_file}"; then
     87 		echo "Loaded entropy from ${random_file}."
     88 	fi
     89 }
     90 
     91 random_save()
     92 {
     93 	oum="$(umask)"
     94 	umask 077
     95 
     96 	rm -Pf "${random_file}"
     97 
     98 	if ! fs_safe "$(dirname "${random_file}")"; then
     99 		umask "${oum}"
    100 		return 1
    101 	fi
    102 
    103 	if rndctl -S "${random_file}"; then
    104 		echo "Saved entropy to ${random_file}."
    105 	fi
    106 	umask "${oum}"
    107 }
    108 
    109 
    110 load_rc_config "${name}"
    111 run_rc_command "$1"
    112