提交 024b4961 编写于 作者: A aefimov

Merge

......@@ -915,6 +915,7 @@ f26f68978e0e7ed0e6e61f9d64fa2d06f1c1a24c jdk8u181-b08
22e01e7c5c39bfa3f5e2d18be76c7bf0dc71033a jdk8u181-b12
0cb452d66676bc1b3824bea4a0c16ac76e58b070 jdk8u181-b13
b01c6e5aa43c784fc66465b56227ddd9aa29eee6 jdk8u191-b01
2db6890a956723ac347b573217d91bbbedbb0528 jdk8u201-b00
2db6890a956723ac347b573217d91bbbedbb0528 jdk8u191-b02
89e2889d02d2f5dabdeda7f60cf80a8df3100eb4 jdk8u191-b03
94e4769c6d69241f9eb7164a85fc91fc83faab5c jdk8u191-b04
......@@ -945,6 +946,16 @@ f47b81dbed2dd730d34a8dc3e3d14e2aa9f9c493 jdk8u192-b09
2cd82eb879dd0f853dbfb7ffa2441e81e2413447 jdk8u192-b11
f877dad22786f92aa495a595a1a4a16f0163c573 jdk8u192-b12
996dd3ce1ec5437da8b5a742c60a5ff7b6028122 jdk8u192-b26
38b4a5b97f38c467446f1767d148075ac98397d1 jdk8u181-b31
d679861a9a1efc80e0671b1c6b870fcffbfb9d9c jdk8u181-b32
078a06936ffe2db2a00e928f88c6e345a126985a jdk8u181-b33
ecfdede1e6ddf37dcca415861ab031c18ec4b349 jdk8u181-b34
ac943243eaf1cb3971b953d56527287ae3f8d223 jdk8u181-b35
674963395b9f747e746af782f2f3ea7995385420 jdk8u181-b36
92587df933606ff8f03c6073be6c4089211de2b3 jdk8u181-b37
fbc886dd68cc0e2d877406f73a24bd332bf78244 jdk8u201-b01
fbeb9b9cc0106ef9bd6b03a441c9a2e06db07bd9 jdk8u201-b02
274162fd9a2334ac99157a87ff3caff9069e4a66 jdk8u201-b03
9da3ff5cd435240bc4941bc1c2ca170c567e012f jdk8u202-b01
478a4add975beb90696a4ead5f8fcd9c17fc1a83 jdk8u202-b02
03719dd7706173821b51f42b20ac3cb040696a56 jdk8u202-b03
......@@ -75,7 +75,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBNET, \
LDFLAGS_SUFFIX_linux := $(LIBDL) -ljvm -lpthread -ljava, \
LDFLAGS_SUFFIX_aix := $(LIBDL) -ljvm -ljava,\
LDFLAGS_SUFFIX_windows := ws2_32.lib jvm.lib secur32.lib iphlpapi.lib \
delayimp.lib $(WIN_JAVA_LIB) advapi32.lib \
delayimp.lib urlmon.lib $(WIN_JAVA_LIB) advapi32.lib \
-DELAYLOAD:secur32.dll -DELAYLOAD:iphlpapi.dll, \
VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \
RC_FLAGS := $(RC_FLAGS) \
......
/*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2018, 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
......@@ -329,7 +329,7 @@ public final class RSACipher extends CipherSpi {
if ((inLen == 0) || (in == null)) {
return;
}
if (bufOfs + inLen > buffer.length) {
if (inLen > (buffer.length - bufOfs)) {
bufOfs = buffer.length + 1;
return;
}
......
......@@ -391,6 +391,7 @@ public class Robot {
* @return Color of the pixel
*/
public synchronized Color getPixelColor(int x, int y) {
checkScreenCaptureAllowed();
Color color = new Color(peer.getRGBPixel(x, y));
return color;
}
......
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2018, 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
......@@ -29,8 +29,8 @@
package java.math;
import java.util.Arrays;
import static java.math.BigInteger.LONG_MASK;
import java.util.Arrays;
/**
* Immutable, arbitrary-precision signed decimal numbers. A
......@@ -407,9 +407,12 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* @since 1.5
*/
public BigDecimal(char[] in, int offset, int len, MathContext mc) {
// protect against huge length.
if (offset + len > in.length || offset < 0)
throw new NumberFormatException("Bad offset or len arguments for char[] input.");
// protect against huge length, negative values, and integer overflow
if ((in.length | len | offset) < 0 || len > in.length - offset) {
throw new NumberFormatException
("Bad offset or len arguments for char[] input.");
}
// This is the primary string to BigDecimal constructor; all
// incoming strings end up here; it uses explicit (inline)
// parsing for speed and generates at most one intermediate
......
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2018, 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
......@@ -1161,6 +1161,14 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
private static final double LOG_TWO = Math.log(2.0);
static {
assert 0 < KARATSUBA_THRESHOLD
&& KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD
&& TOOM_COOK_THRESHOLD < Integer.MAX_VALUE
&& 0 < KARATSUBA_SQUARE_THRESHOLD
&& KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD
&& TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE :
"Algorithm thresholds are inconsistent";
for (int i = 1; i <= MAX_CONSTANT; i++) {
int[] magnitude = new int[1];
magnitude[0] = i;
......@@ -1482,6 +1490,18 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* @return {@code this * val}
*/
public BigInteger multiply(BigInteger val) {
return multiply(val, false);
}
/**
* Returns a BigInteger whose value is {@code (this * val)}. If
* the invocation is recursive certain overflow checks are skipped.
*
* @param val value to be multiplied by this BigInteger.
* @param isRecursion whether this is a recursive invocation
* @return {@code this * val}
*/
private BigInteger multiply(BigInteger val, boolean isRecursion) {
if (val.signum == 0 || signum == 0)
return ZERO;
......@@ -1509,6 +1529,63 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
return multiplyKaratsuba(this, val);
} else {
//
// In "Hacker's Delight" section 2-13, p.33, it is explained
// that if x and y are unsigned 32-bit quantities and m and n
// are their respective numbers of leading zeros within 32 bits,
// then the number of leading zeros within their product as a
// 64-bit unsigned quantity is either m + n or m + n + 1. If
// their product is not to overflow, it cannot exceed 32 bits,
// and so the number of leading zeros of the product within 64
// bits must be at least 32, i.e., the leftmost set bit is at
// zero-relative position 31 or less.
//
// From the above there are three cases:
//
// m + n leftmost set bit condition
// ----- ---------------- ---------
// >= 32 x <= 64 - 32 = 32 no overflow
// == 31 x >= 64 - 32 = 32 possible overflow
// <= 30 x >= 64 - 31 = 33 definite overflow
//
// The "possible overflow" condition cannot be detected by
// examning data lengths alone and requires further calculation.
//
// By analogy, if 'this' and 'val' have m and n as their
// respective numbers of leading zeros within 32*MAX_MAG_LENGTH
// bits, then:
//
// m + n >= 32*MAX_MAG_LENGTH no overflow
// m + n == 32*MAX_MAG_LENGTH - 1 possible overflow
// m + n <= 32*MAX_MAG_LENGTH - 2 definite overflow
//
// Note however that if the number of ints in the result
// were to be MAX_MAG_LENGTH and mag[0] < 0, then there would
// be overflow. As a result the leftmost bit (of mag[0]) cannot
// be used and the constraints must be adjusted by one bit to:
//
// m + n > 32*MAX_MAG_LENGTH no overflow
// m + n == 32*MAX_MAG_LENGTH possible overflow
// m + n < 32*MAX_MAG_LENGTH definite overflow
//
// The foregoing leading zero-based discussion is for clarity
// only. The actual calculations use the estimated bit length
// of the product as this is more natural to the internal
// array representation of the magnitude which has no leading
// zero elements.
//
if (!isRecursion) {
// The bitLength() instance method is not used here as we
// are only considering the magnitudes as non-negative. The
// Toom-Cook multiplication algorithm determines the sign
// at its end from the two signum values.
if (bitLength(mag, mag.length) +
bitLength(val.mag, val.mag.length) >
32L*MAX_MAG_LENGTH) {
reportOverflow();
}
}
return multiplyToomCook3(this, val);
}
}
......@@ -1587,7 +1664,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
int ystart = ylen - 1;
if (z == null || z.length < (xlen+ ylen))
z = new int[xlen+ylen];
z = new int[xlen+ylen];
long carry = 0;
for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
......@@ -1709,16 +1786,16 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
v0 = a0.multiply(b0);
v0 = a0.multiply(b0, true);
da1 = a2.add(a0);
db1 = b2.add(b0);
vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);
da1 = da1.add(a1);
db1 = db1.add(b1);
v1 = da1.multiply(db1);
v1 = da1.multiply(db1, true);
v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
db1.add(b2).shiftLeft(1).subtract(b0));
vinf = a2.multiply(b2);
db1.add(b2).shiftLeft(1).subtract(b0), true);
vinf = a2.multiply(b2, true);
// The algorithm requires two divisions by 2 and one by 3.
// All divisions are known to be exact, that is, they do not produce
......@@ -1884,6 +1961,17 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* @return {@code this<sup>2</sup>}
*/
private BigInteger square() {
return square(false);
}
/**
* Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If
* the invocation is recursive certain overflow checks are skipped.
*
* @param isRecursion whether this is a recursive invocation
* @return {@code this<sup>2</sup>}
*/
private BigInteger square(boolean isRecursion) {
if (signum == 0) {
return ZERO;
}
......@@ -1896,6 +1984,15 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
if (len < TOOM_COOK_SQUARE_THRESHOLD) {
return squareKaratsuba();
} else {
//
// For a discussion of overflow detection see multiply()
//
if (!isRecursion) {
if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) {
reportOverflow();
}
}
return squareToomCook3();
}
}
......@@ -2046,13 +2143,13 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
a0 = getToomSlice(k, r, 2, len);
BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
v0 = a0.square();
v0 = a0.square(true);
da1 = a2.add(a0);
vm1 = da1.subtract(a1).square();
vm1 = da1.subtract(a1).square(true);
da1 = da1.add(a1);
v1 = da1.square();
vinf = a2.square();
v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
v1 = da1.square(true);
vinf = a2.square(true);
v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);
// The algorithm requires two divisions by 2 and one by 3.
// All divisions are known to be exact, that is, they do not produce
......@@ -2223,10 +2320,11 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
// The remaining part can then be exponentiated faster. The
// powers of two will be multiplied back at the end.
int powersOfTwo = partToSquare.getLowestSetBit();
long bitsToShift = (long)powersOfTwo * exponent;
if (bitsToShift > Integer.MAX_VALUE) {
long bitsToShiftLong = (long)powersOfTwo * exponent;
if (bitsToShiftLong > Integer.MAX_VALUE) {
reportOverflow();
}
int bitsToShift = (int)bitsToShiftLong;
int remainingBits;
......@@ -2236,9 +2334,9 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
remainingBits = partToSquare.bitLength();
if (remainingBits == 1) { // Nothing left but +/- 1?
if (signum < 0 && (exponent&1) == 1) {
return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
return NEGATIVE_ONE.shiftLeft(bitsToShift);
} else {
return ONE.shiftLeft(powersOfTwo*exponent);
return ONE.shiftLeft(bitsToShift);
}
}
} else {
......@@ -2283,13 +2381,16 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
if (bitsToShift + scaleFactor <= 62) { // Fits in long?
return valueOf((result << bitsToShift) * newSign);
} else {
return valueOf(result*newSign).shiftLeft((int) bitsToShift);
return valueOf(result*newSign).shiftLeft(bitsToShift);
}
}
else {
} else {
return valueOf(result*newSign);
}
} else {
if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) {
reportOverflow();
}
// Large number algorithm. This is basically identical to
// the algorithm above, but calls multiply() and square()
// which may use more efficient algorithms for large numbers.
......@@ -2309,7 +2410,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
// Multiply back the (exponentiated) powers of two (quickly,
// by shifting left)
if (powersOfTwo > 0) {
answer = answer.shiftLeft(powersOfTwo*exponent);
answer = answer.shiftLeft(bitsToShift);
}
if (signum < 0 && (exponent&1) == 1) {
......@@ -3434,7 +3535,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
for (int i=1; i< len && pow2; i++)
pow2 = (mag[i] == 0);
n = (pow2 ? magBitLength -1 : magBitLength);
n = (pow2 ? magBitLength - 1 : magBitLength);
} else {
n = magBitLength;
}
......
......@@ -33,8 +33,7 @@ import java.net.URL;
* credentials without prompting) should only be tried with trusted sites.
*/
public abstract class NTLMAuthenticationCallback {
private static volatile NTLMAuthenticationCallback callback =
new DefaultNTLMAuthenticationCallback();
private static volatile NTLMAuthenticationCallback callback;
public static void setNTLMAuthenticationCallback(
NTLMAuthenticationCallback callback) {
......@@ -50,10 +49,5 @@ public abstract class NTLMAuthenticationCallback {
* transparent Authentication.
*/
public abstract boolean isTrustedSite(URL url);
static class DefaultNTLMAuthenticationCallback extends NTLMAuthenticationCallback {
@Override
public boolean isTrustedSite(URL url) { return true; }
}
}
......@@ -551,11 +551,10 @@ public class FileChannelImpl
{
// Untrusted target: Use a newly-erased buffer
int c = Math.min(icount, TRANSFER_SIZE);
ByteBuffer bb = Util.getTemporaryDirectBuffer(c);
ByteBuffer bb = ByteBuffer.allocate(c);
long tw = 0; // Total bytes written
long pos = position;
try {
Util.erase(bb);
while (tw < icount) {
bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE));
int nr = read(bb, pos);
......@@ -576,8 +575,6 @@ public class FileChannelImpl
if (tw > 0)
return tw;
throw x;
} finally {
Util.releaseTemporaryDirectBuffer(bb);
}
}
......@@ -661,11 +658,10 @@ public class FileChannelImpl
{
// Untrusted target: Use a newly-erased buffer
int c = (int)Math.min(count, TRANSFER_SIZE);
ByteBuffer bb = Util.getTemporaryDirectBuffer(c);
ByteBuffer bb = ByteBuffer.allocate(c);
long tw = 0; // Total bytes written
long pos = position;
try {
Util.erase(bb);
while (tw < count) {
bb.limit((int)Math.min((count - tw), (long)TRANSFER_SIZE));
// ## Bug: Will block reading src if this channel
......@@ -686,8 +682,6 @@ public class FileChannelImpl
if (tw > 0)
return tw;
throw x;
} finally {
Util.releaseTemporaryDirectBuffer(bb);
}
}
......
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2018, 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
......@@ -472,6 +472,10 @@ final class P11Signature extends SignatureSpi {
if (len == 0) {
return;
}
// check for overflow
if (len + bytesProcessed < 0) {
throw new ProviderException("Processed bytes limits exceeded.");
}
switch (type) {
case T_UPDATE:
try {
......
/*
* Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2018, 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
......@@ -491,7 +491,7 @@ abstract class DSA extends SignatureSpi {
}
}
protected void engineUpdate(byte[] input, int offset, int len) {
if (ofs + len > digestBuffer.length) {
if (len > (digestBuffer.length - ofs)) {
ofs = Integer.MAX_VALUE;
} else {
System.arraycopy(input, offset, digestBuffer, ofs, len);
......@@ -500,7 +500,7 @@ abstract class DSA extends SignatureSpi {
}
protected final void engineUpdate(ByteBuffer input) {
int inputLen = input.remaining();
if (ofs + inputLen > digestBuffer.length) {
if (inputLen > (digestBuffer.length - ofs)) {
ofs = Integer.MAX_VALUE;
} else {
input.get(digestBuffer, ofs, inputLen);
......
......@@ -219,6 +219,7 @@ public class Resources extends java.util.ListResourceBundle {
{"Error.", "Error: "},
{"...Signer", ">>> Signer"},
{"...TSA", ">>> TSA"},
{"trusted.certificate", "trusted certificate"},
{"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.",
"This jar contains unsigned entries which have not been integrity-checked. "},
{"This.jar.contains.entries.whose.signer.certificate.has.expired.",
......@@ -235,8 +236,16 @@ public class Resources extends java.util.ListResourceBundle {
"Re-run with the -verbose and -certs options for more details."},
{"The.signer.certificate.has.expired.",
"The signer certificate has expired."},
{"The.timestamp.expired.1.but.usable.2",
"The timestamp expired on %1$tY-%1$tm-%1$td. However, the JAR will be valid until the signer certificate expires on %2$tY-%2$tm-%2$td."},
{"The.timestamp.has.expired.",
"The timestamp has expired."},
{"The.signer.certificate.will.expire.within.six.months.",
"The signer certificate will expire within six months."},
{"The.timestamp.will.expire.within.one.year.on.1",
"The timestamp will expire within one year on %1$tY-%1$tm-%1$td."},
{"The.timestamp.will.expire.within.one.year.on.1.but.2",
"The timestamp will expire within one year on %1$tY-%1$tm-%1$td. However, the JAR will be valid until the signer certificate expires on %2$tY-%2$tm-%2$td."},
{"The.signer.certificate.is.not.yet.valid.",
"The signer certificate is not yet valid."},
{"The.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing.",
......@@ -267,10 +276,18 @@ public class Resources extends java.util.ListResourceBundle {
"This jar contains entries whose TSA certificate chain is invalid. Reason: %s"},
{"no.timestamp.signing",
"No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (%1$tY-%1$tm-%1$td) or after any future revocation date."},
{"invalid.timestamp.signing",
"The timestamp is invalid. Without a valid timestamp, users may not be able to validate this jar after the signer certificate's expiration date (%1$tY-%1$tm-%1$td)."},
{"no.timestamp.verifying",
"This jar contains signatures that does not include a timestamp. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (%1$tY-%1$tm-%1$td) or after any future revocation date."},
"This jar contains signatures that do not include a timestamp. Without a timestamp, users may not be able to validate this jar after any of the signer certificates expire (as early as %1$tY-%1$tm-%1$td)."},
{"bad.timestamp.verifying",
"This jar contains signatures that include an invalid timestamp. Without a valid timestamp, users may not be able to validate this jar after any of the signer certificates expire (as early as %1$tY-%1$tm-%1$td).\nRerun jarsigner with -J-Djava.security.debug=jar for more information."},
{"The.signer.certificate.will.expire.on.1.",
"The signer certificate will expire on %1$tY-%1$tm-%1$td."},
{"The.timestamp.will.expire.on.1.",
"The timestamp will expire on %1$tY-%1$tm-%1$td."},
{"signer.cert.expired.1.but.timestamp.good.2.",
"The signer certificate expired on %1$tY-%1$tm-%1$td. However, the JAR will be valid until the timestamp expires on %2$tY-%2$tm-%2$td."},
{"Unknown.password.type.", "Unknown password type: "},
{"Cannot.find.environment.variable.",
"Cannot find environment variable: "},
......
############################################################
# Default Networking Configuration File
# Default Networking Configuration File
#
# This file may contain default values for the networking system properties.
# These values are only used when the system properties are not specified
......@@ -14,7 +14,7 @@
# Note that the system properties that do explicitely set proxies
# (like http.proxyHost) do take precedence over the system settings
# even if java.net.useSystemProxies is set to true.
java.net.useSystemProxies=false
#------------------------------------------------------------------------
......@@ -66,8 +66,8 @@ ftp.nonProxyHosts=localhost|127.*|[::1]
# socksProxyPort=1080
#
# HTTP Keep Alive settings. remainingData is the maximum amount of data
# in kilobytes that will be cleaned off the underlying socket so that it
# can be reused (default value is 512K), queuedConnections is the maximum
# in kilobytes that will be cleaned off the underlying socket so that it
# can be reused (default value is 512K), queuedConnections is the maximum
# number of Keep Alive connections to be on the queue for clean up (default
# value is 10).
# http.KeepAlive.remainingData=512
......@@ -99,3 +99,23 @@ ftp.nonProxyHosts=localhost|127.*|[::1]
#jdk.http.auth.proxying.disabledSchemes=
jdk.http.auth.tunneling.disabledSchemes=Basic
#
# Transparent NTLM HTTP authentication mode on Windows. Transparent authentication
# can be used for the NTLM scheme, where the security credentials based on the
# currently logged in user's name and password can be obtained directly from the
# operating system, without prompting the user. This property has three possible
# values which regulate the behavior as shown below. Other unrecognized values
# are handled the same as 'disabled'. Note, that NTLM is not considered to be a
# strongly secure authentication scheme and care should be taken before enabling
# this mechanism.
#
# Transparent authentication never used.
#jdk.http.ntlm.transparentAuth=disabled
#
# Enabled for all hosts.
#jdk.http.ntlm.transparentAuth=allHosts
#
# Enabled for hosts that are trusted in Windows Internet settings
#jdk.http.ntlm.transparentAuth=trustedHosts
#
jdk.http.ntlm.transparentAuth=disabled
......@@ -406,6 +406,9 @@ alloc_sarray (j_common_ptr cinfo, int pool_id,
JDIMENSION rowsperchunk, currow, i;
long ltemp;
if (samplesperrow == 0) {
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
}
/* Calculate max # of rows allowed in one allocation chunk */
ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
((long) samplesperrow * SIZEOF(JSAMPLE));
......@@ -454,6 +457,10 @@ alloc_barray (j_common_ptr cinfo, int pool_id,
JDIMENSION rowsperchunk, currow, i;
long ltemp;
if (blocksperrow == 0) {
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
}
/* Calculate max # of rows allowed in one allocation chunk */
ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
((long) blocksperrow * SIZEOF(JBLOCK));
......
......@@ -1535,10 +1535,16 @@ void AllocateDataSet(cmsIT8* it8)
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));
if (t->Data == NULL) {
if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)
{
SynError(it8, "AllocateDataSet: too much data");
}
else {
t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
}
}
......
......@@ -90,10 +90,13 @@ public class NTLMAuthentication extends AuthenticationInfo {
/**
* Returns true if the given site is trusted, i.e. we can try
* transparent Authentication.
* transparent Authentication. Shouldn't be called since
* capability not supported on Unix
*/
public static boolean isTrustedSite(URL url) {
return NTLMAuthCallback.isTrustedSite(url);
if (NTLMAuthCallback != null)
return NTLMAuthCallback.isTrustedSite(url);
return false;
}
private void init0() {
......
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2018 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
......@@ -23,6 +23,7 @@
* questions.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
......@@ -50,6 +51,10 @@ char* basePath(const char* path) {
} else {
int len = last - path;
char* str = (char*)malloc(len+1);
if (str == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
if (len > 0) {
memcpy(str, path, len);
}
......@@ -80,6 +85,10 @@ static char* normalizePath(const char* pathname, int len, int off) {
if (n == 0) return strdup("/");
sb = (char*)malloc(strlen(pathname)+1);
if (sb == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
sbLen = 0;
if (off > 0) {
......@@ -128,6 +137,10 @@ char* resolve(const char* parent, const char* child) {
len = parentEnd + cn - childStart;
if (child[0] == slash) {
theChars = (char*)malloc(len+1);
if (theChars == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
if (parentEnd > 0)
memcpy(theChars, parent, parentEnd);
if (cn > 0)
......@@ -135,6 +148,10 @@ char* resolve(const char* parent, const char* child) {
theChars[len] = '\0';
} else {
theChars = (char*)malloc(len+2);
if (theChars == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
if (parentEnd > 0)
memcpy(theChars, parent, parentEnd);
theChars[parentEnd] = slash;
......@@ -150,10 +167,13 @@ char* fromURIPath(const char* path) {
if (len > 1 && path[len-1] == slash) {
// "/foo/" --> "/foo", but "/" --> "/"
char* str = (char*)malloc(len);
if (str != NULL) {
memcpy(str, path, len-1);
str[len-1] = '\0';
if (str == NULL)
{
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
memcpy(str, path, len-1);
str[len-1] = '\0';
return str;
} else {
return (char*)path;
......
......@@ -608,6 +608,8 @@ static void initLoopbackRoutes() {
if (loRoutesTemp == 0) {
free(loRoutes);
loRoutes = NULL;
nRoutes = 0;
fclose (f);
return;
}
......
......@@ -184,6 +184,7 @@ Java_sun_awt_UNIXToolkit_load_1stock_1icon(JNIEnv *env, jobject this,
detail_str = (char *)SAFE_SIZE_ARRAY_ALLOC(malloc,
sizeof(char), len + 1);
if (detail_str == NULL) {
free(stock_id_str);
JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
return JNI_FALSE;
}
......
......@@ -30,6 +30,7 @@ import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.UnknownHostException;
import java.net.URL;
import sun.net.NetProperties;
import sun.net.www.HeaderParser;
import sun.net.www.protocol.http.AuthenticationInfo;
import sun.net.www.protocol.http.AuthScheme;
......@@ -52,6 +53,14 @@ public class NTLMAuthentication extends AuthenticationInfo {
private static String defaultDomain; /* Domain to use if not specified by user */
private static final boolean ntlmCache; /* Whether cache is enabled for NTLM */
enum TransparentAuth {
DISABLED, // disable for all hosts (default)
TRUSTED_HOSTS, // use Windows trusted hosts settings
ALL_HOSTS // attempt for all hosts
}
private static final TransparentAuth authMode;
static {
defaultDomain = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("http.auth.ntlm.domain",
......@@ -59,6 +68,19 @@ public class NTLMAuthentication extends AuthenticationInfo {
String ntlmCacheProp = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("jdk.ntlm.cache", "true"));
ntlmCache = Boolean.parseBoolean(ntlmCacheProp);
String modeProp = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<String>() {
public String run() {
return NetProperties.get("jdk.http.ntlm.transparentAuth");
}
});
if ("trustedHosts".equalsIgnoreCase(modeProp))
authMode = TransparentAuth.TRUSTED_HOSTS;
else if ("allHosts".equalsIgnoreCase(modeProp))
authMode = TransparentAuth.ALL_HOSTS;
else
authMode = TransparentAuth.DISABLED;
};
private void init0() {
......@@ -159,9 +181,21 @@ public class NTLMAuthentication extends AuthenticationInfo {
* transparent Authentication.
*/
public static boolean isTrustedSite(URL url) {
return NTLMAuthCallback.isTrustedSite(url);
if (NTLMAuthCallback != null)
return NTLMAuthCallback.isTrustedSite(url);
switch (authMode) {
case TRUSTED_HOSTS:
return isTrustedSite(url.toString());
case ALL_HOSTS:
return true;
default:
return false;
}
}
static native boolean isTrustedSite(String url);
/**
* Not supported. Must use the setHeaders() method
*/
......@@ -211,5 +245,4 @@ public class NTLMAuthentication extends AuthenticationInfo {
return false;
}
}
}
......@@ -753,6 +753,7 @@ abstract class KeyStore extends KeyStoreSpi {
/**
* Generates a certificate chain from the collection of
* certificates and stores the result into a key entry.
* This method is called by native code in libsunmscapi.
*/
private void generateCertificateChain(String alias,
Collection<? extends Certificate> certCollection)
......@@ -775,13 +776,15 @@ abstract class KeyStore extends KeyStoreSpi {
catch (Throwable e)
{
// Ignore the exception and skip this entry
// TODO - throw CertificateException?
// If e is thrown, remember to deal with it in
// native code.
}
}
/**
* Generates RSA key and certificate chain from the private key handle,
* collection of certificates and stores the result into key entries.
* This method is called by native code in libsunmscapi.
*/
private void generateRSAKeyAndCertificateChain(String alias,
long hCryptProv, long hCryptKey, int keyLength,
......@@ -807,12 +810,14 @@ abstract class KeyStore extends KeyStoreSpi {
catch (Throwable e)
{
// Ignore the exception and skip this entry
// TODO - throw CertificateException?
// If e is thrown, remember to deal with it in
// native code.
}
}
/**
* Generates certificates from byte data and stores into cert collection.
* This method is called by native code in libsunmscapi.
*
* @param data Byte data.
* @param certCollection Collection of certificates.
......@@ -836,12 +841,14 @@ abstract class KeyStore extends KeyStoreSpi {
catch (CertificateException e)
{
// Ignore the exception and skip this certificate
// TODO - throw CertificateException?
// If e is thrown, remember to deal with it in
// native code.
}
catch (Throwable te)
{
// Ignore the exception and skip this certificate
// TODO - throw CertificateException?
// If e is thrown, remember to deal with it in
// native code.
}
}
......
/*
* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2018, 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
......@@ -132,7 +132,7 @@ abstract class RSASignature extends java.security.SignatureSpi
@Override
protected void engineUpdate(byte[] b, int off, int len)
throws SignatureException {
if (offset + len > precomputedDigest.length) {
if (len > (precomputedDigest.length - offset)) {
offset = RAW_RSA_MAX + 1;
return;
}
......@@ -147,7 +147,7 @@ abstract class RSASignature extends java.security.SignatureSpi
if (len <= 0) {
return;
}
if (offset + len > precomputedDigest.length) {
if (len > (precomputedDigest.length - offset)) {
offset = RAW_RSA_MAX + 1;
return;
}
......
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2018 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
......@@ -23,6 +23,7 @@
* questions.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
......@@ -66,6 +67,10 @@ char* basePath(const char* path) {
} else {
int len = (int)(last - path);
char* str = (char*)malloc(len+1);
if (str == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
if (len > 0) {
memcpy(str, path, len);
}
......@@ -135,6 +140,10 @@ static char* normalizePath(const char* path, int len, int off) {
if (off < 3) off = 0; /* Avoid fencepost cases with UNC pathnames */
sb = (char*)malloc(len+1);
if (sb == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
sbLen = 0;
if (off == 0) {
......@@ -261,11 +270,19 @@ char* resolve(const char* parent, const char* child) {
if (child[childStart] == slash) {
theChars = (char*)malloc(len+1);
if (theChars == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
memcpy(theChars, parent, parentEnd);
memcpy(theChars+parentEnd, child+childStart, (cn-childStart));
theChars[len] = '\0';
} else {
theChars = (char*)malloc(len+2);
if (theChars == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
memcpy(theChars, parent, parentEnd);
theChars[parentEnd] = slash;
memcpy(theChars+parentEnd+1, child+childStart, (cn-childStart));
......@@ -320,10 +337,12 @@ char* fromURIPath(const char* path) {
return (char*)path;
} else {
char* p = (char*)malloc(len+1);
if (p != NULL) {
memcpy(p, path+start, len);
p[len] = '\0';
if (p == NULL) {
fprintf(stderr, "OOM error in native tmp buffer allocation");
return NULL;
}
memcpy(p, path+start, len);
p[len] = '\0';
return p;
}
}
......@@ -279,7 +279,7 @@ int enumInterfaces(JNIEnv *env, netif **netifPP)
// But in rare case it fails, we allow 'char' to be displayed
curr->displayName = (char *)malloc(ifrowP->dwDescrLen + 1);
} else {
curr->displayName = (wchar_t *)malloc(wlen*(sizeof(wchar_t))+1);
curr->displayName = (wchar_t *)malloc((wlen+1)*sizeof(wchar_t));
}
curr->name = (char *)malloc(strlen(dev_name) + 1);
......@@ -322,7 +322,7 @@ int enumInterfaces(JNIEnv *env, netif **netifPP)
free(curr);
return -1;
} else {
curr->displayName[wlen*(sizeof(wchar_t))] = '\0';
((wchar_t *)curr->displayName)[wlen] = L'\0';
curr->dNameIsUnicode = TRUE;
}
}
......@@ -861,6 +861,7 @@ JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
/* allocate a NetworkInterface array */
netIFArr = (*env)->NewObjectArray(env, count, cls, NULL);
if (netIFArr == NULL) {
free_netif(ifList);
return NULL;
}
......@@ -875,6 +876,7 @@ JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
netifObj = createNetworkInterface(env, curr, -1, NULL);
if (netifObj == NULL) {
free_netif(ifList);
return NULL;
}
......
......@@ -32,6 +32,7 @@
#include "AccessBridgePackages.h" // for debugging only
#include <windows.h>
#include <malloc.h>
#include <new>
DEBUG_CODE(extern HWND theDialogWindow);
extern "C" {
......@@ -46,6 +47,9 @@ AccessBridgeQueueElement::AccessBridgeQueueElement(char *buf, int size) {
next = (AccessBridgeQueueElement *) 0;
previous = (AccessBridgeQueueElement *) 0;
buffer = (char *) malloc(bufsize);
if (buffer == NULL) {
throw std::bad_alloc();
}
memcpy(buffer, buf, bufsize);
}
......
/*
* Copyright (c) 2018, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
#include <jni.h>
#include <windows.h>
#include "jni_util.h"
#include <urlmon.h>
JNIEXPORT jboolean JNICALL Java_sun_net_www_protocol_http_ntlm_NTLMAuthentication_isTrustedSite(JNIEnv *env, jclass clazz, jstring url )
{
HRESULT hr;
DWORD dwZone;
DWORD pPolicy = 0;
IInternetSecurityManager *spSecurityManager;
jboolean ret;
LPCWSTR bstrURL;
// Create IInternetSecurityManager
hr = CoInternetCreateSecurityManager(NULL, &spSecurityManager, (DWORD)0);
if (FAILED(hr)) {
return JNI_FALSE;
}
bstrURL = (LPCWSTR)((*env)->GetStringChars(env, url, NULL));
if (bstrURL == NULL) {
if (!(*env)->ExceptionCheck(env))
JNU_ThrowOutOfMemoryError(env, NULL);
spSecurityManager->lpVtbl->Release(spSecurityManager);
return JNI_FALSE;
}
// Determines the policy for the URLACTION_CREDENTIALS_USE action and display
// a user interface, if the policy indicates that the user should be queried
hr = spSecurityManager->lpVtbl->ProcessUrlAction(
spSecurityManager,
bstrURL,
URLACTION_CREDENTIALS_USE,
(LPBYTE)&pPolicy,
sizeof(DWORD), 0, 0, 0, 0);
if (FAILED(hr)) {
ret = JNI_FALSE;
goto cleanupAndReturn;
}
// If these two User Authentication Logon options is selected
// Anonymous logon
// Prompt for user name and password
if (pPolicy == URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY ||
pPolicy == URLPOLICY_CREDENTIALS_MUST_PROMPT_USER) {
ret = JNI_FALSE;
goto cleanupAndReturn;
}
// Option "Automatic logon with current user name and password" is selected
if (pPolicy == URLPOLICY_CREDENTIALS_SILENT_LOGON_OK) {
ret = JNI_TRUE;
goto cleanupAndReturn;
}
// Option "Automatic logon only in intranet zone" is selected
if (pPolicy == URLPOLICY_CREDENTIALS_CONDITIONAL_PROMPT) {
// Gets the zone index from the specified URL
hr = spSecurityManager->lpVtbl->MapUrlToZone(
spSecurityManager, bstrURL, &dwZone, 0);
if (FAILED(hr)) {
ret = JNI_FALSE;
goto cleanupAndReturn;
}
// Check if the URL is in Local or Intranet zone
if (dwZone == URLZONE_INTRANET || dwZone == URLZONE_LOCAL_MACHINE) {
ret = JNI_TRUE;
goto cleanupAndReturn;
}
}
ret = JNI_FALSE;
cleanupAndReturn:
(*env)->ReleaseStringChars(env, url, bstrURL);
spSecurityManager->lpVtbl->Release(spSecurityManager);
return ret;
}
/*
* Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2018, 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
......@@ -95,6 +95,10 @@ Java_sun_nio_ch_DatagramDispatcher_readv0(JNIEnv *env, jclass clazz,
jint fd = fdval(env, fdo);
struct iovec *iovp = (struct iovec *)address;
WSABUF *bufs = malloc(len * sizeof(WSABUF));
if (bufs == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return IOS_THROWN;
}
/* copy iovec into WSABUF */
for(i=0; i<len; i++) {
......@@ -182,6 +186,10 @@ Java_sun_nio_ch_DatagramDispatcher_writev0(JNIEnv *env, jclass clazz,
jint fd = fdval(env, fdo);
struct iovec *iovp = (struct iovec *)address;
WSABUF *bufs = malloc(len * sizeof(WSABUF));
if (bufs == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return IOS_THROWN;
}
/* copy iovec into WSABUF */
for(i=0; i<len; i++) {
......
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2018, 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
......@@ -208,6 +208,10 @@ Java_sun_nio_ch_WindowsSelectorImpl_resetWakeupSocket0(JNIEnv *env, jclass this,
/* Prepare corresponding buffer if needed, and then read */
if (bytesToRead > WAKEUP_SOCKET_BUF_SIZE) {
char* buf = (char*)malloc(bytesToRead);
if (buf == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return;
}
recv(scinFd, buf, bytesToRead, 0);
free(buf);
} else {
......
......@@ -76,7 +76,8 @@ BOOL native_debug = 0;
BOOL PackageConnectLookup(PHANDLE,PULONG);
NTSTATUS ConstructTicketRequest(UNICODE_STRING DomainName,
NTSTATUS ConstructTicketRequest(JNIEnv *env,
UNICODE_STRING DomainName,
PKERB_RETRIEVE_TKT_REQUEST *outRequest,
ULONG *outSize);
......@@ -102,6 +103,8 @@ jobject BuildEncryptionKey(JNIEnv *env, PKERB_CRYPTO_KEY cryptoKey);
jobject BuildTicketFlags(JNIEnv *env, PULONG flags);
jobject BuildKerberosTime(JNIEnv *env, PLARGE_INTEGER kerbtime);
void ThrowOOME(JNIEnv *env, const char *szMessage);
/*
* Class: sun_security_krb5_KrbCreds
* Method: JNI_OnLoad
......@@ -495,7 +498,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_krb5_Credentials_acquireDefaultNativ
}
// use domain to request Ticket
Status = ConstructTicketRequest(msticket->TargetDomainName,
Status = ConstructTicketRequest(env, msticket->TargetDomainName,
&pTicketRequest, &requestSize);
if (!LSA_SUCCESS(Status)) {
ShowNTError("ConstructTicketRequest status", Status);
......@@ -689,7 +692,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_krb5_Credentials_acquireDefaultNativ
}
static NTSTATUS
ConstructTicketRequest(UNICODE_STRING DomainName,
ConstructTicketRequest(JNIEnv *env, UNICODE_STRING DomainName,
PKERB_RETRIEVE_TKT_REQUEST *outRequest, ULONG *outSize)
{
NTSTATUS Status;
......@@ -736,8 +739,10 @@ ConstructTicketRequest(UNICODE_STRING DomainName,
pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST)
LocalAlloc(LMEM_ZEROINIT, RequestSize);
if (!pTicketRequest)
if (!pTicketRequest) {
ThrowOOME(env, "Can't allocate memory for ticket");
return GetLastError();
}
//
// Concatenate the target prefix with the previous response's
......@@ -894,7 +899,7 @@ jobject BuildTicket(JNIEnv *env, PUCHAR encodedTicket, ULONG encodedTicketSize)
jbyteArray ary;
ary = (*env)->NewByteArray(env,encodedTicketSize);
if ((*env)->ExceptionOccurred(env)) {
if (ary == NULL) {
return (jobject) NULL;
}
......@@ -940,6 +945,10 @@ jobject BuildPrincipal(JNIEnv *env, PKERB_EXTERNAL_NAME principalName,
realm = (WCHAR *) LocalAlloc(LMEM_ZEROINIT,
((domainName.Length)*sizeof(WCHAR) + sizeof(UNICODE_NULL)));
if (realm == NULL) {
ThrowOOME(env, "Can't allocate memory for realm");
return NULL;
}
wcsncpy(realm, domainName.Buffer, domainName.Length/sizeof(WCHAR));
if (native_debug) {
......@@ -1014,6 +1023,9 @@ jobject BuildEncryptionKey(JNIEnv *env, PKERB_CRYPTO_KEY cryptoKey) {
}
ary = (*env)->NewByteArray(env,cryptoKey->Length);
if (ary == NULL) {
return (jobject) NULL;
}
(*env)->SetByteArrayRegion(env, ary, (jsize) 0, cryptoKey->Length,
(jbyte *)cryptoKey->Value);
if ((*env)->ExceptionOccurred(env)) {
......@@ -1036,6 +1048,9 @@ jobject BuildTicketFlags(JNIEnv *env, PULONG flags) {
ULONG nlflags = htonl(*flags);
ary = (*env)->NewByteArray(env, sizeof(*flags));
if (ary == NULL) {
return (jobject) NULL;
}
(*env)->SetByteArrayRegion(env, ary, (jsize) 0, sizeof(*flags),
(jbyte *)&nlflags);
if ((*env)->ExceptionOccurred(env)) {
......@@ -1088,3 +1103,10 @@ jobject BuildKerberosTime(JNIEnv *env, PLARGE_INTEGER kerbtime) {
}
return kerberosTime;
}
void ThrowOOME(JNIEnv *env, const char *szMessage) {
jclass exceptionClazz = (*env)->FindClass(env, "java/lang/OutOfMemoryError");
if (exceptionClazz != NULL) {
(*env)->ThrowNew(env, exceptionClazz, szMessage);
}
}
......@@ -425,6 +425,15 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh
// Create ArrayList to store certs in each chain
jobject jArrayList =
env->NewObject(clazzArrayList, mNewArrayList);
if (jArrayList == NULL) {
__leave;
}
// Cleanup the previous allocated name
if (pszNameString) {
delete [] pszNameString;
pszNameString = NULL;
}
for (unsigned int j=0; j < rgpChain->cElement; j++)
{
......@@ -463,6 +472,9 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh
// Allocate and populate byte array
jbyteArray byteArray = env->NewByteArray(cbCertEncoded);
if (byteArray == NULL) {
__leave;
}
env->SetByteArrayRegion(byteArray, 0, cbCertEncoded,
(jbyte*) pbCertEncoded);
......@@ -471,30 +483,44 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh
env->CallVoidMethod(obj, mGenCert, byteArray, jArrayList);
}
if (bHasNoPrivateKey)
{
// Generate certificate chain and store into cert chain
// collection
env->CallVoidMethod(obj, mGenCertChain,
env->NewStringUTF(pszNameString),
jArrayList);
}
else
// Usually pszNameString should be non-NULL. It's either
// the friendly name or an element from the subject name
// or SAN.
if (pszNameString)
{
// Determine key type: RSA or DSA
DWORD dwData = CALG_RSA_KEYX;
DWORD dwSize = sizeof(DWORD);
::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData,
&dwSize, NULL);
if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA)
if (bHasNoPrivateKey)
{
// Generate RSA certificate chain and store into cert
// chain collection
env->CallVoidMethod(obj, mGenRSAKeyAndCertChain,
env->NewStringUTF(pszNameString),
(jlong) hCryptProv, (jlong) hUserKey,
dwPublicKeyLength, jArrayList);
// Generate certificate chain and store into cert chain
// collection
jstring name = env->NewStringUTF(pszNameString);
if (name == NULL) {
__leave;
}
env->CallVoidMethod(obj, mGenCertChain,
name,
jArrayList);
}
else
{
// Determine key type: RSA or DSA
DWORD dwData = CALG_RSA_KEYX;
DWORD dwSize = sizeof(DWORD);
::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData,
&dwSize, NULL);
if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA)
{
// Generate RSA certificate chain and store into cert
// chain collection
jstring name = env->NewStringUTF(pszNameString);
if (name == NULL) {
__leave;
}
env->CallVoidMethod(obj, mGenRSAKeyAndCertChain,
name,
(jlong) hCryptProv, (jlong) hUserKey,
dwPublicKeyLength, jArrayList);
}
}
}
}
......@@ -641,6 +667,9 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash
// Create new byte array
jbyteArray temp = env->NewByteArray(dwBufLen);
if (temp == NULL) {
__leave;
}
// Copy data from native buffer
env->SetByteArrayRegion(temp, 0, dwBufLen, pSignedHashBuffer);
......@@ -964,6 +993,9 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate
}
jCertAliasChars = env->GetStringChars(jCertAliasName, NULL);
if (jCertAliasChars == NULL) {
__leave;
}
memcpy(pszCertAliasName, jCertAliasChars, size * sizeof(WCHAR));
pszCertAliasName[size] = 0; // append the string terminator
......@@ -1600,7 +1632,9 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSACipher_encryptDecrypt
}
// Create new byte array
result = env->NewByteArray(dwBufLen);
if ((result = env->NewByteArray(dwBufLen)) == NULL) {
__leave;
}
// Copy data from native buffer to Java buffer
env->SetByteArrayRegion(result, 0, dwBufLen, (jbyte*) pData);
......@@ -1651,7 +1685,9 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getPublicKeyB
}
// Create new byte array
blob = env->NewByteArray(dwBlobLen);
if ((blob = env->NewByteArray(dwBlobLen)) == NULL) {
__leave;
}
// Copy data from native buffer to Java buffer
env->SetByteArrayRegion(blob, 0, dwBlobLen, (jbyte*) pbKeyBlob);
......@@ -1680,6 +1716,13 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getExponent
__try {
jsize length = env->GetArrayLength(jKeyBlob);
jsize headerLength = sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY);
if (length < headerLength) {
ThrowExceptionWithMessage(env, KEY_EXCEPTION, "Invalid BLOB");
__leave;
}
if ((keyBlob = env->GetByteArrayElements(jKeyBlob, 0)) == NULL) {
__leave;
}
......@@ -1706,7 +1749,9 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getExponent
exponentBytes[i] = ((BYTE*) &pRsaPubKey->pubexp)[j];
}
exponent = env->NewByteArray(len);
if ((exponent = env->NewByteArray(len)) == NULL) {
__leave;
}
env->SetByteArrayRegion(exponent, 0, len, exponentBytes);
}
__finally
......@@ -1736,6 +1781,13 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getModulus
__try {
jsize length = env->GetArrayLength(jKeyBlob);
jsize headerLength = sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY);
if (length < headerLength) {
ThrowExceptionWithMessage(env, KEY_EXCEPTION, "Invalid BLOB");
__leave;
}
if ((keyBlob = env->GetByteArrayElements(jKeyBlob, 0)) == NULL) {
__leave;
}
......@@ -1752,19 +1804,25 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getModulus
(RSAPUBKEY *) (keyBlob + sizeof(PUBLICKEYSTRUC));
int len = pRsaPubKey->bitlen / 8;
if (len < 0 || len > length - headerLength) {
ThrowExceptionWithMessage(env, KEY_EXCEPTION, "Invalid key length");
__leave;
}
modulusBytes = new (env) jbyte[len];
if (modulusBytes == NULL) {
__leave;
}
BYTE * pbModulus =
(BYTE *) (keyBlob + sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY));
BYTE * pbModulus = (BYTE *) (keyBlob + headerLength);
// convert from little-endian while copying from blob
for (int i = 0, j = len - 1; i < len; i++, j--) {
modulusBytes[i] = pbModulus[j];
}
modulus = env->NewByteArray(len);
if ((modulus = env->NewByteArray(len)) == NULL) {
__leave;
}
env->SetByteArrayRegion(modulus, 0, len, modulusBytes);
}
__finally
......@@ -1972,7 +2030,9 @@ jbyteArray generateKeyBlob(
}
}
jBlob = env->NewByteArray(jBlobLength);
if ((jBlob = env->NewByteArray(jBlobLength)) == NULL) {
__leave;
}
env->SetByteArrayRegion(jBlob, 0, jBlobLength, jBlobBytes);
}
......
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
......@@ -75,18 +75,20 @@
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_connect
(JNIEnv *env, jobject obj, jstring jPkcs11ModulePath, jstring jGetFunctionList)
(JNIEnv *env, jobject obj, jstring jPkcs11ModulePath,
jstring jGetFunctionList)
{
HINSTANCE hModule;
CK_C_GetFunctionList C_GetFunctionList;
CK_RV rv;
CK_RV rv = CK_ASSERT_OK;
ModuleData *moduleData;
jobject globalPKCS11ImplementationReference;
LPVOID lpMsgBuf;
char *exceptionMessage;
LPVOID lpMsgBuf = NULL;
char *exceptionMessage = NULL;
const char *getFunctionListStr;
const char *libraryNameStr = (*env)->GetStringUTFChars(env, jPkcs11ModulePath, 0);
const char *libraryNameStr = (*env)->GetStringUTFChars(env,
jPkcs11ModulePath, 0);
TRACE1("DEBUG: connect to PKCS#11 module: %s ... ", libraryNameStr);
......@@ -106,21 +108,24 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_connect
0,
NULL
);
exceptionMessage = (char *) malloc(sizeof(char) * (strlen((LPTSTR) lpMsgBuf) + strlen(libraryNameStr) + 1));
exceptionMessage = (char *) malloc(sizeof(char) *
(strlen((LPTSTR) lpMsgBuf) + strlen(libraryNameStr) + 1));
if (exceptionMessage == NULL) {
throwOutOfMemoryError(env, 0);
goto cleanup;
}
strcpy(exceptionMessage, (LPTSTR) lpMsgBuf);
strcat(exceptionMessage, libraryNameStr);
throwIOException(env, (LPTSTR) exceptionMessage);
/* Free the buffer. */
free(exceptionMessage);
LocalFree(lpMsgBuf);
return;
goto cleanup;
}
/*
* Get function pointer to C_GetFunctionList
*/
getFunctionListStr = (*env)->GetStringUTFChars(env, jGetFunctionList, 0);
C_GetFunctionList = (CK_C_GetFunctionList) GetProcAddress(hModule, getFunctionListStr);
C_GetFunctionList = (CK_C_GetFunctionList) GetProcAddress(hModule,
getFunctionListStr);
(*env)->ReleaseStringUTFChars(env, jGetFunctionList, getFunctionListStr);
if (C_GetFunctionList == NULL) {
FormatMessage(
......@@ -135,24 +140,37 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_connect
NULL
);
throwIOException(env, (LPTSTR) lpMsgBuf);
/* Free the buffer. */
LocalFree( lpMsgBuf );
return;
goto cleanup;
}
/*
* Get function pointers to all PKCS #11 functions
*/
moduleData = (ModuleData *) malloc(sizeof(ModuleData));
if (moduleData == NULL) {
throwOutOfMemoryError(env, 0);
goto cleanup;
}
moduleData->hModule = hModule;
moduleData->applicationMutexHandler = NULL;
rv = (C_GetFunctionList)(&(moduleData->ckFunctionListPtr));
globalPKCS11ImplementationReference = (*env)->NewGlobalRef(env, obj);
putModuleEntry(env, globalPKCS11ImplementationReference, moduleData);
(*env)->ReleaseStringUTFChars(env, jPkcs11ModulePath, libraryNameStr);
TRACE0("FINISHED\n");
cleanup:
/* Free up allocated buffers we no longer need */
if (lpMsgBuf != NULL) {
LocalFree( lpMsgBuf );
}
if (libraryNameStr != NULL) {
(*env)->ReleaseStringUTFChars(env, jPkcs11ModulePath, libraryNameStr);
}
if (exceptionMessage != NULL) {
free(exceptionMessage);
}
if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
}
......
......@@ -886,10 +886,12 @@ Java_sun_print_Win32PrintService_getDefaultSettings(JNIEnv *env,
if (!present) {
defIndices[0] = papers[0];
}
if (papers != NULL) {
free((char*)papers);
}
}
// If DeviceCapabilities fails, then also free paper allocation
if (papers != NULL) {
free((char*)papers);
}
}
RESTORE_CONTROLWORD
}
......
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 2018, 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
......@@ -23,7 +23,7 @@
/*
* @test
* @bug 6362557
* @bug 6362557 8200698
* @summary Some tests of add(BigDecimal, mc)
* @author Joseph D. Darcy
*/
......@@ -290,12 +290,35 @@ public class AddTests {
return failures;
}
private static int arithmeticExceptionTest() {
int failures = 0;
BigDecimal x;
try {
//
// The string representation "1e2147483647", which is equivalent
// to 10^Integer.MAX_VALUE, is used to create an augend with an
// unscaled value of 1 and a scale of -Integer.MAX_VALUE. The
// addend "1" has an unscaled value of 1 with a scale of 0. The
// addition is performed exactly and is specified to have a
// preferred scale of max(-Integer.MAX_VALUE, 0). As the scale
// of the result is 0, a value with Integer.MAX_VALUE + 1 digits
// would need to be created. Therefore the next statement is
// expected to overflow with an ArithmeticException.
//
x = new BigDecimal("1e2147483647").add(new BigDecimal(1));
failures++;
} catch (ArithmeticException ae) {
}
return failures;
}
public static void main(String argv[]) {
int failures = 0;
failures += extremaTests();
failures += roundingGradationTests();
failures += precisionConsistencyTest();
failures += arithmeticExceptionTest();
if (failures > 0) {
throw new RuntimeException("Incurred " + failures +
......
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2018, 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
......@@ -23,20 +23,48 @@
/*
* @test
* @bug 4259453
* @summary Test string constructor of BigDecimal
* @bug 4259453 8200698
* @summary Test constructors of BigDecimal
* @library ..
* @run testng Constructor
*/
import java.math.BigDecimal;
import org.testng.annotations.Test;
public class Constructor {
public static void main(String[] args) throws Exception {
boolean nfe = false;
@Test(expectedExceptions=NumberFormatException.class)
public void stringConstructor() {
BigDecimal bd = new BigDecimal("1.2e");
}
@Test(expectedExceptions=NumberFormatException.class)
public void charArrayConstructorNegativeOffset() {
BigDecimal bd = new BigDecimal(new char[5], -1, 4, null);
}
@Test(expectedExceptions=NumberFormatException.class)
public void charArrayConstructorNegativeLength() {
BigDecimal bd = new BigDecimal(new char[5], 0, -1, null);
}
@Test(expectedExceptions=NumberFormatException.class)
public void charArrayConstructorIntegerOverflow() {
try {
BigDecimal bd = new BigDecimal("1.2e");
} catch (NumberFormatException e) {
nfe = true;
BigDecimal bd = new BigDecimal(new char[5], Integer.MAX_VALUE - 5,
6, null);
} catch (NumberFormatException nfe) {
if (nfe.getCause() instanceof IndexOutOfBoundsException) {
throw new RuntimeException
("NumberFormatException should not have a cause");
} else {
throw nfe;
}
}
if (!nfe)
throw new Exception("Didn't throw NumberFormatException");
}
@Test(expectedExceptions=NumberFormatException.class)
public void charArrayConstructorIndexOutOfBounds() {
BigDecimal bd = new BigDecimal(new char[5], 1, 5, null);
}
}
/*
* Copyright (c) 2018, 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 8200698
* @summary Tests that exceptions are thrown for ops which would overflow
* @requires (sun.arch.data.model == "64" & os.maxMemory > 4g)
* @run testng/othervm -Xmx4g LargeValueExceptions
*/
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
import org.testng.annotations.Test;
//
// The intent of this test is to probe the boundaries between overflow and
// non-overflow, principally for multiplication and squaring, specifically
// the largest values which should not overflow and the smallest values which
// should. The transition values used are not necessarily at the exact
// boundaries but should be "close." Quite a few different values were used
// experimentally before settling on the ones in this test. For multiplication
// and squaring all cases are exercised: definite overflow and non-overflow
// which can be detected "up front," and "indefinite" overflow, i.e., overflow
// which cannot be detected up front so further calculations are required.
//
// Testing negative values is unnecessary. For both multiplication and squaring
// the paths lead to the Toom-Cook algorithm where the signum is used only to
// determine the sign of the result and not in the intermediate calculations.
// This is also true for exponentiation.
//
// @Test annotations with optional element "enabled" set to "false" should
// succeed when "enabled" is set to "true" but they take too to run in the
// course of the typical regression test execution scenario.
//
public class LargeValueExceptions {
// BigInteger.MAX_MAG_LENGTH
private static final int MAX_INTS = 1 << 26;
// Number of bits corresponding to MAX_INTS
private static final long MAX_BITS = (0xffffffffL & MAX_INTS) << 5L;
// Half BigInteger.MAX_MAG_LENGTH
private static final int MAX_INTS_HALF = MAX_INTS / 2;
// --- squaring ---
// Largest no overflow determined by examining data lengths alone.
@Test(enabled=false)
public void squareNoOverflow() {
BigInteger x = ONE.shiftLeft(16*MAX_INTS - 1).subtract(ONE);
BigInteger y = x.multiply(x);
}
// Smallest no overflow determined by extra calculations.
@Test(enabled=false)
public void squareIndefiniteOverflowSuccess() {
BigInteger x = ONE.shiftLeft(16*MAX_INTS - 1);
BigInteger y = x.multiply(x);
}
// Largest overflow detected by extra calculations.
@Test(expectedExceptions=ArithmeticException.class,enabled=false)
public void squareIndefiniteOverflowFailure() {
BigInteger x = ONE.shiftLeft(16*MAX_INTS).subtract(ONE);
BigInteger y = x.multiply(x);
}
// Smallest overflow detected by examining data lengths alone.
@Test(expectedExceptions=ArithmeticException.class)
public void squareDefiniteOverflow() {
BigInteger x = ONE.shiftLeft(16*MAX_INTS);
BigInteger y = x.multiply(x);
}
// --- multiplication ---
// Largest no overflow determined by examining data lengths alone.
@Test(enabled=false)
public void multiplyNoOverflow() {
final int halfMaxBits = MAX_INTS_HALF << 5;
BigInteger x = ONE.shiftLeft(halfMaxBits).subtract(ONE);
BigInteger y = ONE.shiftLeft(halfMaxBits - 1).subtract(ONE);
BigInteger z = x.multiply(y);
}
// Smallest no overflow determined by extra calculations.
@Test(enabled=false)
public void multiplyIndefiniteOverflowSuccess() {
BigInteger x = ONE.shiftLeft((int)(MAX_BITS/2) - 1);
long m = MAX_BITS - x.bitLength();
BigInteger y = ONE.shiftLeft((int)(MAX_BITS/2) - 1);
long n = MAX_BITS - y.bitLength();
if (m + n != MAX_BITS) {
throw new RuntimeException("Unexpected leading zero sum");
}
BigInteger z = x.multiply(y);
}
// Largest overflow detected by extra calculations.
@Test(expectedExceptions=ArithmeticException.class,enabled=false)
public void multiplyIndefiniteOverflowFailure() {
BigInteger x = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE);
long m = MAX_BITS - x.bitLength();
BigInteger y = ONE.shiftLeft((int)(MAX_BITS/2)).subtract(ONE);
long n = MAX_BITS - y.bitLength();
if (m + n != MAX_BITS) {
throw new RuntimeException("Unexpected leading zero sum");
}
BigInteger z = x.multiply(y);
}
// Smallest overflow detected by examining data lengths alone.
@Test(expectedExceptions=ArithmeticException.class)
public void multiplyDefiniteOverflow() {
// multiply by 4 as MAX_INTS_HALF refers to ints
byte[] xmag = new byte[4*MAX_INTS_HALF];
xmag[0] = (byte)0xff;
BigInteger x = new BigInteger(1, xmag);
byte[] ymag = new byte[4*MAX_INTS_HALF + 1];
ymag[0] = (byte)0xff;
BigInteger y = new BigInteger(1, ymag);
BigInteger z = x.multiply(y);
}
// --- exponentiation ---
@Test(expectedExceptions=ArithmeticException.class)
public void powOverflow() {
BigInteger.TEN.pow(Integer.MAX_VALUE);
}
@Test(expectedExceptions=ArithmeticException.class)
public void powOverflow1() {
int shift = 20;
int exponent = 1 << shift;
BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent));
BigInteger y = x.pow(exponent);
}
@Test(expectedExceptions=ArithmeticException.class)
public void powOverflow2() {
int shift = 20;
int exponent = 1 << shift;
BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).add(ONE);
BigInteger y = x.pow(exponent);
}
@Test(expectedExceptions=ArithmeticException.class,enabled=false)
public void powOverflow3() {
int shift = 20;
int exponent = 1 << shift;
BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent)).subtract(ONE);
BigInteger y = x.pow(exponent);
}
@Test(enabled=false)
public void powOverflow4() {
int shift = 20;
int exponent = 1 << shift;
BigInteger x = ONE.shiftLeft((int)(MAX_BITS / exponent - 1)).add(ONE);
BigInteger y = x.pow(exponent);
}
}
/*
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2018, 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
......@@ -75,6 +75,7 @@ import jdk.testlibrary.Utils;
* java.base/sun.security.util
* java.base/sun.security.tools.keytool
* @library /lib/testlibrary
* @compile -XDignore.symbol.file TimestampCheck.java
* @run main/othervm/timeout=600 TimestampCheck
*/
public class TimestampCheck {
......@@ -121,12 +122,12 @@ public class TimestampCheck {
*/
byte[] sign(byte[] input, String path) throws Exception {
DerValue value = new DerValue(input);
System.out.println("\nIncoming Request\n===================");
System.out.println("Version: " + value.data.getInteger());
System.out.println("#\n# Incoming Request\n===================");
System.out.println("# Version: " + value.data.getInteger());
DerValue messageImprint = value.data.getDerValue();
AlgorithmId aid = AlgorithmId.parse(
messageImprint.data.getDerValue());
System.out.println("AlgorithmId: " + aid);
System.out.println("# AlgorithmId: " + aid);
ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId);
BigInteger nonce = null;
......@@ -134,16 +135,16 @@ public class TimestampCheck {
DerValue v = value.data.getDerValue();
if (v.tag == DerValue.tag_Integer) {
nonce = v.getBigInteger();
System.out.println("nonce: " + nonce);
System.out.println("# nonce: " + nonce);
} else if (v.tag == DerValue.tag_Boolean) {
System.out.println("certReq: " + v.getBoolean());
System.out.println("# certReq: " + v.getBoolean());
} else if (v.tag == DerValue.tag_ObjectId) {
policyId = v.getOID();
System.out.println("PolicyID: " + policyId);
System.out.println("# PolicyID: " + policyId);
}
}
System.out.println("\nResponse\n===================");
System.out.println("#\n# Response\n===================");
FileInputStream is = new FileInputStream(keystore);
KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(is, "changeit".toCharArray());
......@@ -229,10 +230,10 @@ public class TimestampCheck {
"1.2.840.113549.1.9.16.1.4"),
new DerValue(tstInfo2.toByteArray()));
System.out.println("Signing...");
System.out.println(new X500Name(signer
System.out.println("# Signing...");
System.out.println("# " + new X500Name(signer
.getIssuerX500Principal().getName()));
System.out.println(signer.getSerialNumber());
System.out.println("# " + signer.getSerialNumber());
SignerInfo signerInfo = new SignerInfo(
new X500Name(signer.getIssuerX500Principal().getName()),
......@@ -303,8 +304,6 @@ public class TimestampCheck {
public static void main(String[] args) throws Throwable {
prepare();
try (Handler tsa = Handler.init(0, "ks");) {
tsa.start();
int port = tsa.getPort();
......@@ -313,62 +312,99 @@ public class TimestampCheck {
if (args.length == 0) { // Run this test
prepare();
sign("normal")
.shouldNotContain("Warning")
.shouldContain("The signer certificate will expire on")
.shouldContain("The timestamp will expire on")
.shouldHaveExitValue(0);
verify("normal.jar")
.shouldNotContain("Warning")
.shouldHaveExitValue(0);
verify("normal.jar", "-verbose")
.shouldNotContain("Warning")
.shouldContain("The signer certificate will expire on")
.shouldContain("The timestamp will expire on")
.shouldHaveExitValue(0);
// Simulate signing at a previous date:
// 1. tsold will create a timestamp of 20 days ago.
// 2. oldsigner expired 10 days ago.
// jarsigner will show a warning at signing.
signVerbose("tsold", "unsigned.jar", "tsold.jar", "oldsigner")
.shouldHaveExitValue(4);
.shouldNotContain("Warning")
.shouldMatch("signer certificate expired on .*. "
+ "However, the JAR will be valid")
.shouldHaveExitValue(0);
// It verifies perfectly.
verify("tsold.jar", "-verbose", "-certs")
.shouldNotContain("Warning")
.shouldMatch("signer certificate expired on .*. "
+ "However, the JAR will be valid")
.shouldHaveExitValue(0);
// No timestamp
signVerbose(null, "unsigned.jar", "none.jar", "signer")
.shouldContain("is not timestamped")
.shouldContain("The signer certificate will expire on")
.shouldHaveExitValue(0);
verify("none.jar", "-verbose")
.shouldContain("do not include a timestamp")
.shouldContain("The signer certificate will expire on")
.shouldHaveExitValue(0);
// Error cases
signVerbose(null, "unsigned.jar", "badku.jar", "badku")
.shouldContain("KeyUsage extension doesn't allow code signing")
.shouldHaveExitValue(8);
checkBadKU("badku.jar");
// 8180289: unvalidated TSA cert chain
sign("tsnoca")
.shouldContain("TSA certificate chain is invalid")
.shouldContain("The TSA certificate chain is invalid. "
+ "Reason: Path does not chain with any of the trust anchors")
.shouldHaveExitValue(64);
verify("tsnoca.jar", "-verbose", "-certs")
.shouldHaveExitValue(64)
.shouldContain("jar verified")
.shouldContain("Invalid TSA certificate chain")
.shouldContain("TSA certificate chain is invalid");
.shouldContain("Invalid TSA certificate chain: "
+ "Path does not chain with any of the trust anchors")
.shouldContain("TSA certificate chain is invalid."
+ " Reason: Path does not chain with any of the trust anchors");
sign("nononce")
.shouldContain("Nonce missing in timestamp token")
.shouldHaveExitValue(1);
sign("diffnonce")
.shouldContain("Nonce changed in timestamp token")
.shouldHaveExitValue(1);
sign("baddigest")
.shouldContain("Digest octets changed in timestamp token")
.shouldHaveExitValue(1);
sign("diffalg")
.shouldContain("Digest algorithm not")
.shouldHaveExitValue(1);
sign("fullchain")
.shouldHaveExitValue(0); // Success, 6543440 solved.
sign("tsbad1")
.shouldContain("Certificate is not valid for timestamping")
.shouldHaveExitValue(1);
sign("tsbad2")
.shouldContain("Certificate is not valid for timestamping")
.shouldHaveExitValue(1);
sign("tsbad3")
.shouldContain("Certificate is not valid for timestamping")
.shouldHaveExitValue(1);
sign("nocert")
.shouldContain("Certificate not included in timestamp token")
.shouldHaveExitValue(1);
sign("policy", "-tsapolicyid", "1.2.3")
......@@ -376,6 +412,7 @@ public class TimestampCheck {
checkTimestamp("policy.jar", "1.2.3", "SHA-256");
sign("diffpolicy", "-tsapolicyid", "1.2.3")
.shouldContain("TSAPolicyID changed in timestamp token")
.shouldHaveExitValue(1);
sign("sha1alg", "-tsadigestalg", "SHA")
......@@ -384,11 +421,13 @@ public class TimestampCheck {
sign("tsweak", "-digestalg", "MD5",
"-sigalg", "MD5withRSA", "-tsadigestalg", "MD5")
.shouldHaveExitValue(68);
.shouldHaveExitValue(68)
.shouldContain("The timestamp is invalid. Without a valid timestamp");
checkWeak("tsweak.jar");
signVerbose("tsweak", "unsigned.jar", "tsweak2.jar", "signer")
.shouldHaveExitValue(64)
.shouldContain("The timestamp is invalid. Without a valid timestamp")
.shouldContain("TSA certificate chain is invalid");
// Weak timestamp is an error and jar treated unsigned
......@@ -397,19 +436,26 @@ public class TimestampCheck {
.shouldContain("treated as unsigned")
.shouldMatch("Timestamp.*512.*weak");
// Algorithm used in signing is weak
signVerbose("normal", "unsigned.jar", "halfWeak.jar", "signer",
"-digestalg", "MD5")
.shouldContain("-digestalg option is considered a security risk")
.shouldHaveExitValue(4);
checkHalfWeak("halfWeak.jar");
// sign with DSA key
signVerbose("normal", "unsigned.jar", "sign1.jar", "dsakey")
.shouldHaveExitValue(0);
// sign with RSAkeysize < 1024
signVerbose("normal", "sign1.jar", "sign2.jar", "weakkeysize")
.shouldContain("Algorithm constraints check failed on keysize")
.shouldHaveExitValue(4);
checkMultiple("sign2.jar");
// 8191438: jarsigner should print when a timestamp will expire
checkExpiration();
// When .SF or .RSA is missing or invalid
checkMissingOrInvalidFiles("normal.jar");
......@@ -417,12 +463,118 @@ public class TimestampCheck {
checkInvalidTsaCertKeyUsage();
}
} else { // Run as a standalone server
System.out.println("Press Enter to quit server");
System.out.println("TSA started at " + host
+ ". Press Enter to quit server");
System.in.read();
}
}
}
private static void checkExpiration() throws Exception {
// Warning when expired or expiring
signVerbose(null, "unsigned.jar", "expired.jar", "expired")
.shouldContain("signer certificate has expired")
.shouldHaveExitValue(4);
verify("expired.jar")
.shouldContain("signer certificate has expired")
.shouldHaveExitValue(4);
signVerbose(null, "unsigned.jar", "expiring.jar", "expiring")
.shouldContain("signer certificate will expire within")
.shouldHaveExitValue(0);
verify("expiring.jar")
.shouldContain("signer certificate will expire within")
.shouldHaveExitValue(0);
// Info for long
signVerbose(null, "unsigned.jar", "long.jar", "long")
.shouldNotContain("signer certificate has expired")
.shouldNotContain("signer certificate will expire within")
.shouldContain("signer certificate will expire on")
.shouldHaveExitValue(0);
verify("long.jar")
.shouldNotContain("signer certificate has expired")
.shouldNotContain("signer certificate will expire within")
.shouldNotContain("The signer certificate will expire")
.shouldHaveExitValue(0);
verify("long.jar", "-verbose")
.shouldContain("The signer certificate will expire")
.shouldHaveExitValue(0);
// Both expired
signVerbose("tsexpired", "unsigned.jar",
"tsexpired-expired.jar", "expired")
.shouldContain("The signer certificate has expired.")
.shouldContain("The timestamp has expired.")
.shouldHaveExitValue(4);
verify("tsexpired-expired.jar")
.shouldContain("signer certificate has expired")
.shouldContain("timestamp has expired.")
.shouldHaveExitValue(4);
// TS expired but signer still good
signVerbose("tsexpired", "unsigned.jar",
"tsexpired-long.jar", "long")
.shouldContain("The timestamp expired on")
.shouldHaveExitValue(0);
verify("tsexpired-long.jar")
.shouldMatch("timestamp expired on.*However, the JAR will be valid")
.shouldNotContain("Error")
.shouldHaveExitValue(0);
signVerbose("tsexpired", "unsigned.jar",
"tsexpired-ca.jar", "ca")
.shouldContain("The timestamp has expired.")
.shouldHaveExitValue(4);
verify("tsexpired-ca.jar")
.shouldNotContain("timestamp has expired")
.shouldNotContain("Error")
.shouldHaveExitValue(0);
// Warning when expiring
sign("tsexpiring")
.shouldContain("timestamp will expire within")
.shouldHaveExitValue(0);
verify("tsexpiring.jar")
.shouldContain("timestamp will expire within")
.shouldNotContain("still valid")
.shouldHaveExitValue(0);
signVerbose("tsexpiring", "unsigned.jar",
"tsexpiring-ca.jar", "ca")
.shouldContain("self-signed")
.stderrShouldNotMatch("The.*expir")
.shouldHaveExitValue(4); // self-signed
verify("tsexpiring-ca.jar")
.stderrShouldNotMatch("The.*expir")
.shouldHaveExitValue(0);
signVerbose("tsexpiringsoon", "unsigned.jar",
"tsexpiringsoon-long.jar", "long")
.shouldContain("The timestamp will expire")
.shouldHaveExitValue(0);
verify("tsexpiringsoon-long.jar")
.shouldMatch("timestamp will expire.*However, the JAR will be valid until")
.shouldHaveExitValue(0);
// Info for long
sign("tslong")
.shouldNotContain("timestamp has expired")
.shouldNotContain("timestamp will expire within")
.shouldContain("timestamp will expire on")
.shouldContain("signer certificate will expire on")
.shouldHaveExitValue(0);
verify("tslong.jar")
.shouldNotContain("timestamp has expired")
.shouldNotContain("timestamp will expire within")
.shouldNotContain("timestamp will expire on")
.shouldNotContain("signer certificate will expire on")
.shouldHaveExitValue(0);
verify("tslong.jar", "-verbose")
.shouldContain("timestamp will expire on")
.shouldContain("signer certificate will expire on")
.shouldHaveExitValue(0);
}
private static void checkInvalidTsaCertKeyUsage() throws Exception {
// Hack: Rewrite the TSA cert inside normal.jar into ts2.jar.
......@@ -670,6 +822,14 @@ public class TimestampCheck {
keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3");
keytool("-alias tsnoca -genkeypair -dname CN=tsnoca");
keytool("-alias expired -genkeypair -dname CN=expired");
keytool("-alias expiring -genkeypair -dname CN=expiring");
keytool("-alias long -genkeypair -dname CN=long");
keytool("-alias tsexpired -genkeypair -dname CN=tsexpired");
keytool("-alias tsexpiring -genkeypair -dname CN=tsexpiring");
keytool("-alias tsexpiringsoon -genkeypair -dname CN=tsexpiringsoon");
keytool("-alias tslong -genkeypair -dname CN=tslong");
// tsnoca's issuer will be removed from keystore later
keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
gencert("tsnoca", "-ext eku:critical=ts");
......@@ -681,7 +841,15 @@ public class TimestampCheck {
gencert("dsakey");
gencert("weakkeysize");
gencert("badku", "-ext ku:critical=keyAgreement");
gencert("ts", "-ext eku:critical=ts");
gencert("ts", "-ext eku:critical=ts -validity 500");
gencert("expired", "-validity 10 -startdate -12d");
gencert("expiring", "-validity 178");
gencert("long", "-validity 182");
gencert("tsexpired", "-ext eku:critical=ts -validity 10 -startdate -12d");
gencert("tsexpiring", "-ext eku:critical=ts -validity 364");
gencert("tsexpiringsoon", "-ext eku:critical=ts -validity 170"); // earlier than expiring
gencert("tslong", "-ext eku:critical=ts -validity 367");
for (int i = 0; i < 5; i++) {
......@@ -701,7 +869,7 @@ public class TimestampCheck {
}
}
gencert("tsold", "-ext eku:critical=ts -startdate -40d -validity 45");
gencert("tsold", "-ext eku:critical=ts -startdate -40d -validity 500");
gencert("tsweak", "-ext eku:critical=ts");
gencert("tsbad1");
......
......@@ -51,32 +51,12 @@ public class AliasNotInStoreTest extends Test {
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create first key pair for signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", FIRST_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", BOTH_KEYS_KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=First",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
// create second key pair for signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", SECOND_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", BOTH_KEYS_KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Second",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
createAlias(FIRST_KEY_ALIAS);
createAlias(SECOND_KEY_ALIAS);
// sign jar with first key
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
"-keystore", BOTH_KEYS_KEYSTORE,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-signedjar", SIGNED_JARFILE,
......@@ -93,7 +73,7 @@ public class AliasNotInStoreTest extends Test {
// sign jar with second key
analyzer = ProcessTools.executeCommand(JARSIGNER,
"-keystore", BOTH_KEYS_KEYSTORE,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
UPDATED_SIGNED_JARFILE,
......@@ -104,7 +84,7 @@ public class AliasNotInStoreTest extends Test {
// create keystore that contains only first key
ProcessTools.executeCommand(KEYTOOL,
"-importkeystore",
"-srckeystore", BOTH_KEYS_KEYSTORE,
"-srckeystore", KEYSTORE,
"-srcalias", FIRST_KEY_ALIAS,
"-srcstorepass", PASSWORD,
"-srckeypass", PASSWORD,
......@@ -113,7 +93,7 @@ public class AliasNotInStoreTest extends Test {
"-deststorepass", PASSWORD,
"-destkeypass", PASSWORD).shouldHaveExitValue(0);
// verify jar with keystore that contains only first key in strict mode,
// verify jar with keystore that contains only first key,
// so there is signed entry (FirstClass.class) that is not signed
// by any alias in the keystore
analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -52,17 +52,14 @@ public class BadExtendedKeyUsageTest extends Test {
// create a certificate whose signer certificate's
// ExtendedKeyUsage extension doesn't allow code signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
// create key pair for jar signing
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-ext", "ExtendedkeyUsage=serverAuth",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
"-validity", Integer.toString(VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -53,17 +53,13 @@ public class BadKeyUsageTest extends Test {
// create a certificate whose signer certificate's KeyUsage extension
// doesn't allow code signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-ext", "KeyUsage=keyAgreement",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
"-validity", Integer.toString(VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -25,10 +25,6 @@ import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import jdk.testlibrary.JarUtils;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
/**
* @test
* @bug 8024302 8026037
......@@ -38,25 +34,14 @@ import java.util.Base64;
*/
public class BadNetscapeCertTypeTest extends Test {
private static final String NETSCAPE_KEYSTORE_BASE64 = TEST_SOURCES + FS
+ "bad_netscape_cert_type.jks.base64";
private static final String NETSCAPE_KEYSTORE
= "bad_netscape_cert_type.jks";
/**
* The test signs and verifies a jar that contains entries
* whose signer certificate's NetscapeCertType extension
* doesn't allow code signing (badNetscapeCertType).
* Warning message is expected.
* Run bad_netscape_cert_type.sh script to create bad_netscape_cert_type.jks
*/
public static void main(String[] args) throws Throwable {
Files.write(Paths.get(NETSCAPE_KEYSTORE),
Base64.getMimeDecoder().decode(
Files.readAllBytes(Paths.get(NETSCAPE_KEYSTORE_BASE64))));
BadNetscapeCertTypeTest test = new BadNetscapeCertTypeTest();
test.start();
}
......@@ -66,10 +51,22 @@ public class BadNetscapeCertTypeTest extends Test {
Utils.createFiles(FIRST_FILE);
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create a certificate whose signer certificate's
// NetscapeCertType extension doesn't allow code signing
// create key pair for jar signing
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
// NetscapeCertType [ SSL client ]
"-ext", "2.16.840.1.113730.1.1=03020780",
"-validity", Integer.toString(VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
"-verbose",
"-keystore", NETSCAPE_KEYSTORE,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-signedjar", SIGNED_JARFILE,
......@@ -82,7 +79,7 @@ public class BadNetscapeCertTypeTest extends Test {
analyzer = ProcessTools.executeCommand(JARSIGNER,
"-verify",
"-verbose",
"-keystore", NETSCAPE_KEYSTORE,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
SIGNED_JARFILE);
......@@ -94,7 +91,7 @@ public class BadNetscapeCertTypeTest extends Test {
"-verify",
"-verbose",
"-strict",
"-keystore", NETSCAPE_KEYSTORE,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
SIGNED_JARFILE);
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -21,117 +21,52 @@
* questions.
*/
import java.io.File;
import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import jdk.testlibrary.JarUtils;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @test
* @bug 8024302 8026037
* @summary Test for chainNotValidated warning
* @library /lib/testlibrary ../
* @run main ChainNotValidatedTest
* @run main ChainNotValidatedTest ca2yes
* @run main ChainNotValidatedTest ca2no
*/
public class ChainNotValidatedTest extends Test {
private static final String CHAIN = "chain";
/**
* The test signs and verifies a jar that contains entries
* whose cert chain can't be correctly validated (chainNotValidated).
* Warning message is expected.
*/
public static void main(String[] args) throws Throwable {
ChainNotValidatedTest test = new ChainNotValidatedTest();
test.start();
test.start(args[0].equals("ca2yes"));
}
private void start() throws Throwable {
private void start(boolean ca2yes) throws Throwable {
// create a jar file that contains one class file
Utils.createFiles(FIRST_FILE);
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create self-signed certificate whose BasicConstraints extension
// is set to false, so the certificate may not be used
// as a parent certificate (certpath validation should fail)
ProcessTools.executeCommand(KEYTOOL,
"-genkeypair",
"-alias", CA_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=CA",
"-ext", "BasicConstraints:critical=ca:false",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
// We have 2 @run. Need cleanup.
Files.deleteIfExists(Paths.get(KEYSTORE));
// create a certificate that is signed by self-signed certificate
// despite of it may not be used as a parent certificate
// (certpath validation should fail)
ProcessTools.executeCommand(KEYTOOL,
"-genkeypair",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
"-ext", "BasicConstraints:critical=ca:false",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
ProcessTools.executeCommand(KEYTOOL,
"-certreq",
"-alias", KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-file", CERT_REQUEST_FILENAME).shouldHaveExitValue(0);
// Root CA is not checked at all. If the intermediate CA has
// BasicConstraints extension set to true, it will be valid.
// Otherwise, chain validation will fail.
createAlias(CA_KEY_ALIAS);
createAlias(CA2_KEY_ALIAS);
issueCert(CA2_KEY_ALIAS,
"-ext",
"bc=ca:" + ca2yes);
ProcessTools.executeCommand(KEYTOOL,
"-gencert",
"-alias", CA_KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-infile", CERT_REQUEST_FILENAME,
"-validity", Integer.toString(VALIDITY),
"-outfile", CERT_FILENAME).shouldHaveExitValue(0);
ProcessTools.executeCommand(KEYTOOL,
"-importcert",
"-alias", KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-file", CERT_FILENAME).shouldHaveExitValue(0);
ProcessBuilder pb = new ProcessBuilder(KEYTOOL,
"-export",
"-rfc",
"-alias", KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD);
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(CHAIN)));
ProcessTools.executeCommand(pb).shouldHaveExitValue(0);
pb = new ProcessBuilder(KEYTOOL,
"-export",
"-rfc",
"-alias", CA_KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD);
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(CHAIN)));
ProcessTools.executeCommand(pb).shouldHaveExitValue(0);
createAlias(KEY_ALIAS);
issueCert(KEY_ALIAS, "-alias", CA2_KEY_ALIAS);
// remove CA certificate
// remove CA2 certificate so it's not trusted
ProcessTools.executeCommand(KEYTOOL,
"-delete",
"-alias", CA_KEY_ALIAS,
"-alias", CA2_KEY_ALIAS,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD).shouldHaveExitValue(0);
......@@ -141,12 +76,15 @@ public class ChainNotValidatedTest extends Test {
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-certchain", CHAIN,
"-signedjar", SIGNED_JARFILE,
UNSIGNED_JARFILE,
KEY_ALIAS);
checkSigning(analyzer, CHAIN_NOT_VALIDATED_SIGNING_WARNING);
if (ca2yes) {
checkSigning(analyzer, "!" + CHAIN_NOT_VALIDATED_SIGNING_WARNING);
} else {
checkSigning(analyzer, CHAIN_NOT_VALIDATED_SIGNING_WARNING);
}
// verify signed jar
analyzer = ProcessTools.executeCommand(JARSIGNER,
......@@ -155,10 +93,13 @@ public class ChainNotValidatedTest extends Test {
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-certchain", CHAIN,
SIGNED_JARFILE);
checkVerifying(analyzer, 0, CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
if (ca2yes) {
checkVerifying(analyzer, 0, "!" + CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
} else {
checkVerifying(analyzer, 0, CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
}
// verify signed jar in strict mode
analyzer = ProcessTools.executeCommand(JARSIGNER,
......@@ -168,11 +109,15 @@ public class ChainNotValidatedTest extends Test {
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-certchain", CHAIN,
SIGNED_JARFILE);
checkVerifying(analyzer, CHAIN_NOT_VALIDATED_EXIT_CODE,
CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
if (ca2yes) {
checkVerifying(analyzer, 0,
"!" + CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
} else {
checkVerifying(analyzer, CHAIN_NOT_VALIDATED_EXIT_CODE,
CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
}
System.out.println("Test passed");
}
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -52,18 +52,13 @@ public class HasExpiredCertTest extends Test {
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create key pair for jar signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-startdate", "-" + SHORT_VALIDITY * 2 + "d",
"-validity", Integer.toString(SHORT_VALIDITY))
.shouldHaveExitValue(0);
"-validity", Integer.toString(SHORT_VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -52,17 +52,12 @@ public class HasExpiringCertTest extends Test {
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create key pair for jar signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
"-validity", Integer.toString(SHORT_VALIDITY))
.shouldHaveExitValue(0);
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-validity", Integer.toString(SHORT_VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -51,16 +51,11 @@ public class HasUnsignedEntryTest extends Test {
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create key pair for signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-validity", Integer.toString(VALIDITY));
// sign jar
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -54,35 +54,25 @@ public class MultipleWarningsTest extends Test {
// create a jar file that contains one class file
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
createAlias(CA_KEY_ALIAS);
// create first expired certificate
// whose ExtendedKeyUsage extension does not allow code signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", FIRST_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=First",
createAlias(FIRST_KEY_ALIAS);
issueCert(
FIRST_KEY_ALIAS,
"-ext", "ExtendedkeyUsage=serverAuth",
"-startdate", "-" + VALIDITY * 2 + "d",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
"-validity", Integer.toString(VALIDITY));
// create second expired certificate
// whose KeyUsage extension does not allow code signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", SECOND_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Second",
createAlias(SECOND_KEY_ALIAS);
issueCert(
SECOND_KEY_ALIAS,
"-ext", "ExtendedkeyUsage=serverAuth",
"-startdate", "-" + VALIDITY * 2 + "d",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
"-validity", Integer.toString(VALIDITY));
// sign jar with first key
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -57,15 +57,9 @@ public class NoTimestampTest extends Test {
* 24 * 60 * 60 * 1000L);
// create key pair
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(KEY_ALIAS,
"-validity", Integer.toString(VALIDITY));
// sign jar file
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -49,29 +49,19 @@ public class NotSignedByAliasTest extends Test {
Utils.createFiles(FIRST_FILE);
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
createAlias(CA_KEY_ALIAS);
// create first key pair for signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", FIRST_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=First",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
createAlias(FIRST_KEY_ALIAS);
issueCert(
FIRST_KEY_ALIAS,
"-validity", Integer.toString(VALIDITY));
// create first key pair for signing
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", SECOND_KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Second",
"-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
createAlias(SECOND_KEY_ALIAS);
issueCert(
SECOND_KEY_ALIAS,
"-validity", Integer.toString(VALIDITY));
// sign jar with first key
OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
......
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -50,15 +50,11 @@ public class NotYetValidCertTest extends Test {
JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
// create certificate that will be valid only tomorrow
ProcessTools.executeCommand(KEYTOOL,
"-genkey",
"-alias", KEY_ALIAS,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=Test",
createAlias(CA_KEY_ALIAS);
createAlias(KEY_ALIAS);
issueCert(
KEY_ALIAS,
"-startdate", "+1d",
"-validity", Integer.toString(VALIDITY));
......
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, 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
......@@ -45,7 +45,6 @@ public abstract class Test {
static final String FIRST_FILE = "first.txt";
static final String SECOND_FILE = "second.txt";
static final String PASSWORD = "password";
static final String BOTH_KEYS_KEYSTORE = "both_keys.jks";
static final String FIRST_KEY_KEYSTORE = "first_key.jks";
static final String KEYSTORE = "keystore.jks";
static final String FIRST_KEY_ALIAS = "first";
......@@ -55,11 +54,13 @@ public abstract class Test {
static final String CERT_REQUEST_FILENAME = "test.req";
static final String CERT_FILENAME = "test.crt";
static final String CA_KEY_ALIAS = "ca";
static final String CA2_KEY_ALIAS = "ca2";
static final int KEY_SIZE = 2048;
static final int TIMEOUT = 6 * 60 * 1000; // in millis
static final int VALIDITY = 365;
static final String WARNING = "Warning:";
static final String WARNING_OR_ERROR = "(Warning|Error):";
static final String CHAIN_NOT_VALIDATED_VERIFYING_WARNING
= "This jar contains entries "
......@@ -126,10 +127,10 @@ public abstract class Test {
+ "(%1$tY-%1$tm-%1$td) or after any future revocation date.";
static final String NO_TIMESTAMP_VERIFYING_WARN_TEMPLATE
= "This jar contains signatures that does not include a timestamp. "
= "This jar contains signatures that do not include a timestamp. "
+ "Without a timestamp, users may not be able to validate this jar "
+ "after the signer certificate's expiration date "
+ "(%1$tY-%1$tm-%1$td) or after any future revocation date.";
+ "after any of the signer certificates expire "
+ "(as early as %1$tY-%1$tm-%1$td).";
static final String NOT_YET_VALID_CERT_SIGNING_WARNING
= "The signer certificate is not yet valid.";
......@@ -154,14 +155,72 @@ public abstract class Test {
static final int ALIAS_NOT_IN_STORE_EXIT_CODE = 32;
static final int NOT_SIGNED_BY_ALIAS_EXIT_CODE = 32;
protected void createAlias(String alias, String ... options)
throws Throwable {
List<String> cmd = new ArrayList<>();
cmd.addAll(Arrays.asList(
"-genkeypair",
"-alias", alias,
"-keyalg", KEY_ALG,
"-keysize", Integer.toString(KEY_SIZE),
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-dname", "CN=" + alias));
cmd.addAll(Arrays.asList(options));
keytool(cmd.toArray(new String[cmd.size()]))
.shouldHaveExitValue(0);
}
protected void issueCert(String alias, String ... options)
throws Throwable {
keytool("-certreq",
"-alias", alias,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-file", alias + ".req")
.shouldHaveExitValue(0);
List<String> cmd = new ArrayList<>();
cmd.addAll(Arrays.asList(
"-gencert",
"-alias", CA_KEY_ALIAS,
"-infile", alias + ".req",
"-outfile", alias + ".cert",
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-file", alias + ".req"));
cmd.addAll(Arrays.asList(options));
keytool(cmd.toArray(new String[cmd.size()]))
.shouldHaveExitValue(0);
keytool("-importcert",
"-alias", alias,
"-keystore", KEYSTORE,
"-storepass", PASSWORD,
"-keypass", PASSWORD,
"-file", alias + ".cert")
.shouldHaveExitValue(0);
}
protected void checkVerifying(OutputAnalyzer analyzer, int expectedExitCode,
String... warnings) {
analyzer.shouldHaveExitValue(expectedExitCode);
int count = 0;
for (String warning : warnings) {
analyzer.shouldContain(warning);
if (warning.startsWith("!")) {
analyzer.shouldNotContain(warning.substring(1));
} else {
count++;
analyzer.shouldContain(warning);
}
}
if (warnings.length > 0) {
analyzer.shouldContain(WARNING);
if (count > 0) {
analyzer.shouldMatch(WARNING_OR_ERROR);
}
if (expectedExitCode == 0) {
analyzer.shouldContain(JAR_VERIFIED);
......@@ -172,11 +231,17 @@ public abstract class Test {
protected void checkSigning(OutputAnalyzer analyzer, String... warnings) {
analyzer.shouldHaveExitValue(0);
int count = 0;
for (String warning : warnings) {
analyzer.shouldContain(warning);
if (warning.startsWith("!")) {
analyzer.shouldNotContain(warning.substring(1));
} else {
count++;
analyzer.shouldContain(warning);
}
}
if (warnings.length > 0) {
analyzer.shouldContain(WARNING);
if (count > 0) {
analyzer.shouldMatch(WARNING_OR_ERROR);
}
analyzer.shouldContain(JAR_SIGNED);
}
......
/u3+7QAAAAIAAAABAAAAAQAFYWxpYXMAAAFBpkwW0gAAAr0wggK5MA4GCisGAQQB
KgIRAQEFAASCAqWkGJ3PPjYmWNKrV23Y1u413RMAkrRZ+1OLWYRcQt4jtxtIyEH5
Ho5b9dy9XN9FBKlTOD4c2Pc1T43BLKXeuLu3uLLeIxgXFt0z9CLyGwdYZZ751kXr
DQ99qY6aNQUO6SeE4Wdty0KPAqid6ZJ8bF7T6wsTZSvNhaBRzyFydEfG7bbUYjOl
mWC44nlsu6VEU3o9RQpcm1gIMwradOaIVT/HoB2bKmAv8gHqI6kreiEZwTdZkSAI
IRi2vt1RPllXt5hgjDxUfZe8XOYYweR4Vt2/jVuKLJ80DNTu/9SeUD88zQAz53k4
r3nRhv6TRcPm6tV/Fh92XLHiskL+TAzTfm+bUAudPCCVxN+yRtxvAgA+UhdV/SuM
Zn5F6nrmP+YJG1hmprgCJIJJaCEXa9RXYC+vIVpO0WVNRuGlGm+/1afnOuQC8Wss
ShXwjkaqTwAhqBFq7eYmmP8BK3gflYrt2zDLXvhl4ndVvMhMthFJ3ZvLh2LWpqLI
/n8EMCf8US3lIEFk9DTHBZjffiHkqK2e7+FXEpG3xrgE6ZYLMdbd5Pb3YjZfhQx+
ZTtiEFzYSaEGhacek/m7dRq1qmwgFsytng2OdWZe2ln8LJY0odr1dGUfJHfgafvi
tlfbkg/rgjONtwliChDggbkUwnerrj/D/zrdEufUvfyltSshhHXRNDD3fH6spmEk
hHKgxEc4yvxqJxzdMGtuib355aSfNegyl+GsnsKzXQCVEK2h3BLTQObzaD+8NZ12
LQHvbrCiaS34vxJ3rEC+a+SW7itZp0aCdXMWdMJNkRKqyLBD3vG3zN05sN3XrhEM
8BRT020TWY00tbVFbbBFheYLQRgTjrQtr0Yt6UHWBZc4N20crDLcSH5gqcCOVpla
1Y2uqFEn8yqrGRwn/kgfNgAAAAEABVguNTA5AAABtTCCAbEwggEaoAMCAQICCQDH
cEuVvzCuqzANBgkqhkiG9w0BAQUFADAPMQ0wCwYDVQQDDARUZXN0MB4XDTEzMTAx
MTA2NTUwNloXDTIzMTAwOTA2NTUwNlowDzENMAsGA1UEAwwEVGVzdDCBnzANBgkq
hkiG9w0BAQEFAAOBjQAwgYkCgYEA8hOfp2Dcnvt//ZZQAja9TRiwKqXVS+TiYE3S
gngCBjIi+YYdo0DsUeO5MBfE6uvCWOr5lwAR/u1iaJOhIoGJDiGoPasZlt+yIgtR
LzA7j2q+1q6kcwiVxfikI3aUgHV/QsybTriT4Bf7TQNKtJG23MQa4sD7+PjtCWD7
p3cHTfkCAwEAAaMVMBMwEQYJYIZIAYb4QgEBBAQDAgeAMA0GCSqGSIb3DQEBBQUA
A4GBAKoDlTJ8wLRA7G8XdGm4gv733n1cSQzlkcsjfOO6/mA5Jvu8tyFNq9HTf9AT
VXbrbGcUYJjhzSSY3w5apXK1kXyqTB1LUNEJ45WnmciqSSecVTpJz9TuegyoX0Zf
HScSgqfDmjqoiiFiNCgn3ZEJ85ykGvoFYGH+php+BVi3S0bj5E/jRpyV3vNnii/S
wJDSAXF6bYU=
#
# Copyright (c) 2013, 2015, 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.
#
#!/bin/sh
# This script creates JKS keystore with a certificate
# that contains Netscape Certificate Type extension
# that does not allow code signing
# The keystore is used by BadNetscapeCertTypeTest.java test
rm -rf keystore.jks
echo "nsCertType = client" > ext.cfg
openssl req -new -out cert.req -keyout key.pem -days 3650 \
-passin pass:password -passout pass:password -subj "/CN=Test"
openssl x509 -in cert.req -out cert.pem -req -signkey key.pem -days 3650 \
-passin pass:password -extfile ext.cfg
openssl pkcs12 -export -in cert.pem -inkey key.pem -out keystore.p12 \
-passin pass:password -passout pass:password -name alias
${JAVA_HOME}/bin/keytool -importkeystore \
-srckeystore keystore.p12 -srcstoretype pkcs12 \
-srcstorepass password -alias alias \
-destkeystore bad_netscape_cert_type.jks -deststoretype jks \
-deststorepass password -destalias alias \
openssl base64 < bad_netscape_cert_type.jks > bad_netscape_cert_type.jks.base64
rm -rf cert.req key.pem cert.pem keystore.p12 ext.cfg bad_netscape_cert_type.jks
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册