#!/bin/sh
#
# fill_random.sh
#
# This script tries to create entropy for /dev/random by doing
# reads on random blocks on an IDE disk. The random driver fills
# /dev/random using the disk writes as a reference. I *think* this
# should be considered secure, but I'm not sure so don't take
# this for granted.
#
# It works under Linux and its footprint is fairly low. This helped
# me resolve problems with "PRNG not seeded" when running several
# ssh's and scp's one after another on a low-end Linux client that
# did not have lots of disk acess and no console input.
#
# My tests show that reading 16Mb of data (2000 8192-byte blocks)
# is enough to fill the device. You can adjust as necessary.
#
# (c) 2005 Olivier S. Masse, omasse ~at~ mayoxide ~dot~ com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#

# Configurable options
blocksize=8192			# size of blocks to read
default_sleep=5			# time between checking cycles 
min_entropy=2048		# minimum acceptable size of the entropy pool
disk=hda			# IDE disk to copy from
blocks_to_write=2000		# number of blocks to read from the disk
# End configurable options

cap_kbytes=$(cat /proc/ide/${disk}/capacity)
cap_bytes=$((${cap_kbytes} * 1024))
diskblocks=$((${cap_bytes} / ${blocksize}))
diskblocks=$((${diskblocks} - ${blocks_to_write}))

echo "Will read ${blocks_to_write} random blocks between ${diskblocks} blocks of ${blocksize} bytes."

while true
do
	entropy_avail=$(cat /proc/sys/kernel/random/entropy_avail)
	if [ $entropy_avail -lt $min_entropy ]
	then
		block=$((${diskblocks} % ${RANDOM}))
		echo "$(date +'%Y/%m/%d-%H:%M:%S') Entropy pool exhausted. Reading ${blocks_to_write} disk blocks starting at #${block}."
		dd if=/dev/${disk} of=/dev/null bs=${blocksize} skip=${RANDOM} count=${blocks_to_write}
	else
		sleep ${default_sleep}
	fi
done

