undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2004, 2022, 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 5097015 8130181 8279222 8292739
* @summary make sure we correctly treat Provider string entries as case insensitive
* @author Andreas Sterbenz
*/
import java.security.*;
import java.security.Provider.*;
public class CaseSensitiveServices extends Provider {
CaseSensitiveServices() {
super("Foo", "1.0", null);
put("MessageDigest.Foo", "com.Foo");
put("mESSAGEdIGEST.fOO xYz", "aBc");
// first assign the DEF alias to algorithm Foo
put("ALg.aliaS.MESSAGEdigest.DEF", "FoO");
put("messageDigest.Bar", "com.Bar");
put("MESSAGEDIGEST.BAZ", "com.Baz");
// reassign the DEF alias to algorithm Bar
put("ALg.aliaS.MESSAGEdigest.DEF", "Bar");
// invalid entry since it misses the corresponding impl class info
// e.g. put("MessageDigest.Invalid", "implClass");
put("MessageDigest.Invalid xYz", "aBc");
}
public static void main(String[] args) throws Exception {
Provider p = new CaseSensitiveServices();
System.out.println("Services: " + p.getServices());
if (p.getServices().size() != 3) {
throw new Exception("services.size() should be 3");
}
if (p.getService("MessageDigest", "Invalid") != null) {
throw new Exception("Invalid service returned");
}
Service s = testService(p, "MessageDigest", "fOO");
String val = s.getAttribute("Xyz");
if ("aBc".equals(val) == false) {
throw new Exception("Wrong value: " + val);
}
if (s.toString().indexOf("DEF") != -1) {
throw new Exception("Old alias DEF should be removed");
}
// test Service alias DEF and its associated impl is Bar
s = testService(p, "MessageDigest", "DeF");
if (s.getAttribute("Xyz") != null) {
throw new Exception("DEF mapped to the wrong impl");
}
testService(p, "MessageDigest", "BAR");
testService(p, "MessageDigest", "baz");
System.out.println("OK");
}
private static Service testService(Provider p, String type, String alg)
throws Exception {
System.out.println("Getting " + type + "." + alg + "...");
Service s = p.getService(type, alg);
System.out.println(s);
if (s == null) {
throw new Exception("Lookup failed for: " + type + "." + alg);
}
return s;
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2005, 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 6219491
* @summary CertStore.getInstance(String,CertStoreParameters,String) throws NoSuchAlgorithmE
*/
import java.security.*;
import java.security.cert.*;
public class CertStoreConstructorParam {
public static void main(String[] args) throws Exception {
try {
// attempt with null constructor param
CertStore.getInstance("Collection", null, "SUN");
} catch (InvalidAlgorithmParameterException iape) {
// ok - thrown by SUN provider
System.out.println("test passed");
} catch (NoSuchAlgorithmException nsae) {
// bad - thrown by Provider.Service.newInstance
System.out.println("test failed");
throw nsae;
}
}
}

View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2003, 2025, 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 4856968 7054918 8130181 8175874
* @library /test/lib
* @summary make sure add/insert/removeProvider() work correctly
* @author Andreas Sterbenz
*/
import java.security.*;
import jdk.test.lib.security.ProvidersSnapshot;
public class ChangeProviders extends Provider {
private ChangeProviders() {
super("Foo", "47.23", "none");
}
private static int plen() {
return Security.getProviders().length;
}
public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
long start = System.currentTimeMillis();
Provider p = new ChangeProviders();
int n = plen();
Security.addProvider(p);
if (plen() != n + 1) {
throw new Exception("Provider not added");
}
Security.addProvider(p);
if (plen() != n + 1) {
throw new Exception("Provider readded");
}
Security.insertProviderAt(p, 1);
if (plen() != n + 1) {
throw new Exception("Provider readded");
}
Security.removeProvider(p.getName());
if ((plen() != n) || (Security.getProvider(p.getName()) != null)) {
throw new Exception("Provider not removed");
}
Security.insertProviderAt(p, 1);
if (plen() != n + 1) {
throw new Exception("Provider not added");
}
if (Security.getProviders()[0] != p) {
throw new Exception("Provider not at pos 1");
}
// Ensure that providers inserted at positions outside of [1..n] are placed
// at the n+1st position
Security.removeProvider(p.getName());
Security.insertProviderAt(p, 0);
if (plen() != n + 1 || Security.getProviders()[n] != p) {
throw new Exception("Provider inserted at zero not at pos n+1");
}
Security.removeProvider(p.getName());
Security.insertProviderAt(p, n + 5);
if (plen() != n + 1 || Security.getProviders()[n] != p) {
throw new Exception("Provider inserted at n+5 not at pos n+1");
}
System.out.println("All tests passed.");
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 7191662 8157469 8157489
* @summary Ensure non-java.base providers can be found by ServiceLoader
* @author Valerie Peng
*/
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ServiceLoader;
public class DefaultProviderList {
public static void main(String[] args) throws Exception {
Provider[] defaultProvs = Security.getProviders();
System.out.println("Providers: " + Arrays.asList(defaultProvs));
System.out.println();
ServiceLoader<Provider> sl = ServiceLoader.load(Provider.class);
boolean failed = false;
Module baseMod = Object.class.getModule();
// Test#1: check that all non-base security providers can be found
// through ServiceLoader
for (Provider p : defaultProvs) {
String pName = p.getName();
Class pClass = p.getClass();
if (pClass.getModule() != baseMod) {
String pClassName = pClass.getName();
Iterator<Provider> provIter = sl.iterator();
boolean found = false;
while (provIter.hasNext()) {
Provider pFromSL = provIter.next();
// check for match by class name because PKCS11 provider
// will have a different name after being configured.
if (pFromSL.getClass().getName().equals(pClassName)) {
found = true;
System.out.println("SL found provider " + pName);
break;
}
}
if (!found) {
failed = true;
System.out.println("Error: SL cannot find provider " +
pName);
}
}
}
// Test#2: check that all security providers found through ServiceLoader
// are not from base module
Iterator<Provider> provIter = sl.iterator();
while (provIter.hasNext()) {
Provider pFromSL = provIter.next();
if (pFromSL.getClass().getModule() == baseMod) {
failed = true;
System.out.println("Error: base provider " +
pFromSL.getName() + " loaded by SL");
}
}
if (!failed) {
System.out.println("Test Passed");
} else {
throw new Exception("One or more tests failed");
}
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4918769 8130181
* @summary make sure Provider.equals() behaves as expected with the id attributes
* @author Andreas Sterbenz
*/
import java.security.*;
public class Equals {
public static void main(String[] args) throws Exception {
Provider p1 = new P1("foo", "1.0", "foo");
Provider p1b = new P1("foo", "1.0", "foo");
Provider p2 = new P2("foo", "1.0", "foo");
System.out.println(p1.entrySet());
if (p1.equals(p2)) {
throw new Exception("Objects are equal");
}
if (p1.equals(p1b) == false) {
throw new Exception("Objects not equal");
}
p1.clear();
if (p1.equals(p1b) == false) {
throw new Exception("Objects not equal");
}
p1.put("Provider.id name", "bar");
p1.remove("Provider.id version");
if (p1.equals(p1b) == false) {
throw new Exception("Objects not equal");
}
}
private static class P1 extends Provider {
P1(String name, String version, String info) {
super(name, version, info);
}
}
private static class P2 extends Provider {
P2(String name, String version, String info) {
super(name, version, info);
}
}
}

View file

@ -0,0 +1,267 @@
/*
* Copyright (c) 2003, 2025, 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 4856968 7054918 8130181
* @library /test/lib
* @summary make sure getInstance() works correctly, including failover
* and delayed provider selection for Signatures
* @author Andreas Sterbenz
*/
import java.util.*;
import java.security.*;
import java.security.cert.*;
import jdk.test.lib.security.ProvidersSnapshot;
public class GetInstance {
private static void same(Provider p1, Provider p2) throws Exception {
if (p1 != p2) {
throw new Exception("Wrong provider");
}
}
public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
long start = System.currentTimeMillis();
Provider foo = new FooProvider();
Provider bar = new BarProvider();
Provider baz = new BazProvider();
Security.addProvider(foo);
Security.addProvider(bar);
Security.addProvider(baz);
System.out.println("Testing MessageDigest.getInstance()...");
MessageDigest m;
m = MessageDigest.getInstance("foo");
m = MessageDigest.getInstance("foo", "foo");
m = MessageDigest.getInstance("foo", foo);
System.out.println("Testing Signature.getInstance() for SPI...");
Signature sig;
PrivateKey privateKey = new FooPrivateKey();
sig = Signature.getInstance("foo");
same(foo, sig.getProvider());
sig = Signature.getInstance("foo");
sig.initSign(privateKey);
same(foo, sig.getProvider());
sig = Signature.getInstance("foo", "foo");
sig.initSign(privateKey);
same(foo, sig.getProvider());
sig = Signature.getInstance("foo", foo);
sig.initSign(privateKey);
same(foo, sig.getProvider());
System.out.println("Testing Signature.getInstance() for Signature...");
sig = Signature.getInstance("fuu");
same(foo, sig.getProvider());
sig = Signature.getInstance("fuu");
sig.initSign(privateKey);
same(foo, sig.getProvider());
sig = Signature.getInstance("fuu", "foo");
sig.initSign(privateKey);
same(foo, sig.getProvider());
sig = Signature.getInstance("fuu", foo);
sig.initSign(privateKey);
same(foo, sig.getProvider());
System.out.println("Testing CertStore.getInstance()...");
CertStoreParameters params = new CollectionCertStoreParameters(Collections.EMPTY_LIST);
CertStore cs;
cs = CertStore.getInstance("foo", params);
cs = CertStore.getInstance("foo", params, "foo");
cs = CertStore.getInstance("foo", params, foo);
System.out.println("Testing failover...");
m = MessageDigest.getInstance("bar");
same(m.getProvider(), baz);
sig = Signature.getInstance("bar");
same(sig.getProvider(), baz);
cs = CertStore.getInstance("bar", params);
same(cs.getProvider(), baz);
System.out.println("Testing Signature delayed provider selection...");
sig = Signature.getInstance("baz");
sig.initVerify(new FooPublicKey());
same(sig.getProvider(), baz);
Provider.Service s = foo.getService("CertStore", "foo");
s.newInstance(null);
s.newInstance(params);
try {
s.newInstance(0);
throw new Exception("call should not succeed");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Throwable cause = e.getCause();
if (cause instanceof InvalidParameterException == false) {
throw new Exception("incorrect exception");
}
}
long stop = System.currentTimeMillis();
System.out.println("Done (" + (stop - start) + " ms).");
}
public static class FooProvider extends Provider {
FooProvider() {
super("foo", "1.0", "none");
put("MessageDigest.foo", "GetInstance$FooDigest");
put("CertStore.foo", "GetInstance$FooStore");
put("Signature.foo", "GetInstance$FooSignatureSpi");
put("Signature.fuu", "GetInstance$BazSignature");
// throws InvalidKeyException, skipped in delayed provider selection
put("Signature.baz", "GetInstance$BazSignatureSpi");
}
}
public static class BarProvider extends Provider {
BarProvider() {
super("bar", "1.0", "none");
// all entries invalid for failover
put("MessageDigest.bar", "GetInstance$FooKey");
put("Signature.bar", "GetInstance$FooKey");
put("Certstore.bar", "GetInstance$FooKey");
// not an SPI, skipped in delayed provider selection
put("Signature.baz", "GetInstance$BazSignature");
}
}
public static class BazProvider extends Provider {
BazProvider() {
super("baz", "1.0", "none");
put("MessageDigest.bar", "GetInstance$FooDigest");
put("CertStore.bar", "GetInstance$FooStore");
put("Signature.bar", "GetInstance$FooSignatureSpi");
put("Signature.baz", "GetInstance$FooSignatureSpi");
}
}
public static class FooDigest extends MessageDigestSpi {
public byte[] engineDigest() { return new byte[0]; }
public void engineReset() {}
public void engineUpdate(byte input) {}
public void engineUpdate(byte[] b, int ofs, int len) {}
}
public static class FooStore extends CertStoreSpi {
public FooStore(CertStoreParameters params) throws InvalidAlgorithmParameterException { super(params); }
public Collection engineGetCertificates(CertSelector sel) { return Collections.EMPTY_LIST; }
public Collection engineGetCRLs(CRLSelector sel) { return Collections.EMPTY_LIST; }
}
public static class BaseSignatureSpi extends SignatureSpi {
protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
}
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
}
protected void engineUpdate(byte b) throws SignatureException { }
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { }
protected byte[] engineSign() throws SignatureException {
return new byte[0];
}
protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
return false;
}
protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
}
protected Object engineGetParameter(String param) throws InvalidParameterException {
return null;
}
}
public static class BaseSignature extends Signature {
BaseSignature(String s) {
super(s);
}
protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
//
}
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { }
protected void engineUpdate(byte b) throws SignatureException { }
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { }
protected byte[] engineSign() throws SignatureException {
return new byte[0];
}
protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
return false;
}
protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
}
protected Object engineGetParameter(String param) throws InvalidParameterException {
return null;
}
}
public static abstract class FooKey implements Key {
public String getFormat() { return null; }
public byte[] getEncoded() { return null; }
public String getAlgorithm() { return "foo"; }
}
public static class FooPrivateKey extends FooKey implements PrivateKey { }
public static class FooPublicKey extends FooKey implements PublicKey { }
public static class FooSignatureSpi extends BaseSignatureSpi {
public FooSignatureSpi() {
super();
System.out.println("FooSignatureSpi constructor");
}
}
public static class BazSignatureSpi extends BaseSignatureSpi {
public BazSignatureSpi() {
super();
System.out.println("BazSignatureSpi constructor");
}
protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
throw new InvalidKeyException("verify not supported");
}
}
public static class BazSignature extends BaseSignature {
public BazSignature() {
super("baz");
System.out.println("BazSignature constructor");
}
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 2019, 2025, 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 8231387
* @summary make sure getService() avoids a race
* @author Tianmin Shi
*/
import java.security.Provider;
public class GetServiceRace {
private static final Provider testProvider;
static {
testProvider = new Provider("MyProvider", 1.0, "test") {
};
testProvider.put("CertificateFactory.Fixed", "MyCertificateFactory");
}
private static final int NUMBER_OF_RETRIEVERS = 3;
private static final int TEST_TIME_MS = 1000;
public static boolean testFailed = false;
public static void main(String[] args) throws Exception {
Updater updater = new Updater();
updater.start();
Retriever [] retrievers = new Retriever[NUMBER_OF_RETRIEVERS];
for (int i=0; i<retrievers.length; i++) {
retrievers[i] = new Retriever();
retrievers[i].start();
}
Thread.sleep(TEST_TIME_MS);
System.out.println("Interrupt");
updater.interrupt();
updater.join();
for (int i=0; i<retrievers.length; i++) {
retrievers[i].interrupt();
retrievers[i].join();
}
System.out.println("Done");
if (testFailed) {
throw new Exception("Test Failed");
}
System.out.println("Test Passed");
}
private static class Updater extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
testProvider.put("CertificateFactory.Added", "MyCertificateFactory");
}
System.out.println("Updater stopped");
}
}
private static class Retriever extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
Provider.Service service = testProvider.getService("CertificateFactory", "Fixed");
if (service == null) {
if (!testFailed) {
System.err.println("CertificateFactory.Fixed is NULL");
testFailed = true;
}
} else {
//System.out.println("CertificateFactory.Fixed is good");
}
}
System.out.println("Retriever stopped");
}
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2025, 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 8344361
* @summary Restore null return for invalid services
*/
import java.security.Provider;
public class InvalidServiceTest {
public static void main(String[] args) throws Exception {
Provider p1 = new LProvider("LegacyFormat");
// this returns a service with null class name. Helps exercise the code path
Provider.Service s1 = p1.getService("MessageDigest", "SHA-1");
if (s1 != null)
throw new RuntimeException("expecting null service");
}
private static class LProvider extends Provider {
LProvider(String name) {
super(name, "1.0", null);
put("Signature.MD5withRSA", "com.foo.Sig");
put("MessageDigest.SHA-1 ImplementedIn", "Software");
}
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2014, 2025, 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 8039853
* @summary Provider.Service.newInstance() does not work with current
JDK JGSS Mechanisms
* @library /test/lib
*/
import jtreg.SkippedException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class NewInstance {
public static void main(String[] args) throws Exception {
System.out.println("Removing SunPCSC provider from the list (A smartcard might not be installed).");
final List<Provider> providers = Arrays.stream(Security.getProviders())
.filter(provider -> !provider.getName().equals("SunPCSC"))
.collect(Collectors.toList());
for (Provider p : providers) {
System.out.println("---------");
System.out.println(p.getName() + ":" + p.getInfo());
Set<Provider.Service> set = p.getServices();
Iterator<Provider.Service> i = set.iterator();
while (i.hasNext()) {
Provider.Service s = i.next();
System.out.println(s.getType() + "." + s.getAlgorithm());
try {
s.newInstance(null);
} catch (NoSuchAlgorithmException e) {
System.out.println(" check");
Throwable t = e.getCause();
if (!(t instanceof InvalidAlgorithmParameterException)) {
// Some engines require certain parameters to be
// present on creation. Calling newInstance(null) will
// trigger this exception and it's OK.
throw e;
}
}
}
}
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6455351 8130181
* @summary Make sure the Provider.info entries have the correct values
* after going through serialization/deserialization.
* @author Valerie Peng
*/
import java.io.*;
import java.security.*;
import java.util.*;
public class ProviderInfoCheck {
public static void main(String[] args) throws Exception {
Provider p = new SampleProvider();
// Serialize and deserialize the above Provider object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(p);
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Provider p2 = (Provider) ois.readObject();
ois.close();
checkProviderInfoEntries(p2);
}
private static void checkProviderInfoEntries(Provider p)
throws Exception {
String value = (String) p.get("Provider.id name");
if (!SampleProvider.NAME.equalsIgnoreCase(value) ||
!p.getName().equalsIgnoreCase(value)) {
throw new Exception("Test Failed: incorrect name!");
}
value = (String) p.get("Provider.id info");
if (!SampleProvider.INFO.equalsIgnoreCase(value) ||
!p.getInfo().equalsIgnoreCase(value)) {
throw new Exception("Test Failed: incorrect info!");
}
value = (String) p.get("Provider.id className");
if (!p.getClass().getName().equalsIgnoreCase(value)) {
throw new Exception("Test Failed: incorrect className!");
}
value = (String) p.get("Provider.id version");
if (!SampleProvider.VERSION.equalsIgnoreCase(value) ||
p.getVersionStr() != value) {
throw new Exception("Test Failed: incorrect versionStr!");
}
System.out.println("Test Passed");
}
private static class SampleProvider extends Provider {
static String NAME = "Sample";
static String VERSION = "1.1";
static String INFO = "Good for nothing";
SampleProvider() {
super(NAME, VERSION, INFO);
}
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2013, 2025, 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.
*/
import java.security.Provider;
import java.security.Security;
import java.lang.Exception;
/*
* @test
* @bug 8030823 8130696 8196414
* @run main/othervm ProviderVersionCheck
* @summary Verify all providers in the default Providers list have the proper
* version for the release
* @author Anthony Scarpino
*/
public class ProviderVersionCheck {
public static void main(String arg[]) throws Exception{
boolean failure = false;
for (Provider p: Security.getProviders()) {
System.out.print(p.getName() + " ");
if (p.getName().equals(System.getProperty("test.provider.name"))) {
// Version numbers of non JDK-providers do not match JDK version number.
continue;
}
String specVersion = System.getProperty("java.specification.version");
if (p.getVersion() != Double.parseDouble(specVersion)) {
System.out.println("failed. " + "Version received was " +
p.getVersion());
failure = true;
} else {
System.out.println("passed.");
}
}
if (failure) {
throw new Exception("Provider(s) failed to have the expected " +
"version value.");
}
}
}

View file

@ -0,0 +1,192 @@
/*
* Copyright (c) 1998, 2025, 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 4190873 7054918 8130181
* @library /test/lib
* @summary Make sure provider instance can be removed from list of registered
* providers, and "entrySet", "keySet", and "values" methods don't loop
* indefinitely.
*/
import java.security.*;
import java.util.*;
import jdk.test.lib.security.ProvidersSnapshot;
public class RemoveProvider {
public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
// Add provider 1
Provider p1 = new MyProvider("name1","1","");
Security.addProvider(p1);
// Add provider 2
Provider p2 = new MyProvider("name2","1","");
Security.addProvider(p2);
// List all providers
System.out.println("// List all providers");
Provider[] provs = Security.getProviders();
for (int i=0; i<provs.length; i++)
System.out.println(provs[i].toString());
// Remove one provider and list all remaining providers
System.out.println("");
System.out.println("// Remove one provider");
Security.removeProvider("name1");
provs = Security.getProviders();
for (int i=0; i<provs.length; i++)
System.out.println(provs[i].toString());
// Iterate over the entrySet
System.out.println("");
System.out.println("// Iterate over entrySet");
Map.Entry me = null;
Set es = p1.entrySet();
Iterator i = es.iterator();
while (i.hasNext()) {
me = (Map.Entry)i.next();
System.out.println("Key: " + (String)me.getKey());
System.out.println("Value: " + (String)me.getValue());
}
// Try to modify the backing Map, and catch the expected exception
try {
me.setValue("name1.mac");
throw new Exception("Expected exception not thrown");
} catch (UnsupportedOperationException uoe) {
System.out.println("Expected exception caught");
}
// Iterate over the keySet, and try to remove one (should fail)
System.out.println("");
System.out.println("// Iterate over keySet");
Object o = null;
Set ks = p1.keySet();
i = ks.iterator();
while (i.hasNext()) {
o = i.next();
System.out.println((String)o);
}
try {
ks.remove(o);
throw new Exception("Expected exception not thrown");
} catch (UnsupportedOperationException uoe) {
}
// Iterate over the map values
System.out.println("");
System.out.println("// Iterate over values");
Collection c = p1.values();
i = c.iterator();
while (i.hasNext()) {
System.out.println((String)i.next());
}
// Modify provider and make sure changes are reflected in
// existing entrySet (i.e., make sure entrySet is "live").
// First, add entry to provider.
System.out.println("");
System.out.println("// Add 'Cipher' entry to provider");
p1.put("Cipher", "name1.des");
// entrySet
i = es.iterator();
boolean found = false;
while (i.hasNext()) {
me = (Map.Entry)i.next();
System.out.println("Key: " + (String)me.getKey());
System.out.println("Value: " + (String)me.getValue());
if (((String)me.getKey()).equals("Cipher"))
found = true;
}
if (!found)
throw new Exception("EntrySet not live");
// keySet
i = ks.iterator();
while (i.hasNext()) {
o = i.next();
System.out.println((String)o);
}
// collection
i = c.iterator();
while (i.hasNext()) {
System.out.println((String)i.next());
}
// Remove entry from provider
System.out.println("");
System.out.println("// Remove 'Digest' entry from provider");
p1.remove("Digest");
// entrySet
i = es.iterator();
while (i.hasNext()) {
me = (Map.Entry)i.next();
System.out.println("Key: " + (String)me.getKey());
System.out.println("Value: " + (String)me.getValue());
}
// keySet
i = ks.iterator();
while (i.hasNext()) {
o = i.next();
System.out.println((String)o);
}
// collection
i = c.iterator();
while (i.hasNext()) {
System.out.println((String)i.next());
}
// Retrieve new entrySet and make sure the backing Map cannot be
// mofified
es = p1.entrySet();
i = es.iterator();
while (i.hasNext()) {
me = (Map.Entry)i.next();
System.out.println("Key: " + (String)me.getKey());
System.out.println("Value: " + (String)me.getValue());
}
try {
me.setValue("name1.mac");
throw new Exception("Expected exception not thrown");
} catch (UnsupportedOperationException uoe) {
System.out.println("Expected exception caught");
}
}
}
class MyProvider extends Provider {
public MyProvider(String name, String version, String info) {
super(name, version, info);
put("Signature", name+".signature");
put("Digest", name+".digest");
}
}

View file

@ -0,0 +1,387 @@
/*
* Copyright (c) 2015, 2024, 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.
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.Security;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.stream.Stream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Builder;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.JarUtils;
import jdk.test.lib.util.ModuleInfoWriter;
/*
* @test
* @bug 8130360 8183310
* @summary Test security provider in different combination of modular option
* defined with(out) service description.
* @modules java.base/jdk.internal.module
* @library /test/lib
* @build jdk.test.lib.util.JarUtils
* jdk.test.lib.util.ModuleInfoWriter
* TestProvider TestClient
* @run main SecurityProviderModularTest CL true
* @run main SecurityProviderModularTest CL false
* @run main SecurityProviderModularTest SL true
* @run main SecurityProviderModularTest SL false
* @run main SecurityProviderModularTest SPN true
* @run main SecurityProviderModularTest SPN false
* @run main SecurityProviderModularTest SPT true
* @run main SecurityProviderModularTest SPT false
*/
public class SecurityProviderModularTest {
private static final Path TEST_CLASSES
= Paths.get(System.getProperty("test.classes"));
private static final Path ARTIFACT_DIR = Paths.get("jars");
private static final Path SEC_FILE = Paths.get("java.extn.security");
private static final String PS = File.pathSeparator;
private static final String P_TYPE = "p.TestProvider";
private static final String C_TYPE = "c.TestClient";
/**
* Here is the naming convention followed.
* Test runtime arguments,
* CL - Provider class loaded through ClassLoader
* SL - Provider class to be discovered by ServiceLoader
* SPN - Provider name defined through "java.extn.security" file which
* referred through system property "java.security.properties".
* SPT - Provider type defined through "java.extn.security" file which
* referred through system property "java.security.properties".
*
* For each jar file name,
* p.jar - Unnamed provider jar.
* pd.jar - Unnamed provider jar with META-INF provider descriptor.
* mp.jar - Modular provider jar.
* mpd.jar - Modular provider jar with META-INF provider descriptor.
* msp.jar - Modular provider jar provides service through module-info.java
* mspd.jar - Modular provider jar with META-INF provider descriptor and
* provides service through module-info.java.
* c.jar - Unnamed client jar.
* mc.jar - Modular client jar.
* mcs.jar - Modular client jar uses service through module-info.java.
* amc.jar - Modular client used for automatic provider jar.
* amcs.jar - Modular client used for automatic provider jar uses service
* through module-info.java.
*/
private static final Path P_JAR = artifact("p.jar");
private static final Path PD_JAR = artifact("pd.jar");
private static final Path MP_JAR = artifact("mp.jar");
private static final Path MPD_JAR = artifact("mpd.jar");
private static final Path MSP_JAR = artifact("msp.jar");
private static final Path MSPD_JAR = artifact("mspd.jar");
private static final Path C_JAR = artifact("c.jar");
private static final Path MC_JAR = artifact("mc.jar");
private static final Path MCS_JAR = artifact("mcs.jar");
private static final Path AMC_JAR = artifact("amc.jar");
private static final Path AMCS_JAR = artifact("amcs.jar");
private static final Map<String, String> MSG_MAP = new HashMap<>();
static {
/*
* This mapping help process finding expected message based
* on the key passed as argument while executing java command.
*/
MSG_MAP.put("NoAccess", "cannot access class p.TestProvider");
MSG_MAP.put("Success", "Client: found provider TestProvider");
MSG_MAP.put("NoProvider", "Provider TestProvider not found");
}
private final String addUNArg;
private final String addNMArg;
private final String cArg;
private final String unnP;
private final String modP;
private final String unnC;
private final String modC;
private final String autoMC;
private final String expModRes;
private final String expAModRes;
// Common set of VM arguments used in all test cases
private final List<String> commonArgs;
public SecurityProviderModularTest(String use, boolean metaDesc) {
List<String> argList = new LinkedList<>();
argList.add("-Duser.language=en");
argList.add("-Duser.region=US");
final boolean useSL = "SL".equals(use) || "SPN".equals(use);
final boolean useCL = "CL".equals(use);
final boolean useSPT = "SPT".equals(use);
final boolean useSP = use.startsWith("SP");
/* Use Security property file when the provider expected to
* loaded through Security property file. */
if (useSP) {
/* Create a java.security file to specify the new provider.
* java.security file extension can be provided using
* "-Djava.security.properties" VM argument at runtime.*/
createJavaSecurityFileExtn("SPN".equals(use));
argList.add("-Djava.security.properties=" + toAbsPath(SEC_FILE));
}
commonArgs = Collections.unmodifiableList(argList);
cArg = (useCL) ? P_TYPE : "TestProvider";
addUNArg = (useSL) ? "" : ("--add-modules="
+ ((metaDesc) ? "pd" : "p"));
addNMArg = (useSL) ? "" : "--add-modules=mp";
// Based on Testcase, select unnamed/modular jar files to use.
unnP = toAbsPath((metaDesc) ? PD_JAR : P_JAR);
modP = toAbsPath(useSL ? (metaDesc ? MSPD_JAR : MSP_JAR)
: (metaDesc ? MPD_JAR : MP_JAR));
unnC = toAbsPath(C_JAR);
modC = toAbsPath(useSL ? MCS_JAR : MC_JAR);
autoMC = toAbsPath(useSL ? AMCS_JAR : AMC_JAR);
expModRes = "Success";
expAModRes = (useSPT | useCL) ? "Success"
: (metaDesc) ? "Success" : "NoProvider";
String loadByMsg = useSP ? "SecurityPropertyFile"
: ((useCL) ? "ClassLoader" : "ServiceLoader");
System.out.printf("%n*** Providers loaded through %s and includes"
+ " META Descriptor: %s ***%n%n", loadByMsg, metaDesc);
}
/*
* Test cases are based on the following logic,
* for (ProviderLoadedThrough : {"ServiceLoader", "ClassLoader",
* "SecurityPropertyFile"}) {
* for (definedWith : {"METAINFService", "WithoutMETAINFService"}) {
* for (clientType : {"NAMED", "AUTOMATIC", "UNNAMED"}) {
* for (providerType : {"NAMED", "AUTOMATIC", "UNNAMED"}) {
* Create and run java command for each possible case
* }
* }
* }
* }
*/
public static void main(String[] args) throws Exception {
// Generates unnamed and modular jars.
setUp();
boolean metaDesc = Boolean.valueOf(args[1]);
SecurityProviderModularTest test
= new SecurityProviderModularTest(args[0], metaDesc);
test.process(args[0]);
}
private void process(String use) throws Exception {
// Case: NAMED-NAMED, NAMED-AUTOMATIC, NAMED-UNNAMED
System.out.printf("Case: Modular Client and Modular Provider");
execute(String.format("--module-path %s%s%s -m mc/%s %s %s",
modC, PS, modP, C_TYPE, use, cArg), expModRes);
System.out.printf("Case: Modular Client and automatic Provider");
execute(String.format("--module-path %s%s%s %s -m mc/%s %s %s", autoMC,
PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes);
System.out.printf("Case: Modular Client and unnamed Provider");
execute(String.format("--module-path %s -cp %s -m mc/%s %s %s", autoMC,
unnP, C_TYPE, use, cArg), expAModRes);
// Case: AUTOMATIC-NAMED, AUTOMATIC-AUTOMATIC, AUTOMATIC-UNNAMED
System.out.printf("Case: Automatic Client and modular Provider");
execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC,
PS, modP, addNMArg, C_TYPE, use, cArg), expModRes);
System.out.printf("Case: Automatic Client and automatic Provider");
execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC,
PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes);
System.out.printf("Case: Automatic Client and unnamed Provider");
execute(String.format("--module-path %s -cp %s -m c/%s %s %s", unnC,
unnP, C_TYPE, use, cArg), expAModRes);
// Case: UNNAMED-NAMED, UNNAMED-AUTOMATIC, UNNAMED-UNNAMED
System.out.printf("Case: Unnamed Client and modular Provider");
execute(String.format("-cp %s --module-path %s %s %s %s %s", unnC,
modP, addNMArg, C_TYPE, use, cArg), expModRes);
System.out.printf("Case: Unnamed Client and automatic Provider");
execute(String.format("-cp %s --module-path %s %s %s %s %s", unnC,
unnP, addUNArg, C_TYPE, use, cArg), expAModRes);
System.out.printf("Case: Unnamed Client and unnamed Provider");
execute(String.format("-cp %s%s%s %s %s %s", unnC, PS, unnP, C_TYPE,
use, cArg), expAModRes);
// Case: unnamed jars in --module-path and modular jars in -cp.
System.out.printf(
"Case: Unnamed Client and Unnamed Provider in modulepath");
execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC,
PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes);
System.out.printf(
"Case: Modular Client and Modular Provider in classpath");
execute(String.format("-cp %s%s%s %s %s %s", modC, PS, modP, C_TYPE,
use, cArg), expAModRes);
}
/**
* Execute with command arguments and process the result.
*/
private void execute(String args, String msgKey) throws Exception {
String[] safeArgs = Stream.concat(commonArgs.stream(),
Stream.of(args.split("\\s+"))).filter(s -> {
if (s.contains(" ")) {
throw new RuntimeException("No spaces in args");
}
return !s.isEmpty();
}).toArray(String[]::new);
String out = ProcessTools.executeTestJava(safeArgs).getOutput();
// Handle response.
if ((msgKey != null && out.contains(MSG_MAP.get(msgKey)))) {
System.out.printf("PASS: Expected Result: %s.%n",
MSG_MAP.get(msgKey));
} else if (out.contains("Exception") || out.contains("Error")) {
System.out.printf("OUTPUT: %s", out);
throw new RuntimeException("FAIL: Unknown Exception occured. "
+ "Expected: " + MSG_MAP.get(msgKey));
} else {
System.out.printf("OUTPUT: %s", out);
throw new RuntimeException("FAIL: Unknown Test case found");
}
}
/**
* Creates Unnamed/modular jar files for TestClient and TestClassLoader.
*/
private static void setUp() throws Exception {
if (ARTIFACT_DIR.toFile().exists()) {
System.out.println("Skipping setup: Artifacts already exists.");
return;
}
// Generate unnamed provider jar file.
JarUtils.createJarFile(P_JAR, TEST_CLASSES, "p/TestProvider.class");
// Generate unnamed client jar file.
JarUtils.createJarFile(C_JAR, TEST_CLASSES, "c/TestClient.class");
// Generate unnamed provider jar files with META-INF descriptor.
generateJar(P_JAR, PD_JAR, null, true);
Builder mBuilder = ModuleDescriptor.newModule("mp").exports("p");
// Modular provider defined as META-INF service.
generateJar(P_JAR, MPD_JAR, mBuilder.build(), true);
// Modular jar exports package to let the provider type accessible.
generateJar(P_JAR, MP_JAR, mBuilder.build(), false);
mBuilder = ModuleDescriptor.newModule("mp")
.provides("java.security.Provider", Arrays.asList(P_TYPE));
// Modular provider Service in module-info does not need to export
// its package.
generateJar(P_JAR, MSP_JAR, mBuilder.build(), false);
// Modular provider Service in module-info also have META-INF descriptor
generateJar(P_JAR, MSPD_JAR, mBuilder.build(), true);
mBuilder = ModuleDescriptor.newModule("mc").exports("c");
// Generate modular client jar file to use automatic provider jar.
generateJar(C_JAR, AMC_JAR, mBuilder.build(), false);
// Generate modular client jar file to use modular provider jar.
generateJar(C_JAR, MC_JAR, mBuilder.requires("mp").build(), false);
mBuilder = ModuleDescriptor.newModule("mc").exports("c")
.uses("java.security.Provider");
// Generate modular client jar file to use automatic provider service.
generateJar(C_JAR, AMCS_JAR, mBuilder.build(), false);
// Generate modular client jar file using modular provider service.
generateJar(C_JAR, MCS_JAR, mBuilder.requires("mp").build(), false);
}
/**
* Update Unnamed jars and include descriptor files.
*/
private static void generateJar(Path sjar, Path djar,
ModuleDescriptor mDesc, boolean metaDesc) throws Exception {
Files.copy(sjar, djar, StandardCopyOption.REPLACE_EXISTING);
Path dir = Files.createTempDirectory("tmp");
if (metaDesc) {
write(dir.resolve(Paths.get("META-INF", "services",
"java.security.Provider")), P_TYPE);
}
if (mDesc != null) {
Path mi = dir.resolve("module-info.class");
try (OutputStream out = Files.newOutputStream(mi)) {
ModuleInfoWriter.write(mDesc, out);
}
System.out.format("Added 'module-info.class' in '%s'%n", djar);
}
JarUtils.updateJarFile(djar, dir);
}
/**
* Look for file path in generated jars.
*/
private static Path artifact(String file) {
return ARTIFACT_DIR.resolve(file);
}
/**
* Convert to absolute file path.
*/
private static String toAbsPath(Path path) {
return path.toFile().getAbsolutePath();
}
/**
* Create the parent directories if missing to ensure the path exist.
*/
private static Path ensurePath(Path at) throws IOException {
Path parent = at.getParent();
if (parent != null && !parent.toFile().exists()) {
ensurePath(parent);
}
return Files.createDirectories(parent);
}
/**
* Generates service descriptor inside META-INF folder.
*/
private static void write(Path at, String content) throws IOException {
ensurePath(at);
Files.write(at, content.getBytes("UTF-8"));
}
/**
* Create new provider entry through java.security file extension.
* New provider entry will be the last entry inside the JRE.
*/
private static void createJavaSecurityFileExtn(boolean useName) {
int insertAt = Security.getProviders().length + 1;
String provider = (useName ? "TestProvider" : P_TYPE);
try {
Files.write(SEC_FILE, String.format("security.provider.%s=%s",
insertAt, provider).getBytes("UTF-8"));
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.printf("Security property file created at: %s with value:"
+ " %s%n", SEC_FILE, provider);
}
}

View file

@ -0,0 +1,150 @@
/*
* Copyright (c) 2003, 2024, 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 4911081 8130181
* @library /test/lib
* @summary verify that Provider.Service.supportsParameter() works
* @author Andreas Sterbenz
*/
import java.security.*;
import java.security.Provider.Service;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import jdk.test.lib.security.SecurityUtils;
public class SupportsParameter {
public static void main(String[] args) throws Exception {
String kpgAlgorithm = "DSA";
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgorithm);
kpg.initialize(SecurityUtils.getTestKeySize(kpgAlgorithm));
KeyPair kp = kpg.generateKeyPair();
PublicKey dsaPublicKey = kp.getPublic();
PrivateKey dsaPrivateKey = kp.getPrivate();
PublicKey myPublicKey = new MyPublicKey();
PrivateKey myPrivateKey = new MyPrivateKey();
SecretKey mySecretKey = new MySecretKey();
Provider p = new MyProvider();
Service s;
// none specified, always true
s = p.getService("Signature", "DSA0");
checkSupports(s, null, true);
checkSupports(s, dsaPublicKey, true);
checkSupports(s, dsaPrivateKey, true);
checkSupports(s, myPublicKey, true);
checkSupports(s, myPrivateKey, true);
checkSupports(s, mySecretKey, true);
// DSAPublic/PrivateKey specified as classes
s = p.getService("Signature", "DSA");
checkSupports(s, dsaPublicKey, true);
checkSupports(s, dsaPrivateKey, true);
checkSupports(s, myPublicKey, false);
checkSupports(s, myPrivateKey, false);
checkSupports(s, mySecretKey, false);
// X.509/PKCS#8 specified as formats
s = p.getService("Signature", "DSA2");
checkSupports(s, dsaPublicKey, true);
checkSupports(s, dsaPrivateKey, true);
checkSupports(s, myPublicKey, false);
checkSupports(s, myPrivateKey, false);
checkSupports(s, mySecretKey, false);
// MyPublic/PrivateKey + DSAPublicKey specified as classes
s = p.getService("Signature", "DSA3");
checkSupports(s, dsaPublicKey, true);
checkSupports(s, dsaPrivateKey, false);
checkSupports(s, myPublicKey, true);
checkSupports(s, myPrivateKey, true);
checkSupports(s, mySecretKey, false);
// MyPublic/PrivateKey + DSAPublicKey specified as classes
s = p.getService("Cipher", "DES");
checkSupports(s, dsaPublicKey, false);
checkSupports(s, dsaPrivateKey, false);
checkSupports(s, myPublicKey, false);
checkSupports(s, myPrivateKey, false);
checkSupports(s, mySecretKey, true);
Key secretKeySpec = new SecretKeySpec(new byte[8], "DES");
checkSupports(s, secretKeySpec, true);
}
private static void checkSupports(Service s, Key key, boolean r) throws Exception {
if (s.supportsParameter(key) != r) {
throw new Exception("Result mismatch");
}
System.out.println("Passed");
}
private static class MyProvider extends Provider {
MyProvider() {
super("MyProvider", "1.0", "MyProvider");
put("Signature.DSA0", "foo.DSA0");
put("Signature.DSA", "foo.DSA");
put("Signature.DSA SupportedKeyClasses",
"java.security.interfaces.DSAPublicKey" +
"|java.security.interfaces.DSAPrivateKey");
put("Signature.DSA2", "foo.DSA2");
put("Signature.DSA2 SupportedKeyFormats", "X.509|PKCS#8");
put("Signature.DSA3", "foo.DSA3");
put("Signature.DSA3 SupportedKeyClasses",
"SupportsParameter$MyPrivateKey" +
"|SupportsParameter$MyPublicKey" +
"|java.security.interfaces.DSAPublicKey");
put("Cipher.DES", "foo.DES");
put("Cipher.DES SupportedKeyFormats", "RAW");
put("Cipher.DES SupportedKeyClasses", "SupportsParameter$MySecretKey");
}
}
private static class MyKey implements Key {
public String getAlgorithm() { return "FOO"; }
public String getFormat() { return null; }
public byte[] getEncoded() { return null; }
}
private static class MyPrivateKey extends MyKey implements PrivateKey { }
private static class MyPublicKey extends MyKey implements PublicKey {}
private static class MySecretKey extends MyKey implements SecretKey {
public String getAlgorithm() { return "DES"; }
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2015, 2017, 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.
*/
package c;
import java.security.Provider;
import java.security.Security;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* A Test client using different mechanism to search the custom security
* provider. It uses ClassLoader, ServiceLoader and default mechanism to find
* a provider registered through "java.security" extension file.
*/
public class TestClient {
public static void main(String[] args) throws Exception {
Provider p = null;
if (args != null && args.length > 1) {
switch (args[0]) {
case "CL":
p = (Provider) Class.forName(args[1]).newInstance();
if (Security.addProvider(p) == -1) {
throw new RuntimeException("Failed to add provider");
}
break;
case "SL":
ServiceLoader<Provider> services
= ServiceLoader.load(java.security.Provider.class);
Iterator<Provider> iterator = services.iterator();
while (iterator.hasNext()) {
Provider spr = iterator.next();
if (spr.getName().equals(args[1])) {
p = spr;
if (Security.addProvider(p) == -1) {
throw new RuntimeException(
"Failed to add provider");
}
break;
}
}
break;
case "SPN":
case "SPT":
p = Security.getProvider(args[1]);
break;
default:
throw new RuntimeException("Invalid argument.");
}
}
if (p == null) {
throw new RuntimeException("Provider TestProvider not found");
}
System.out.printf("Client: found provider %s", p.getName());
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2015, 2017, 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.
*/
package p;
import java.security.Provider;
/**
* Custom Security provider for modular test.
*/
public final class TestProvider extends Provider {
public TestProvider() {
super("TestProvider", "1.0", "Test Security provider");
System.out.println(String.format("TEST Security provider loaded"
+ " successfully : %s", this.toString()));
}
@Override
public String toString() {
return "TestProvider [getName()=" + getName()
+ ", getVersion()=" + getVersionStr() + ", getInfo()="
+ getInfo() + ", toString()=" + super.toString() + "]";
}
}

View file

@ -0,0 +1,119 @@
/*
* Copyright (c) 2005, 2022, 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 6220064 7054918 8130181
* @summary make sure everything works ok in the Turkish local (dotted/dotless i problem)
* @author Andreas Sterbenz
*/
import java.util.*;
import java.security.*;
import java.security.Provider.Service;
import javax.crypto.*;
public class Turkish {
public static void main(String[] args) throws Exception {
Provider p1 = new TProvider("T1");
System.out.println(p1.getServices()); // trigger service parsing
Locale loc = Locale.getDefault();
try {
Locale.setDefault(Locale.of("tr", "TR"));
Provider p2 = new TProvider("T2");
System.out.println(p2.getServices()); // trigger service parsing
System.out.println(Signature.getInstance("MD5withRSA"));
System.out.println(Signature.getInstance("md5withrsa"));
System.out.println(Signature.getInstance("MD5WITHRSA"));
Service s1, s2;
s1 = p1.getService("Signature", "MD5withRSA");
check(s1, null);
check(s1, p1.getService("Signature", "md5withrsa"));
check(s1, p1.getService("Signature", "MD5WITHRSA"));
check(s1, p1.getService("Signature", "MD5RSA"));
check(s1, p1.getService("Signature", "md5rsa"));
check(s1, p1.getService("Signature", "MD5rsa"));
s1 = p1.getService("Signature", "SHAwithRSA");
check(s1, null);
check(s1, p1.getService("Signature", "shawithrsa"));
check(s1, p1.getService("Signature", "SHAWITHRSA"));
check(s1, p1.getService("Signature", "SHARSA"));
check(s1, p1.getService("Signature", "sharsa"));
check(s1, p1.getService("Signature", "SHArsa"));
check(s1, p1.getService("Signature", "SHA1RSA"));
check(s1, p1.getService("Signature", "sha1rsa"));
check(s1, p1.getService("Signature", "SHA1rsa"));
s1 = p2.getService("Signature", "MD5withRSA");
check(s1, null);
check(s1, p2.getService("Signature", "md5withrsa"));
check(s1, p2.getService("Signature", "MD5WITHRSA"));
check(s1, p2.getService("Signature", "MD5RSA"));
check(s1, p2.getService("Signature", "md5rsa"));
check(s1, p2.getService("Signature", "MD5rsa"));
s1 = p2.getService("Signature", "SHAwithRSA");
check(s1, null);
check(s1, p2.getService("Signature", "shawithrsa"));
check(s1, p2.getService("Signature", "SHAWITHRSA"));
check(s1, p2.getService("Signature", "SHARSA"));
check(s1, p2.getService("Signature", "sharsa"));
check(s1, p2.getService("Signature", "SHArsa"));
check(s1, p2.getService("Signature", "SHA1RSA"));
check(s1, p2.getService("Signature", "sha1rsa"));
check(s1, p2.getService("Signature", "SHA1rsa"));
System.out.println("OK");
} finally {
Locale.setDefault(loc);
}
}
private static void check(Service s1, Service s2) throws Exception {
System.out.println(s1);
if (s1 == null) {
throw new Exception("service is null");
}
if ((s2 != null) && (s1 != s2)) {
throw new Exception("service does not match");
}
}
private static class TProvider extends Provider {
TProvider(String name) {
super(name, "1.0", null);
put("Signature.MD5withRSA", "com.foo.Sig");
put("Alg.Alias.Signature.MD5RSA", "MD5withRSA");
put("sIGNATURE.shaWITHrsa", "com.foo.Sig");
put("aLG.aLIAS.sIGNATURE.sharsa", "shaWITHrsa");
put("aLG.aLIAS.sIGNATURE.sha1rsa", "shawithrsa");
}
}
}