Path: blob/master/src/java.base/share/classes/sun/security/provider/AbstractDrbg.java
41159 views
/*1* Copyright (c) 2016, 2020, 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;2627import sun.security.util.Debug;2829import java.security.*;30import java.util.Arrays;31import java.util.Objects;32import static java.security.DrbgParameters.Capability.*;3334/**35* The abstract base class for all DRBGs. It is used as {@link DRBG#impl}.36* <p>37* This class has 5 abstract methods. 3 are defined by SP800-90A:38* <ol>39* <li>{@link #generateAlgorithm(byte[], byte[])}40* <li>{@link #reseedAlgorithm(byte[], byte[])} (In fact this is not an41* abstract method, but any DRBG supporting reseeding must override it.)42* <li>{@link #instantiateAlgorithm(byte[])}43* </ol>44* and 2 for implementation purpose:45* <ol>46* <li>{@link #initEngine()}47* <li>{@link #chooseAlgorithmAndStrength}48* </ol>49* Although this class is not a child class of {@link SecureRandomSpi}, it50* implements all abstract methods there as final.51* <p>52* The initialization process of a DRBG is divided into 2 phases:53* {@link #configure configuration} is eagerly called to set up parameters,54* and {@link #instantiateIfNecessary instantiation} is lazily called only55* when nextBytes or reseed is called.56* <p>57* SecureRandom methods like reseed and nextBytes are not thread-safe.58* An implementation is required to protect shared access to instantiate states59* (instantiated, nonce) and DRBG states (v, c, key, reseedCounter, etc).60*/61public abstract class AbstractDrbg {6263/**64* This field is not null if {@code -Djava.security.debug=securerandom} is65* specified on the command line. An implementation can print useful66* debug info.67*/68protected static final Debug debug = Debug.getInstance(69"securerandom", "drbg");7071// Common working status7273private boolean instantiated;7475/**76* Reseed counter of a DRBG instance. A mechanism should increment it77* after each random bits generation and reset it in reseed. A mechanism78* does <em>not</em> need to compare it to {@link #reseedInterval}.79*80* Volatile, will be used in a double checked locking.81*/82protected volatile int reseedCounter;8384// Mech features. If not same as below, must be redefined in constructor.8586/**87* Default strength of a DRBG instance if it is not configured.88* 128 is considered secure enough now. A mechanism89* can change it in a constructor.90*91* Remember to sync with "securerandom.drbg.config" in java.security.92*/93protected static final int DEFAULT_STRENGTH = 128;9495/**96* Mechanism name, say, {@code HashDRBG}. Must be set in constructor.97* This value will be used in {@code toString}.98*/99protected String mechName = "DRBG";100101/**102* highest_supported_security_strength of this mechanism for all algorithms103* it supports. A mechanism should update the value in its constructor104* if the value is not 256.105*/106protected int highestSupportedSecurityStrength = 256;107108/**109* Whether prediction resistance is supported. A mechanism should update110* the value in its constructor if it is <em>not</em> supported.111*/112protected boolean supportPredictionResistance = true;113114/**115* Whether reseed is supported. A mechanism should update116* the value in its constructor if it is <em>not</em> supported.117*/118protected boolean supportReseeding = true;119120// Strength features. If not same as below, must be redefined in121// chooseAlgorithmAndStrength. Among these, minLength and seedLen have no122// default value and must be redefined. If personalization string or123// additional input is not supported, set maxPersonalizationStringLength124// or maxAdditionalInputLength to -1.125126/**127* Minimum entropy input length in bytes for this DRBG instance.128* Must be assigned in {@link #chooseAlgorithmAndStrength}.129*/130protected int minLength;131132/**133* Maximum entropy input length in bytes for this DRBG instance.134* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not135* {@link Integer#MAX_VALUE}.136* <p>137* In theory this value (and the values below) can be bigger than138* {@code Integer.MAX_VALUE} but a Java array can only have an int32 index.139*/140protected int maxLength = Integer.MAX_VALUE;141142/**143* Maximum personalization string length in bytes for this DRBG instance.144* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not145* {@link Integer#MAX_VALUE}.146*/147protected int maxPersonalizationStringLength = Integer.MAX_VALUE;148149/**150* Maximum additional input length in bytes for this DRBG instance.151* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not152* {@link Integer#MAX_VALUE}.153*/154protected int maxAdditionalInputLength = Integer.MAX_VALUE;155156/**157* max_number_of_bits_per_request in bytes for this DRBG instance.158* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not159* {@link Integer#MAX_VALUE}.160*/161protected int maxNumberOfBytesPerRequest = Integer.MAX_VALUE;162163/**164* Maximum number of requests between reseeds for this DRBG instance.165* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not166* {@link Integer#MAX_VALUE}.167*/168protected int reseedInterval = Integer.MAX_VALUE;169170171/**172* Algorithm used by this instance (SHA-512 or AES-256). Must be assigned173* in {@link #chooseAlgorithmAndStrength}. This field is used in174* {@link #toString()}.175*/176protected String algorithm;177178// Configurable parameters179180/**181* Security strength for this instance. Must be assigned in182* {@link #chooseAlgorithmAndStrength}. Should be at least the requested183* strength. Might be smaller than the highest strength184* {@link #algorithm} supports. Must not be -1.185*/186protected int securityStrength; // in bits187188/**189* Strength requested in {@link DrbgParameters.Instantiation}.190* The real strength is based on it. Do not modify it in a mechanism.191*/192protected int requestedInstantiationSecurityStrength = -1;193194/**195* The personalization string used by this instance. Set inside196* {@link #configure(SecureRandomParameters)} and197* can be used in a mechanism. Do not modify it in a mechanism.198*/199protected byte[] personalizationString;200201/**202* The prediction resistance flag used by this instance. Set inside203* {@link #configure(SecureRandomParameters)}.204*/205private boolean predictionResistanceFlag;206207// Non-standard configurable parameters208209/**210* Whether a derivation function is used. Requested in211* {@link MoreDrbgParameters}. Only CtrDRBG uses it.212* Do not modify it in a mechanism.213*/214protected boolean usedf;215216/**217* The nonce for this instance. Set in {@link #instantiateIfNecessary}.218* After instantiation, this field is not null. Do not modify it219* in a mechanism.220*/221protected byte[] nonce;222223/**224* Requested nonce in {@link MoreDrbgParameters}. If set to null,225* nonce will be chosen by system, and a reinstantiated DRBG will get a226* new system-provided nonce.227*/228private byte[] requestedNonce;229230/**231* Requested algorithm in {@link MoreDrbgParameters}.232* Do not modify it in a mechanism.233*/234protected String requestedAlgorithm;235236/**237* The entropy source used by this instance. Set inside238* {@link #configure(SecureRandomParameters)}. This field239* can be null. {@link #getEntropyInput} will take care of null check.240*/241private EntropySource es;242243// Five abstract methods for SP 800-90A DRBG244245/**246* Decides what algorithm and strength to use (SHA-256 or AES-256,247* 128 or 256). Strength related fields must also be defined or redefined248* here. Called in {@link #configure}. A mechanism uses249* {@link #requestedAlgorithm},250* {@link #requestedInstantiationSecurityStrength}, and251* {@link #DEFAULT_STRENGTH} to decide which algorithm and strength to use.252* <p>253* If {@code requestedAlgorithm} is provided, it will always be used.254* If {@code requestedInstantiationSecurityStrength} is also provided,255* the algorithm will use the strength (an exception will be thrown if256* the strength is not supported), otherwise, the smaller one of257* the highest supported strength of the algorithm and the default strength258* will be used.259* <p>260* If {@code requestedAlgorithm} is not provided, an algorithm will be261* chosen that supports {@code requestedInstantiationSecurityStrength}262* (or {@code DEFAULT_STRENGTH} if there is no request).263* <p>264* Since every call to {@link #configure} will call this method,265* make sure to the calls do not contradict with each other.266* <p>267* Here are some examples of the algorithm and strength chosen (suppose268* {@code DEFAULT_STRENGTH} is 128) for HashDRBG:269* <pre>270* requested effective271* (SHA-224, 256) IAE272* (SHA-256, -1) (SHA-256,128)273* (SHA-256, 112) (SHA-256,112)274* (SHA-256, 128) (SHA-256,128)275* (SHA-3, -1) IAE276* (null, -1) (SHA-256,128)277* (null, 112) (SHA-256,112)278* (null, 192) (SHA-256,192)279* (null, 256) (SHA-256,256)280* (null, 384) IAE281* </pre>282*283* @throws IllegalArgumentException if the requested parameters284* can not be supported or contradict with each other.285*/286protected abstract void chooseAlgorithmAndStrength();287288/**289* Initiates security engines ({@code MessageDigest}, {@code Mac},290* or {@code Cipher}). This method is called during instantiation.291*/292protected abstract void initEngine();293294/**295* Instantiates a DRBG. Called automatically before the first296* {@code nextBytes} call.297* <p>298* Note that the other parameters (nonce, strength, ps) are already299* stored inside at configuration.300*301* @param ei the entropy input, its length is already conditioned to be302* between {@link #minLength} and {@link #maxLength}.303*/304protected abstract void instantiateAlgorithm(byte[] ei);305306/**307* The generate function.308*309* @param result fill result here, not null310* @param additionalInput additional input, can be null. If not null,311* its length is smaller than {@link #maxAdditionalInputLength}312*/313protected abstract void generateAlgorithm(314byte[] result, byte[] additionalInput);315316/**317* The reseed function.318*319* @param ei the entropy input, its length is already conditioned to be320* between {@link #minLength} and {@link #maxLength}.321* @param additionalInput additional input, can be null. If not null,322* its length is smaller than {@link #maxAdditionalInputLength}323* @throws UnsupportedOperationException if reseed is not supported324*/325protected void reseedAlgorithm(326byte[] ei, byte[] additionalInput) {327throw new UnsupportedOperationException("No reseed function");328}329330// SecureRandomSpi methods taken care of here. All final.331332protected final void engineNextBytes(byte[] result) {333engineNextBytes(result, DrbgParameters.nextBytes(334-1, predictionResistanceFlag, null));335}336337protected final void engineNextBytes(338byte[] result, SecureRandomParameters params) {339340Objects.requireNonNull(result);341342if (debug != null) {343debug.println(this, "nextBytes");344}345if (params instanceof DrbgParameters.NextBytes) {346347// 800-90Ar1 9.3: Generate Process.348349DrbgParameters.NextBytes dp = (DrbgParameters.NextBytes) params;350351// Step 2: max_number_of_bits_per_request352if (result.length > maxNumberOfBytesPerRequest) {353// generateAlgorithm should be called multiple times to fill354// up result. Unimplemented since maxNumberOfBytesPerRequest355// is now Integer.MAX_VALUE.356}357358// Step 3: check requested_security_strength359if (dp.getStrength() > securityStrength) {360throw new IllegalArgumentException("strength too high: "361+ dp.getStrength());362}363364// Step 4: check max_additional_input_length365byte[] ai = dp.getAdditionalInput();366if (ai != null && ai.length > maxAdditionalInputLength) {367throw new IllegalArgumentException("ai too long: "368+ ai.length);369}370371// Step 5: check prediction_resistance_flag372boolean pr = dp.getPredictionResistance();373if (!predictionResistanceFlag && pr) {374throw new IllegalArgumentException("pr not available");375}376377instantiateIfNecessary(null);378379// Step 7: Auto reseed (reseedCounter might overflow)380// Double checked locking, safe because reseedCounter is volatile381if (reseedCounter < 0 || reseedCounter > reseedInterval || pr) {382synchronized (this) {383if (reseedCounter < 0 || reseedCounter > reseedInterval384|| pr) {385reseedAlgorithm(getEntropyInput(pr), ai);386ai = null;387}388}389}390391// Step 8, 10: Generate_algorithm392// Step 9: Unnecessary. reseedCounter only updated after generation393generateAlgorithm(result, ai);394395// Step 11: Return396} else {397throw new IllegalArgumentException("unknown params type:"398+ params.getClass());399}400}401402public final void engineReseed(SecureRandomParameters params) {403if (debug != null) {404debug.println(this, "reseed with params");405}406if (!supportReseeding) {407throw new UnsupportedOperationException("Reseed not supported");408}409if (params == null) {410params = DrbgParameters.reseed(predictionResistanceFlag, null);411}412if (params instanceof DrbgParameters.Reseed) {413DrbgParameters.Reseed dp = (DrbgParameters.Reseed) params;414415// 800-90Ar1 9.2: Reseed Process.416417// Step 2: Check prediction_resistance_request418boolean pr = dp.getPredictionResistance();419if (!predictionResistanceFlag && pr) {420throw new IllegalArgumentException("pr not available");421}422423// Step 3: Check additional_input length424byte[] ai = dp.getAdditionalInput();425if (ai != null && ai.length > maxAdditionalInputLength) {426throw new IllegalArgumentException("ai too long: "427+ ai.length);428}429instantiateIfNecessary(null);430431// Step 4: Get_entropy_input432// Step 5: Check step 4433// Step 6-7: Reseed_algorithm434reseedAlgorithm(getEntropyInput(pr), ai);435436// Step 8: Return437} else {438throw new IllegalArgumentException("unknown params type: "439+ params.getClass());440}441}442443/**444* Returns the given number of seed bytes. A DRBG always uses445* {@link SeedGenerator} to get an array with full-entropy.446* <p>447* The implementation is identical to SHA1PRNG's448* {@link SecureRandom#engineGenerateSeed}.449*450* @param numBytes the number of seed bytes to generate.451* @return the seed bytes.452*/453public final byte[] engineGenerateSeed(int numBytes) {454byte[] b = new byte[numBytes];455SeedGenerator.generateSeed(b);456return b;457}458459/**460* Reseeds this random object with the given seed. A DRBG always expands461* or truncates the input to be between {@link #minLength} and462* {@link #maxLength} and uses it to instantiate or reseed itself463* (depending on whether the DRBG is instantiated).464*465* @param input the seed466*/467public final synchronized void engineSetSeed(byte[] input) {468if (debug != null) {469debug.println(this, "setSeed");470}471if (input.length < minLength) {472input = Arrays.copyOf(input, minLength);473} else if (input.length > maxLength) {474input = Arrays.copyOf(input, maxLength);475}476if (!instantiated) {477instantiateIfNecessary(input);478} else {479reseedAlgorithm(input, null);480}481}482483// get_entropy_input484485private byte[] getEntropyInput(boolean isPr) {486// Should the 1st arg be minEntropy or minLength?487//488// Technically it should be minEntropy, but CtrDRBG489// (not using derivation function) is so confusing490// (does it need only strength or seedlen of entropy?)491// that it's safer to assume minLength. In all other492// cases minLength is equal to minEntropy.493return getEntropyInput(minLength, minLength, maxLength, isPr);494}495496private byte[] getEntropyInput(int minEntropy, int minLength,497int maxLength, boolean pr) {498if (debug != null) {499debug.println(this, "getEntropy(" + minEntropy + "," + minLength +500"," + maxLength + "," + pr + ")");501}502EntropySource esNow = es;503if (esNow == null) {504esNow = pr ? SeederHolder.prseeder : SeederHolder.seeder;505}506return esNow.getEntropy(minEntropy, minLength, maxLength, pr);507}508509// Defaults510511/**512* The default {@code EntropySource} determined by system property513* "java.security.egd" or security property "securerandom.source".514* <p>515* This object uses {@link SeedGenerator#generateSeed(byte[])} to516* return a byte array containing {@code minLength} bytes. It is517* assumed to support prediction resistance and always contains518* full-entropy.519*/520private static final EntropySource defaultES =521(minE, minLen, maxLen, pr) -> {522byte[] result = new byte[minLen];523SeedGenerator.generateSeed(result);524return result;525};526527private static class SeederHolder {528529/**530* Default EntropySource for SecureRandom with prediction resistance,531*/532static final EntropySource prseeder;533534/**535* Default EntropySource for SecureRandom without prediction resistance,536* which is backed by a DRBG whose EntropySource is {@link #prseeder}.537*/538static final EntropySource seeder;539540static {541prseeder = defaultES;542// According to SP800-90C section 7, a DRBG without live543// entropy (drbg here, with pr being false) can instantiate544// another DRBG with weaker strength. So we choose highest545// strength we support.546HashDrbg first = new HashDrbg(new MoreDrbgParameters(547prseeder, null, "SHA-256", null, false,548DrbgParameters.instantiation(549256, NONE,550SeedGenerator.getSystemEntropy())));551seeder = (entropy, minLen, maxLen, pr) -> {552if (pr) {553// This SEI does not support pr554throw new IllegalArgumentException("pr not supported");555}556byte[] result = new byte[minLen];557first.engineNextBytes(result);558return result;559};560}561}562563// Constructor called by overridden methods, initializer...564565/**566* A constructor without argument so that an implementation does not567* need to always write {@code super(params)}.568*/569protected AbstractDrbg() {570// Nothing571}572573/**574* A mechanism shall override this constructor to setup {@link #mechName},575* {@link #highestSupportedSecurityStrength},576* {@link #supportPredictionResistance}, {@link #supportReseeding}577* or other features like {@link #DEFAULT_STRENGTH}. Finally it shall578* call {@link #configure} on {@code params}.579*580* @param params the {@link SecureRandomParameters} object.581* This argument can be {@code null}.582* @throws IllegalArgumentException if {@code params} is583* inappropriate for this SecureRandom.584*/585protected AbstractDrbg(SecureRandomParameters params) {586// Nothing587}588589/**590* Returns the current configuration as a {@link DrbgParameters.Instantiation}591* object.592*593* @return the curent configuration594*/595protected SecureRandomParameters engineGetParameters() {596// Or read from variable.597return DrbgParameters.instantiation(598securityStrength,599predictionResistanceFlag ? PR_AND_RESEED :600(supportReseeding ? RESEED_ONLY : NONE),601personalizationString);602}603604/**605* Configure this DRBG. This method calls606* {@link #chooseAlgorithmAndStrength()} and {@link #initEngine()}607* but does not do the actual instantiation.608*609* @param params configuration, if null, default configuration (default610* strength, pr_false, no personalization string) is used.611* @throws IllegalArgumentException if {@code params} is612* inappropriate for this SecureRandom.613*/614protected final void configure(SecureRandomParameters params) {615if (debug != null) {616debug.println(this, "configure " + this + " with " + params);617}618if (params == null) {619params = DrbgParameters.instantiation(-1, RESEED_ONLY, null);620}621if (params instanceof MoreDrbgParameters) {622MoreDrbgParameters m = (MoreDrbgParameters)params;623this.requestedNonce = m.nonce;624this.es = m.es;625this.requestedAlgorithm = m.algorithm;626this.usedf = m.usedf;627params = DrbgParameters.instantiation(m.strength,628m.capability, m.personalizationString);629}630if (params != null) {631if (params instanceof DrbgParameters.Instantiation) {632DrbgParameters.Instantiation inst =633(DrbgParameters.Instantiation) params;634635// 800-90Ar1 9.1: Instantiate Process. Steps 1-5.636637// Step 1: Check requested_instantiation_security_strength638if (inst.getStrength() > highestSupportedSecurityStrength) {639throw new IllegalArgumentException("strength too big: "640+ inst.getStrength());641}642643// Step 2: Check prediction_resistance_flag644if (inst.getCapability().supportsPredictionResistance()645&& !supportPredictionResistance) {646throw new IllegalArgumentException("pr not supported");647}648649// Step 3: Check personalization_string650byte[] ps = inst.getPersonalizationString();651if (ps != null && ps.length > maxPersonalizationStringLength) {652throw new IllegalArgumentException("ps too long: "653+ ps.length);654}655656if (inst.getCapability().supportsReseeding()657&& !supportReseeding) {658throw new IllegalArgumentException("reseed not supported");659}660this.personalizationString = ps;661this.predictionResistanceFlag =662inst.getCapability().supportsPredictionResistance();663this.requestedInstantiationSecurityStrength = inst.getStrength();664} else {665throw new IllegalArgumentException("unknown params: "666+ params.getClass());667}668}669670// Step 4: Set security_strength671chooseAlgorithmAndStrength();672instantiated = false;673674// Step 5: no-op.675676if (debug != null) {677debug.println(this, "configured " + this);678}679}680681/**682* Instantiate if necessary,683*684* @param entropy a user-provided entropy, the length is already good.685* If null, will fetch entropy input automatically.686*/687private synchronized void instantiateIfNecessary(byte[] entropy) {688if (!instantiated) {689690// 800-90Ar1 9.1: Instantiate Process. Steps 6-12.691692// Step 6: Get_entropy_input693// Step 7: check error (getEntropyInput throw no exception now)694if (entropy == null) {695entropy = getEntropyInput(predictionResistanceFlag);696}697698// Step 8. nonce699if (requestedNonce != null) {700nonce = requestedNonce;701} else {702nonce = NonceProvider.next();703}704initEngine();705706// Step 9-11: Instantiate_algorithm707instantiateAlgorithm(entropy);708instantiated = true;709710// Step 12: Return711}712}713714// Nonce provider715716private static class NonceProvider {717718// 128 bits of nonce can be used by 256-bit strength DRBG719private static final byte[] block = new byte[16];720721private static synchronized byte[] next() {722int k = 15;723while ((k >= 0) && (++block[k] == 0)) {724k--;725}726return block.clone();727}728}729730// Misc731732/**733* Returns the smallest standard strength (112, 128, 192, 256) that is734* greater or equal to the input.735*736* @param input the input strength737* @return the standard strength738*/739protected static int getStandardStrength(int input) {740if (input <= 112) return 112;741if (input <= 128) return 128;742if (input <= 192) return 192;743if (input <= 256) return 256;744throw new IllegalArgumentException("input too big: " + input);745}746747@Override748public String toString() {749return mechName + "," + algorithm750+ "," + securityStrength + ","751+ (predictionResistanceFlag ? "pr_and_reseed"752: (supportReseeding ? "reseed_only" : "none"));753}754}755756757