Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/provider/SeedGenerator.java
38830 views
/*1* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.provider;2627/**28* This class generates seeds for the SHA1PRNG cryptographically strong29* random number generator.30* <p>31* The seed is produced using one of two techniques, via a computation32* of current system activity or from an entropy gathering device.33* <p>34* In the default technique the seed is produced by counting the35* number of times the VM manages to loop in a given period. This number36* roughly reflects the machine load at that point in time.37* The samples are translated using a permutation (s-box)38* and then XORed together. This process is non linear and39* should prevent the samples from "averaging out". The s-box40* was designed to have even statistical distribution; it's specific41* values are not crucial for the security of the seed.42* We also create a number of sleeper threads which add entropy43* to the system by keeping the scheduler busy.44* Twenty such samples should give us roughly 160 bits of randomness.45* <p>46* These values are gathered in the background by a daemon thread47* thus allowing the system to continue performing it's different48* activites, which in turn add entropy to the random seed.49* <p>50* The class also gathers miscellaneous system information, some51* machine dependent, some not. This information is then hashed together52* with the 20 seed bytes.53* <p>54* The alternative to the above approach is to acquire seed material55* from an entropy gathering device, such as /dev/random. This can be56* accomplished by setting the value of the {@code securerandom.source}57* Security property to a URL specifying the location of the entropy58* gathering device, or by setting the {@code java.security.egd} System59* property.60* <p>61* In the event the specified URL cannot be accessed the default62* threading mechanism is used.63*64* @author Joshua Bloch65* @author Gadi Guy66*/6768import java.security.*;69import java.io.*;70import java.util.Properties;71import java.util.Enumeration;72import java.net.*;73import java.nio.file.DirectoryStream;74import java.nio.file.Files;75import java.nio.file.Path;76import java.util.Random;77import sun.security.util.Debug;7879abstract class SeedGenerator {8081// Static instance is created at link time82private static SeedGenerator instance;8384private static final Debug debug = Debug.getInstance("provider");8586// Static initializer to hook in selected or best performing generator87static {88String egdSource = SunEntries.getSeedSource();8990/*91* Try the URL specifying the source (e.g. file:/dev/random)92*93* The URLs "file:/dev/random" or "file:/dev/urandom" are used to94* indicate the SeedGenerator should use OS support, if available.95*96* On Windows, this causes the MS CryptoAPI seeder to be used.97*98* On Solaris/Linux/MacOS, this is identical to using99* URLSeedGenerator to read from /dev/[u]random100*/101if (egdSource.equals(SunEntries.URL_DEV_RANDOM) ||102egdSource.equals(SunEntries.URL_DEV_URANDOM)) {103try {104instance = new NativeSeedGenerator(egdSource);105if (debug != null) {106debug.println(107"Using operating system seed generator" + egdSource);108}109} catch (IOException e) {110if (debug != null) {111debug.println("Failed to use operating system seed "112+ "generator: " + e.toString());113}114}115} else if (egdSource.length() != 0) {116try {117instance = new URLSeedGenerator(egdSource);118if (debug != null) {119debug.println("Using URL seed generator reading from "120+ egdSource);121}122} catch (IOException e) {123if (debug != null) {124debug.println("Failed to create seed generator with "125+ egdSource + ": " + e.toString());126}127}128}129130// Fall back to ThreadedSeedGenerator131if (instance == null) {132if (debug != null) {133debug.println("Using default threaded seed generator");134}135instance = new ThreadedSeedGenerator();136}137}138139/**140* Fill result with bytes from the queue. Wait for it if it isn't ready.141*/142static public void generateSeed(byte[] result) {143instance.getSeedBytes(result);144}145146abstract void getSeedBytes(byte[] result);147148/**149* Retrieve some system information, hashed.150*/151static byte[] getSystemEntropy() {152byte[] ba;153final MessageDigest md;154155try {156md = MessageDigest.getInstance("SHA");157} catch (NoSuchAlgorithmException nsae) {158throw new InternalError("internal error: SHA-1 not available."159, nsae);160}161162// The current time in millis163byte b =(byte)System.currentTimeMillis();164md.update(b);165166java.security.AccessController.doPrivileged167(new java.security.PrivilegedAction<Void>() {168@Override169public Void run() {170try {171// System properties can change from machine to machine172String s;173Properties p = System.getProperties();174Enumeration<?> e = p.propertyNames();175while (e.hasMoreElements()) {176s =(String)e.nextElement();177md.update(s.getBytes());178md.update(p.getProperty(s).getBytes());179}180181// Include network adapter names (and a Mac address)182addNetworkAdapterInfo(md);183184// The temporary dir185File f = new File(p.getProperty("java.io.tmpdir"));186int count = 0;187try (188DirectoryStream<Path> stream =189Files.newDirectoryStream(f.toPath())) {190// We use a Random object to choose what file names191// should be used. Otherwise on a machine with too192// many files, the same first 1024 files always get193// used. Any, We make sure the first 512 files are194// always used.195Random r = new Random();196for (Path entry: stream) {197if (count < 512 || r.nextBoolean()) {198md.update(entry.getFileName()199.toString().getBytes());200}201if (count++ > 1024) {202break;203}204}205}206} catch (Exception ex) {207md.update((byte)ex.hashCode());208}209210// get Runtime memory stats211Runtime rt = Runtime.getRuntime();212byte[] memBytes = longToByteArray(rt.totalMemory());213md.update(memBytes, 0, memBytes.length);214memBytes = longToByteArray(rt.freeMemory());215md.update(memBytes, 0, memBytes.length);216217return null;218}219});220return md.digest();221}222223/*224* Include network adapter names and, if available, a Mac address225*226* See also java.util.concurrent.ThreadLocalRandom.initialSeed()227*/228private static void addNetworkAdapterInfo(MessageDigest md) {229230try {231Enumeration<NetworkInterface> ifcs =232NetworkInterface.getNetworkInterfaces();233while (ifcs.hasMoreElements()) {234NetworkInterface ifc = ifcs.nextElement();235md.update(ifc.toString().getBytes());236if (!ifc.isVirtual()) { // skip fake addresses237byte[] bs = ifc.getHardwareAddress();238if (bs != null) {239md.update(bs);240break;241}242}243}244} catch (Exception ignore) {245}246}247248/**249* Helper function to convert a long into a byte array (least significant250* byte first).251*/252private static byte[] longToByteArray(long l) {253byte[] retVal = new byte[8];254255for (int i=0; i<8; i++) {256retVal[i] = (byte) l;257l >>= 8;258}259260return retVal;261}262263/*264// This method helps the test utility receive unprocessed seed bytes.265public static int genTestSeed() {266return myself.getByte();267}268*/269270271private static class ThreadedSeedGenerator extends SeedGenerator272implements Runnable {273// Queue is used to collect seed bytes274private byte[] pool;275private int start, end, count;276277// Thread group for our threads278ThreadGroup seedGroup;279280/**281* The constructor is only called once to construct the one282* instance we actually use. It instantiates the message digest283* and starts the thread going.284*/285ThreadedSeedGenerator() {286pool = new byte[20];287start = end = 0;288289MessageDigest digest;290291try {292digest = MessageDigest.getInstance("SHA");293} catch (NoSuchAlgorithmException e) {294throw new InternalError("internal error: SHA-1 not available."295, e);296}297298final ThreadGroup[] finalsg = new ThreadGroup[1];299Thread t = java.security.AccessController.doPrivileged300(new java.security.PrivilegedAction<Thread>() {301@Override302public Thread run() {303ThreadGroup parent, group =304Thread.currentThread().getThreadGroup();305while ((parent = group.getParent()) != null) {306group = parent;307}308finalsg[0] = new ThreadGroup309(group, "SeedGenerator ThreadGroup");310Thread newT = new Thread(finalsg[0],311ThreadedSeedGenerator.this,312"SeedGenerator Thread");313newT.setPriority(Thread.MIN_PRIORITY);314newT.setDaemon(true);315return newT;316}317});318seedGroup = finalsg[0];319t.start();320}321322/**323* This method does the actual work. It collects random bytes and324* pushes them into the queue.325*/326@Override327final public void run() {328try {329while (true) {330// Queue full? Wait till there's room.331synchronized(this) {332while (count >= pool.length) {333wait();334}335}336337int counter, quanta;338byte v = 0;339340// Spin count must not be under 64000341for (counter = quanta = 0;342(counter < 64000) && (quanta < 6); quanta++) {343344// Start some noisy threads345try {346BogusThread bt = new BogusThread();347Thread t = new Thread348(seedGroup, bt, "SeedGenerator Thread");349t.start();350} catch (Exception e) {351throw new InternalError("internal error: " +352"SeedGenerator thread creation error.", e);353}354355// We wait 250milli quanta, so the minimum wait time356// cannot be under 250milli.357int latch = 0;358long l = System.currentTimeMillis() + 250;359while (System.currentTimeMillis() < l) {360synchronized(this){};361latch++;362}363364// Translate the value using the permutation, and xor365// it with previous values gathered.366v ^= rndTab[latch % 255];367counter += latch;368}369370// Push it into the queue and notify anybody who might371// be waiting for it.372synchronized(this) {373pool[end] = v;374end++;375count++;376if (end >= pool.length) {377end = 0;378}379380notifyAll();381}382}383} catch (Exception e) {384throw new InternalError("internal error: " +385"SeedGenerator thread generated an exception.", e);386}387}388389@Override390void getSeedBytes(byte[] result) {391for (int i = 0; i < result.length; i++) {392result[i] = getSeedByte();393}394}395396byte getSeedByte() {397byte b;398399try {400// Wait for it...401synchronized(this) {402while (count <= 0) {403wait();404}405}406} catch (Exception e) {407if (count <= 0) {408throw new InternalError("internal error: " +409"SeedGenerator thread generated an exception.", e);410}411}412413synchronized(this) {414// Get it from the queue415b = pool[start];416pool[start] = 0;417start++;418count--;419if (start == pool.length) {420start = 0;421}422423// Notify the daemon thread, just in case it is424// waiting for us to make room in the queue.425notifyAll();426}427428return b;429}430431// The permutation was calculated by generating 64k of random432// data and using it to mix the trivial permutation.433// It should be evenly distributed. The specific values434// are not crucial to the security of this class.435private static byte[] rndTab = {43656, 30, -107, -6, -86, 25, -83, 75, -12, -64,4375, -128, 78, 21, 16, 32, 70, -81, 37, -51,438-43, -46, -108, 87, 29, 17, -55, 22, -11, -111,439-115, 84, -100, 108, -45, -15, -98, 72, -33, -28,44031, -52, -37, -117, -97, -27, 93, -123, 47, 126,441-80, -62, -93, -79, 61, -96, -65, -5, -47, -119,44214, 89, 81, -118, -88, 20, 67, -126, -113, 60,443-102, 55, 110, 28, 85, 121, 122, -58, 2, 45,44443, 24, -9, 103, -13, 102, -68, -54, -101, -104,44519, 13, -39, -26, -103, 62, 77, 51, 44, 111,44673, 18, -127, -82, 4, -30, 11, -99, -74, 40,447-89, 42, -76, -77, -94, -35, -69, 35, 120, 76,44833, -73, -7, 82, -25, -10, 88, 125, -112, 58,44983, 95, 6, 10, 98, -34, 80, 15, -91, 86,450-19, 52, -17, 117, 49, -63, 118, -90, 36, -116,451-40, -71, 97, -53, -109, -85, 109, -16, -3, 104,452-95, 68, 54, 34, 26, 114, -1, 106, -121, 3,45366, 0, 100, -84, 57, 107, 119, -42, 112, -61,4541, 48, 38, 12, -56, -57, 39, -106, -72, 41,4557, 71, -29, -59, -8, -38, 79, -31, 124, -124,4568, 91, 116, 99, -4, 9, -36, -78, 63, -49,457-67, -87, 59, 101, -32, 92, 94, 53, -41, 115,458-66, -70, -122, 50, -50, -22, -20, -18, -21, 23,459-2, -48, 96, 65, -105, 123, -14, -110, 69, -24,460-120, -75, 74, 127, -60, 113, 90, -114, 105, 46,46127, -125, -23, -44, 64462};463464/**465* This inner thread causes the thread scheduler to become 'noisy',466* thus adding entropy to the system load.467* At least one instance of this class is generated for every seed byte.468*/469private static class BogusThread implements Runnable {470@Override471final public void run() {472try {473for (int i = 0; i < 5; i++) {474Thread.sleep(50);475}476// System.gc();477} catch (Exception e) {478}479}480}481}482483static class URLSeedGenerator extends SeedGenerator {484485private String deviceName;486private InputStream seedStream;487488/**489* The constructor is only called once to construct the one490* instance we actually use. It opens the entropy gathering device491* which will supply the randomness.492*/493494URLSeedGenerator(String egdurl) throws IOException {495if (egdurl == null) {496throw new IOException("No random source specified");497}498deviceName = egdurl;499init();500}501502private void init() throws IOException {503final URL device = new URL(deviceName);504try {505seedStream = java.security.AccessController.doPrivileged506(new java.security.PrivilegedExceptionAction<InputStream>() {507@Override508public InputStream run() throws IOException {509/*510* return a FileInputStream for file URLs and511* avoid buffering. The openStream() call wraps512* InputStream in a BufferedInputStream which513* can buffer up to 8K bytes. This read is a514* performance issue for entropy sources which515* can be slow to replenish.516*/517if (device.getProtocol().equalsIgnoreCase("file")) {518File deviceFile =519SunEntries.getDeviceFile(device);520return new FileInputStream(deviceFile);521} else {522return device.openStream();523}524}525});526} catch (Exception e) {527throw new IOException(528"Failed to open " + deviceName, e.getCause());529}530}531532@Override533void getSeedBytes(byte[] result) {534int len = result.length;535int read = 0;536try {537while (read < len) {538int count = seedStream.read(result, read, len - read);539// /dev/random blocks - should never have EOF540if (count < 0) {541throw new InternalError(542"URLSeedGenerator " + deviceName +543" reached end of file");544}545read += count;546}547} catch (IOException ioe) {548throw new InternalError("URLSeedGenerator " + deviceName +549" generated exception: " + ioe.getMessage(), ioe);550}551}552}553}554555556