1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
|
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8141039
* @library /lib/testlibrary
* @summary This test do API coverage for SecureRandom. It covers most of
* supported operations along with possible positive and negative
* parameters for DRBG mechanism.
* @run main/othervm ApiTest Hash_DRBG
* @run main/othervm ApiTest HMAC_DRBG
* @run main/othervm ApiTest CTR_DRBG
* @run main/othervm ApiTest SHA1PRNG
* @run main/othervm ApiTest NATIVE
*/
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SecureRandomParameters;
import java.security.DrbgParameters;
import java.security.DrbgParameters.Instantiation;
import java.security.DrbgParameters.Capability;
import javax.crypto.Cipher;
public class ApiTest {
private static final boolean SHOULD_PASS = true;
private static final long SEED = 1l;
private static final String INVALID_ALGO = "INVALID";
private static final String DRBG_CONFIG = "securerandom.drbg.config";
private static final String DRBG_CONFIG_VALUE
= Security.getProperty(DRBG_CONFIG);
public static void main(String[] args) throws Exception {
System.setProperty("java.security.egd", "file:/dev/urandom");
if (args == null || args.length < 1) {
throw new RuntimeException("No mechanism available to run test.");
}
String mech
= "NATIVE".equals(args[0]) ? supportedNativeAlgo() : args[0];
String[] algs = null;
boolean success = true;
try {
if (!isDRBG(mech)) {
SecureRandom random = SecureRandom.getInstance(mech);
verifyAPI(random, mech);
return;
} else if (mech.equals("CTR_DRBG")) {
algs = new String[]{"AES-128", "AES-192", "AES-256",
INVALID_ALGO};
} else if (mech.equals("Hash_DRBG") || mech.equals("HMAC_DRBG")) {
algs = new String[]{"SHA-224", "SHA-256", "SHA-512/224",
"SHA-512/256", "SHA-384", "SHA-512", INVALID_ALGO};
} else {
throw new RuntimeException(
String.format("Not a valid mechanism '%s'", mech));
}
runForEachMech(mech, algs);
} catch (Exception e) {
e.printStackTrace(System.out);
success = false;
}
if (!success) {
throw new RuntimeException("At least one test failed.");
}
}
/**
* Run the test for a DRBG mechanism with a possible set of parameter
* combination.
* @param mech DRBG mechanism name
* @param algs Algorithm supported by each mechanism
* @throws Exception
*/
private static void runForEachMech(String mech, String[] algs)
throws Exception {
for (String alg : algs) {
runForEachAlg(mech, alg);
}
}
private static void runForEachAlg(String mech, String alg)
throws Exception {
for (int strength : new int[]{-1, 0, 1, 223, 224,
192, 255, 256}) {
for (Capability cp : Capability.values()) {
for (byte[] pr : new byte[][]{null, new byte[]{},
"personal".getBytes()}) {
SecureRandomParameters param
= DrbgParameters.instantiation(strength, cp, pr);
runForEachParam(mech, alg, param);
}
}
}
}
private static void runForEachParam(String mech, String alg,
SecureRandomParameters param) throws Exception {
for (boolean df : new Boolean[]{true, false}) {
try {
Security.setProperty(DRBG_CONFIG, mech + "," + alg + ","
+ (df ? "use_df" : "no_df"));
System.out.printf("%nParameter for SecureRandom "
+ "mechanism: %s is (param:%s, algo:%s, df:%s)",
mech, param, alg, df);
SecureRandom sr = SecureRandom.getInstance("DRBG", param);
verifyAPI(sr, mech);
} catch (NoSuchAlgorithmException e) {
// Verify exception status for current test.
checkException(getDefaultAlg(mech, alg), param, e);
} finally {
Security.setProperty(DRBG_CONFIG, DRBG_CONFIG_VALUE);
}
}
}
/**
* Returns the algorithm supported for input mechanism.
* @param mech Mechanism name
* @param alg Algorithm name
* @return Algorithm name
*/
private static String getDefaultAlg(String mech, String alg)
throws NoSuchAlgorithmException {
if (alg == null) {
switch (mech) {
case "Hash_DRBG":
case "HMAC_DRBG":
return "SHA-256";
case "CTR_DRBG":
return (Cipher.getMaxAllowedKeyLength("AES") < 256)
? "AES-128" : "AES-256";
default:
throw new RuntimeException("Mechanism not supported");
}
}
return alg;
}
/**
* Verify the exception type either it is expected to occur or not.
* @param alg Algorithm name
* @param param DRBG parameter
* @param e Exception to verify
* @throws NoSuchAlgorithmException
*/
private static void checkException(String alg, SecureRandomParameters param,
NoSuchAlgorithmException e) throws NoSuchAlgorithmException {
int strength = ((Instantiation) param).getStrength();
boolean error = true;
switch (alg) {
case INVALID_ALGO:
error = false;
break;
case "SHA-224":
case "SHA-512/224":
if (strength > 192) {
error = false;
}
break;
case "SHA-256":
case "SHA-512/256":
case "SHA-384":
case "SHA-512":
if (strength > 256) {
error = false;
}
break;
case "AES-128":
case "AES-192":
case "AES-256":
int algoStrength = Integer.parseInt(alg.substring("AES-".length()));
int maxAESStrength = Cipher.getMaxAllowedKeyLength("AES");
if (strength > algoStrength
|| algoStrength > maxAESStrength) {
error = false;
}
break;
}
if (error) {
throw new RuntimeException("Unknown :", e);
}
}
/**
* Find if the mechanism is a DRBG mechanism.
* @param mech Mechanism name
* @return True for DRBG mechanism else False
*/
private static boolean isDRBG(String mech) {
return mech.contains("_DRBG");
}
/**
* Find the name of supported native mechanism name for current platform.
*/
private static String supportedNativeAlgo() {
String nativeSr = "Windows-PRNG";
try {
SecureRandom.getInstance(nativeSr);
} catch (NoSuchAlgorithmException e) {
nativeSr = "NativePRNG";
}
return nativeSr;
}
/**
* Test a possible set of SecureRandom API for a SecureRandom instance.
* @param random SecureRandom instance
* @param mech Mechanism used to create SecureRandom instance
*/
private static void verifyAPI(SecureRandom random, String mech)
throws Exception {
System.out.printf("%nTest SecureRandom mechanism: %s for provider: %s",
mech, random.getProvider().getName());
byte[] output = new byte[2];
// Generate random number.
random.nextBytes(output);
// Seed the SecureRandom with a generated seed value of lesser size.
byte[] seed = random.generateSeed(1);
random.setSeed(seed);
random.nextBytes(output);
// Seed the SecureRandom with a fixed seed value.
random.setSeed(SEED);
random.nextBytes(output);
// Seed the SecureRandom with a larger seed value.
seed = random.generateSeed(128);
random.setSeed(seed);
random.nextBytes(output);
// Additional operation only supported for DRBG based SecureRandom.
// Execute the code block and expect to pass for DRBG. If it will fail
// then it should fail with specified exception type. Else the case
// will be considered as a test case failure.
matchExc(() -> {
random.reseed();
random.nextBytes(output);
},
isDRBG(mech),
UnsupportedOperationException.class,
String.format("PASS - Unsupported reseed() method for "
+ "SecureRandom Algorithm %s ", mech));
matchExc(() -> {
random.reseed(DrbgParameters.reseed(false, new byte[]{}));
random.nextBytes(output);
},
isDRBG(mech),
UnsupportedOperationException.class,
String.format("PASS - Unsupported reseed(param) method for "
+ "SecureRandom Algorithm %s ", mech));
matchExc(() -> {
random.reseed(DrbgParameters.reseed(true, new byte[]{}));
random.nextBytes(output);
},
isDRBG(mech),
!isSupportPR(mech, random) ? IllegalArgumentException.class
: UnsupportedOperationException.class,
String.format("PASS - Unsupported or illegal reseed(param) "
+ "method for SecureRandom Algorithm %s ", mech));
matchExc(() -> random.nextBytes(output,
DrbgParameters.nextBytes(-1, false, new byte[]{})),
isDRBG(mech),
UnsupportedOperationException.class,
String.format("PASS - Unsupported nextBytes(out, nextByteParam)"
+ " method for SecureRandom Algorithm %s ", mech));
matchExc(() -> random.nextBytes(output,
DrbgParameters.nextBytes(-1, true, new byte[]{})),
isDRBG(mech),
!isSupportPR(mech, random) ? IllegalArgumentException.class
: UnsupportedOperationException.class,
String.format("PASS - Unsupported or illegal "
+ "nextBytes(out, nextByteParam) method for "
+ "SecureRandom Algorithm %s ", mech));
matchExc(() -> {
random.reseed(null);
random.nextBytes(output);
},
!SHOULD_PASS,
IllegalArgumentException.class,
"PASS - Test is expected to fail when parameter for reseed() "
+ "is null");
matchExc(() -> random.nextBytes(output, null),
!SHOULD_PASS,
IllegalArgumentException.class,
"PASS - Test is expected to fail when parameter for nextBytes()"
+ " is null");
}
private static boolean isSupportPR(String mech, SecureRandom random) {
return (isDRBG(mech) && ((Instantiation) random.getParameters())
.getCapability()
.supportsPredictionResistance());
}
private interface RunnableCode {
void run() throws Exception;
}
/**
* Execute a given code block and verify, if the exception type is expected.
* @param r Code block to run
* @param ex Expected exception type
* @param shouldPass If the code execution expected to pass without failure
* @param msg Message to log in case of expected failure
*/
private static void matchExc(RunnableCode r, boolean shouldPass, Class ex,
String msg) {
try {
r.run();
if (!shouldPass) {
throw new RuntimeException("Excecution should fail here.");
}
} catch (Exception e) {
System.out.printf("%nOccured exception: %s - Expected exception: "
+ "%s : ", e.getClass(), ex.getCanonicalName());
if (ex.isAssignableFrom(e.getClass())) {
System.out.printf("%n%s : Expected Exception occured: %s : ",
e.getClass(), msg);
} else if (shouldPass) {
throw new RuntimeException(e);
} else {
System.out.printf("Ignore the following exception: %s%n",
e.getMessage());
}
}
}
}
|